feign传递oauth2 token问题

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

feign传递oauth2 token问题

张占岭   2022-05-28 我要评论

feign之间传递oauth2 token问题

在微服务架构里,服务与服务之间的调用一般用feign就可以实现,它是一种可视化的rpc,并且集成了ribbon的负载均衡能力,所以很受欢迎。

授权服务

在授权服务里,用户通过用户名密码,或者手机和验证码等方式登陆之后,在http头里会有授权的标识,在客户端调用时,需要添加当时有效的token才可以正常访问被授权的页面。

Content-Type:application/jsonAuthorization: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的请求头传递信息进行讲解分享给大家,各位多注意下!

oauth2 feign报401的错误

报错问题:

feign.FeignException: status 401 reading UserFeign#queryUser(Long,String,String,String,Integer,Integer,Integer)

解决方法

import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.provider.authentication.OAuth2AuthenticationDetails;
@Configuration
public class FeignOauth2RequestInterceptor implements RequestInterceptor {
    private final String AUTHORIZATION_HEADER = "Authorization";
    private final String BEARER_TOKEN_TYPE = "Bearer";
    @Override
    public void apply(RequestTemplate requestTemplate) {
        SecurityContext securityContext = SecurityContextHolder.getContext();
        Authentication authentication = securityContext.getAuthentication();
        if (authentication != null && authentication.getDetails() instanceof OAuth2AuthenticationDetails) {
            OAuth2AuthenticationDetails details = (OAuth2AuthenticationDetails) authentication.getDetails();
            requestTemplate.header(AUTHORIZATION_HEADER, String.format("%s %s", BEARER_TOKEN_TYPE, details.getTokenValue()));
        }
    }
}

以上为个人经验,希望能给大家一个参考,也希望大家多多支持。

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们