spring cloud微服務增加oauth2權限后 feign調用報null錯誤


spring cloud微服務增加oauth2權限后 feign調用報null錯誤

​ 在授權服務里,用戶通過用戶名密碼,或者手機和驗證碼等方式登陸之后,在http頭里會有授權的標識,在客戶端調用時,需要添加當時有效的token才可以正常訪問被授權的頁面。

Content-Type:application/json
Authorization:Bearer d79c064c-8675-4047-a119-fac692e447e8

​ 而在業務層里,服務與服務之間使用feign來實現調用,而授權的代碼我們可以通過攔截器實現,在feign請求之前,把當前服務的token添加到目標服務的請求頭就可以了,一般是這樣實現的。

/**
 * 發送FeignClient設置Header信息.
 * http://www.itmuch.com/spring-cloud-sum/hystrix-threadlocal/
 * Hystrix傳播ThreadLocal對象
 */
@Component
public class TokenFeignClientInterceptor implements RequestInterceptor {
  /**
   * token放在請求頭.
   *
   * @param requestTemplate 請求參數
   */
  @Override
  public void apply(RequestTemplate requestTemplate) {
    RequestAttributes requestAttributes = RequestContextHolder.currentRequestAttributes();
    if (requestAttributes != null) {
      HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();
      requestTemplate.header("Authorization", request.getHeader("Authorization"));
    }
  }
}

​ 上面的攔截器代碼沒有什么問題,也很好理解,但事實上,當你的feign開啟了hystrix功能,如果開啟了,需要把hystrix的策略進行修改,默認是THREAD的,這個級別時ThreadLocal是空的,所以你的授權不能傳給feign的攔截器.

hystrix: 
	command: 
		default: 
			execution: 
				isolation: 
					strategy: SEMAPHORE 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM