微服务中怎么通过Feign实现密码安全认证

发布时间:2021-06-30 14:14:40 作者:Leah
来源:亿速云 阅读:267

本篇文章为大家展示了微服务中怎么通过Feign实现密码安全认证,内容简明扼要并且容易理解,绝对能使你眼前一亮,通过这篇文章的详细介绍希望你能有所收获。

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

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实现密码安全认证

微服务中怎么通过Feign实现密码安全认证

那么,既然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注解注入进来即可

上述内容就是微服务中怎么通过Feign实现密码安全认证,你们学到知识或技能了吗?如果还想学到更多技能或者丰富自己的知识储备,欢迎关注亿速云行业资讯频道。

推荐阅读:
  1. Python如何通过kerberos安全认证操作kafka
  2. 使用Feign怎么实现微服务间文件下载

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

微服务 feign

上一篇:php中有哪些魔幻方法

下一篇:怎么使用docker compose安装harbor私有仓库

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》