使用openfeign传递oauth2令牌

通过RequestInterceptor拦截Feign请求并装填OAuth2 Token

public class OAuth2FeignRequestInterceptor implements RequestInterceptor {
    private static final String AUTHORIZATION_HEADER = "Authorization";

    private static final String BEARER_TOKEN_TYPE = "Bearer";

    private final OAuth2RestTemplate oAuth2RestTemplate;

    public OAuth2FeignRequestInterceptor(OAuth2RestTemplate oAuth2RestTemplate) {
        this.oAuth2RestTemplate = oAuth2RestTemplate;
    }

    @Override
    public void apply(RequestTemplate requestTemplate) {
        requestTemplate.header(AUTHORIZATION_HEADER,
                String.format("%s %s",
                        BEARER_TOKEN_TYPE,
                        oAuth2RestTemplate.getAccessToken().toString()));
    }
}

上面的方法通过OAuth2RestTemplate获取token, 也可以直接从请求中获取token

RequestAttributes requestAttributes = RequestContextHolder.currentRequestAttributes();
if (requestAttributes != null) {
  HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();
  String token = request.getHeader("Authorization");
  if(StringUtils.isBlank(token)){
  	token = String.format("%s %s",
	    "Bearer",
	    request.getParameter("access_token")));
  }
  ...
}

posted on 2022-04-11 22:39  路过君  阅读(185)  评论(0编辑  收藏  举报

导航