zoukankan      html  css  js  c++  java
  • Feign解决服务之间调用传递token

    现在的微服务基本就是SpringSecurity+Oauth2做的授权和认证,假如多个服务直接要通过Fegin来调用,会报错401

    a、有做权限处理的服务接口直接调用会造成调用时出现http 401未授权的错误,继而导致最终服务的http 500内部服务器错误

    b、解决方式:最方便的就是往请求头里加上token,一起带过去;

    Feign有提供一个接口,RequestInterceptor;只要实现这个接口,简单做一些处理,比如说我们验证请求头的token叫Access-Token,我们就先取出当前请求的token,然后放到feign请求头上;

    public class FeignConfig implements RequestInterceptor {
            @Override
            public void apply(RequestTemplate requestTemplate) {
                ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
                HttpServletRequest request = attributes.getRequest();
                //添加token
                requestTemplate.header(HttpHeaders.AUTHORIZATION, request.getHeader(HttpHeaders.AUTHORIZATION));
            }
        }
        调用方式
        @FeignClient(name = "qtjuaa", configuration = FeignConfig.class)
        public interface UaaClient {
            @RequestMapping(value = "/api/test", method= RequestMethod.GET)
            String test();
        }

     

  • 相关阅读:
    SimpleCursorAdapter的使用
    sizeof和strlen的区别和联系总结
    设计模式-工厂方法模式
    Python第四章-字典
    Python第四章-字典
    Python第三章-字符串
    Python第三章-字符串
    Python 第二章-列表和元组
    Python 第二章-列表和元组
    设计模式-简单工厂模式
  • 原文地址:https://www.cnblogs.com/dalianpai/p/12426425.html
Copyright © 2011-2022 走看看