在微服務架構里,服務與服務之間的調用一般用feign就可以實現,它是一種可視化的rpc,並且集成了ribbon的負載均衡能力,所以很受歡迎。
授權服務
在授權服務里,用戶通過用戶名密碼,或者手機和驗證碼等方式登陸之后,在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();
String token = request.getHeader(TokenContext.KEY_OAUTH2_TOKEN);
requestTemplate.header(TokenContext.KEY_OAUTH2_TOKEN,
new String[] {token});
}
}
}
上面的攔截器代碼沒有什么問題,也很好理解,但事實上,當你的feign開啟了hystrix功能,如果開啟了,需要把hystrix的策略進行修改,默認是THREAD
的,這個級別時ThreadLocal是空的,所以你的授權不能傳給feign的攔截器.
hystrix.command.default.execution.isolation.strategy: SEMAPHORE
資源項目里獲取當前用戶
在另一個項目,需要其它獲取當前用戶,需要使用下面的代碼。
- 先配置一個授權的地址
security:
oauth2:
resource:
id: user
user-info-uri: http://${auth.host:localhost}:${auth.port:8002}/user # 這里是授權服務的地址,即auth-service
prefer-token-info: false
auth:
host: localhost #這個不可以用eureka里的服務名,只能使用docker-compose里的服務名
port: 8002
- 下面的代碼用來獲取當前用戶
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
String user = objectMapper.writeValueAsString(authentication.getPrincipal());
本講主要對feign的請求頭傳遞信息進行講解,開發時遇到的坑總節了一下,分享給大家!