别再让你的微服务裸奔了,基于 Spring Session & Spring Security 微服务权限控制
微服务架构
- 网关:路由用户请求到指定服务,转发前端 Cookie 中包含的 Session 信息;
- 用户服务:用户登录认证(Authentication),用户授权(Authority),用户管理(Redis Session Management)
- 其他服务:依赖 Redis 中用户信息进行接口请求验证
用户 - 角色 - 权限表结构设计
- 权限表
权限表最小粒度的控制单个功能,例如用户管理、资源管理,表结构示例:
id | authority | description |
---|---|---|
1 | ROLE_ADMIN_USER | 管理所有用户 |
2 | ROLE_ADMIN_RESOURCE | 管理所有资源 |
3 | ROLE_A_1 | 访问 ServiceA 的某接口的权限 |
4 | ROLE_A_2 | 访问 ServiceA 的另一个接口的权限 |
5 | ROLE_B_1 | 访问 ServiceB 的某接口的权限 |
6 | ROLE_B_2 | 访问 ServiceB 的另一个接口的权限 |
- 角色 - 权限表
自定义角色,组合各种权限,例如超级管理员拥有所有权限,表结构示例:
id | name | authority_ids |
---|---|---|
1 | 超级管理员 | 1,2,3,4,5,6 |
2 | 管理员A | 3,4 |
3 | 管理员B | 5,6 |
4 | 普通用户 | NULL |
- 用户 - 角色表
用户绑定一个或多个角色,即分配各种权限,示例表结构:
user_id | role_id |
---|---|
1 | 1 |
1 | 4 |
2 | 2 |
用户服务设计
Maven 依赖(所有服务)
<!-- Security --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> <!-- Spring Session Redis --> <dependency> <groupId>org.springframework.session</groupId> <artifactId>spring-session-data-redis</artifactId> </dependency>
应用配置 application.yml
示例: