前言

这段时间研究微服务的认证中心,着实费了些功夫,首先要感谢很多博客,帮助到了我很多.以前我写博客主要是为了自己,更像是学习笔记.那么这次想帮助到看我博客的人
为啥说废了些功夫呢?基于spring-security-auth2的微服务认证中心,不是网上的样例一大堆吗?
难点:网上spring-security的样例大多是基于servlet的,但是我想要和gateway集成到一起,那么就不能基于servlet,而要基于webflux.webflux的底层库是Reactor(响应式编程的一个实现java库),所以首先就得去学习Reactor.

简介

大多的微服务认证这块的架构都是如下这种,每个请求都需要去认证中心去认证,这样做有个致命的缺点就是就是每次请求都需要在认证的环节耗费几百毫秒(都是在内网都需要几百毫秒).虽然微服务的划分有一个原则是职责单一化,但是原则是死的人是活的,很明显如下的架构减低了性能.所以再三考虑下,我采用了图二的架构.就是把网关和认证中心放在一个微服务中

微服务 统一身份认证 微服务 认证中心_微服务


微服务 统一身份认证 微服务 认证中心_User_02

代码

直接上代码吧 Gitee: https://gitee.com/wangwei1991/auth-central-try-parent.

你至少需要down下图中标识的项目或者pom,然后导入ide,跑其中的这三个项目,就可以试一试了

微服务 统一身份认证 微服务 认证中心_微服务_03

微服务 统一身份认证 微服务 认证中心_微服务 统一身份认证_04

说明:
1.看com.svw.asmpcloud.service.impl.UserServiceImpl 可知,我模拟了2个用户,及他们的菜单

private static Map<String,User> users = new HashMap<String,User>();

    static {
            // 用户1
            User user1 = new User();
            user1.setUsername("aaa");
            user1.setPassword("111");
            List<UriSimpleGrantedAuthority> uris1 = new ArrayList<UriSimpleGrantedAuthority>();
            uris1.add(new UriSimpleGrantedAuthority("/auth-central-try-producer/user1Call"));
            uris1.add(new UriSimpleGrantedAuthority("/auth-central-try-producer/user2Call"));
            user1.setUris(uris1);
            users.put("aaa",user1);
            // 用户2
            User user2 = new User();
            user2.setUsername("bbb");
            user2.setPassword("111");
            List<UriSimpleGrantedAuthority> uris2 = new ArrayList<UriSimpleGrantedAuthority>();
            uris2.add(new UriSimpleGrantedAuthority("/auth-central-try-producer/user1Call"));
            user2.setUris(uris2);
            users.put("bbb",user2);
    }

2.项目跑起来之后,首先请求登录接口获得token,最下面那一段就是token

微服务 统一身份认证 微服务 认证中心_User_05


3.得到了token之后,就可以访问资源了,结果是可以访问的,

微服务 统一身份认证 微服务 认证中心_java_06


4.修改uri,继续访问,结果没有权限

微服务 统一身份认证 微服务 认证中心_User_07

代码说明

其实你看我的源码,你需要有一定的spring security ,webflux的基础,我源码中其实对每个类和关键代码都有比较详细注释.看一看,然后调试调试…

那么你从哪个类开始看呢?那就从这个类吧(如:下图),这是核心配置类

微服务 统一身份认证 微服务 认证中心_微服务_08