您的位置:首页 > 教程文章 > 编程开发

微服务通过Feign调用进行密码安全认证操作

:0 :2021-10-22 18:40:03

微服务通过Feign调用进行密码安全认证
在项目中,微服务之间的通信也是通过Feign的HTTP客户端通信,为了保护我们的业务微服务不被其他非法未经允许的服务调用, 我们要进行访问授权配置!
Feign是客户端配置,@FeignClient注解有个configuation属性,可以配置我们自定义的配置类,在此类中注入微服务认证拦截器
  /**
     * 访问微服务需要密码
     * @return
     */
    @Bean
    public FeignBasicAuthRequestInterceptor requestInterceptor(){
        System.out.println("------>进入微服务认证拦截器");
        return new FeignBasicAuthRequestInterceptor();
    }
feign内部有自带的BasicAuthRequestInterceptor类实现了RequestInterceptor接口,接收username,password参数,并将此参数通过apply方法设置到了请求头中
public void apply(RequestTemplate template) {
        template.header("Authorization", new String[]{this.headerValue});
    }
由此我们可知,我们可以自定义类实现RequestInterceptor接口,重写apply方法,添加我们的认证逻辑,也同样通过RequestTemplate就token设置到请求头中!
启动两个微服务,打印日志信息,两个微服务各自的控制台都打印,证明认证拦截器配置成功,通过Spring容器加载成功
那么,既然feign是客户端配置,那么客户端只要知道了所需调用微服务的rest就可以不配置这个拦截器也能访问,上述代码并没有达到保护业务服务资源的作用,"调用我必须需要密码"这一行为应该是由微服务强制要求才是!那么微服务在什么地方制定这个规则呢?
仔细阅读BasicAuthRequestInterceptor源码便知客户端将密码设置到了请求头中,feign是模拟HTTP请求到微服务拿取资源,那么微服务就可以通过配置过滤器来过滤所有经过"我"的请求,微服务在过滤器拿到客户端请求的header就可以开始我们的认证逻辑了!
比较简单的认证就是各自的微服务通过application.yml配置访问所需的账号密码,将这个账号密码告诉授信用的调用方,调用方设置feign拦截器将账号密码注入到header中!也可以进行加密传输,过滤器再进行解密
微服务过滤器注意对响应设置编码,否则输出中文会乱码
 httpResponse.setCharacterEncoding("UTF-8");
 httpResponse.setContentType("application/json;charset=utf-8");
 PrintWriter print = httpResponse.getWriter();
可以将过滤器抽取在公共类中,否则每个微服务都要配一个过滤器
微服务之间调用部分Feign接口忽略认证授权
在SpringSecurity框架基础之上实现微服务之间部分接口忽略认证授权.
思路
创建忽略授权注解
获取所有被注解的类或者方法
在SpringSecurity框架中忽略授权
1. 创建忽略授权注解
@Target({ElementType.TYPE,ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface AuthIgnore {
}
2. 获取所有被注解的类或者方法
@Slf4j
@Configuration
public class AuthIgnoreConfig implements InitializingBean {
    @Autowired
    private ApplicationContext applicationContext;
    private static final Pattern PATTERN = Pattern.compile("\{(.*?)\}");
    private static final String ASTERISK = "*";
    @Getter
    @Setter
    private List<String> ignoreUrls = new ArrayList<>();
    @Override
    public void afterPropertiesSet(){
        RequestMappingHandlerMapping mapping = applicationContext.getBean(RequestMappingHandlerMapping.class);
        Map<RequestMappingInfo, HandlerMethod> map = mapping.getHandlerMethods();
        map.keySet().forEach(mappingInfo -> {
            HandlerMethod handlerMethod = map.get(mappingInfo);
            AuthIgnore method = AnnotationUtils.findAnnotation(handlerMethod.getMethod(), AuthIgnore.class);
            Optional.ofNullable(method)
                    .ifPresent(authIgnore -> mappingInfo
                            .getPatternsCondition()
                            .getPatterns()
                            .forEach(url -> ignoreUrls.add(ReUtil.replaceAll(url, PATTERN, ASTERISK))));
        });
        Optional.ofNullable(applicationContext.getBeansWithAnnotation(AuthIgnore.class))
                .ifPresent(stringObjectMap -> stringObjectMap.values()
                    .forEach(object -> Arrays.asList(object.getClass().getInterfaces()[0].getDeclaredMethods()).forEach(method -> {
                        List<Annotation> annotations = Arrays.asList(method.getAnnotation(RequestMapping.class), method.getAnnotation(PostMapping.class),
                                method.getAnnotation(GetMapping.class));
                        annotations.forEach(annotation -> {
                            if (ObjectUtil.isNotEmpty(annotation)) {
                                try {
                                    Field field = Proxy.getInvocationHandler(annotation).getClass().getDeclaredField("memberValues");
                                    field.setAccessible(true);
                                    Map valueMap = (Map) field.get(Proxy.getInvocationHandler(annotation));
                                    String[] string = (String[])valueMap.get("value");
                                    ignoreUrls.add(StrUtil.SLASH.concat(ReUtil.replaceAll(string[0], PATTERN, ASTERISK)));
                                } catch (Exception e) {
                                   log.error(e.getMessage(),e);
                                }
                            }
                        });
                    })));
    }
}
实现InitializingBean接口后,该类初始化的时候会调用afterPropertiesSet方法
代码中的工具类统一使用的hutool工具类
3. 在SpringSecurity框架中忽略授权
@Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/**/api/**","/v2/**","/actuator/**","doc.html")
                .antMatchers(authIgnoreConfig.getIgnoreUrls().stream().distinct().toArray(String[]::new));
    }
authIgnoreConfig变量为第二步的类,使用@Autowired注解注入进来即可
最后
服务启动后自动加载所有的@AuthIgnore标注的URL给资源服务设置为忽略认证
以上为个人经验,希望能给大家一个参考,也希望大家多多支持无名。

SpringBoot处理请求参数中包含特殊符号
教你java面试时如何聊单例模式

同类资源