使用openfeign传递oauth2令牌

2020-06-19 16:43:18 浏览数 (2)

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

代码语言:javascript复制
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

代码语言:javascript复制
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")));
  }
  ...
}

0 人点赞