1,Passport作为用户统一账户(登录注册等)中心,因此客户端应当封装成统一的针对不同平台的SDK;
2,所有系统服务访问Passport,都必须携带由Passport颁发的APP统一标识appId;
3,所有系统服务访问Passport,都必须携带用户登录成功后取得的token。
- 后台服务客户端访问Passport配置
@Configuration public class CommonConfig implements RequestInterceptor, HandlerInterceptor { public static final ThreadLocal<String> Token = new ThreadLocal(); @Value("${app.id}") private String AppID; @Bean public WebMvcConfigurer webMvcConfigurer(@Autowired CommonConfig config) { return new WebMvcConfigurer(){ @Override public void addInterceptors(InterceptorRegistry registry) { // 配置需要访问UCenter的请求url String[] includePatterns = {"/**","/passport/**"}; HandlerInterceptor mappedInterceptor = new MappedInterceptor(includePatterns, null, config); registry.addInterceptor(mappedInterceptor); } }; } @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) { //将app客户端请求header中的token使用ThreadLocal缓存起来, //后续将请求转发至Passport时,获取token构造请求header String token = request.getHeader("token"); Token.set(token); return true; } @Override public void apply(RequestTemplate requestTemplate) { //所有通过 FeignClient 发出的request header都会被该构造, //为了满足2和3的要求,所有发出的请求头中加入appId和token String token = Token.get(); requestTemplate.header("appId", AppID); requestTemplate.header("token", token); } } |
如上述代码所示,定义spring boot配置类CommonConfig,并实现RequestInterceptor和HandlerInterceptor接口,分别实现
boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)和void apply(RequestTemplate requestTemplate)方。同时还要注册WebMvcConfigurer类,配置请求拦截url,并在拦截方法preHandle中缓存请求header的token。
随后,将请求转发到Passport时,在请求header里加入缓存的token和对应服务的AppID。