参考教程地址
认证过程
- 用户使用账号密码登陆
- springsecurity将接收到的登陆信息封装成实现了Authentication 接口的UsernamePasswordAuthenticationToken
- 将产生的token对象传给AuthenticationManager进行登陆认证
- AuthenticationManager认证成功后,会返回一个封装了用户权限信息的Authentication对象
- 通过调用 SecurityContextHolder.getContext().setAuthentication(…) 将 AuthenticationManager 返回的 Authentication 对象赋予给当前的 SecurityContext
验证流程
- ChannelProcessingFilter
- SecurityContextPersistenceFilter
- ConcurrentSessionFilter
- 实现Filter接口的验证类
- SecurityContextHolderAwareRequestFilter
- JaasApiIntegrationFilter
- RememberMeAuthenticationFilter
- AnonymousAuthenticationFilter
- ExceptionTransactionFilter
- FilterSecurityInterceptor
与springboot集
指定拦截的url
- antMatchers :configure(HttpSecurity httpSecurity) 中增加antMatchers
- @PreAuthorize注解 :具体方法上增加PreAuthorize注解如下:
@PreAuthorize("hasAnyRole('ADMIN','MENU_ALL','MENU_SELECT','ROLES_ALL','USER_ALL','USER_SELECT')")
方法级安全使用诸如@PreAuthorize、@PostAuthorize 、@ Secured 注解来实现。
要想使 @PreAuthorize 注解生效,需要继承 WebSecurityConfigurerAdapter 配置类上添加 @EnableGlobalMethodSecurity注解部分代码如下
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
上面的 prePostEnabled :确定 Spring Security 前置注释 [@PreAuthorize,@PostAuthorize,..] 是否应该启用
认证处理机制
- BasicAuthenticationFilter(basic)
- UsernamePasswordAuthenticationFilter(用户密码)
- jwt(自定义jwt的方式)
maven引用
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
security配置
继承WebSecurityConfigurerAdapter,然后重写两个configur
public void configure(WebSecurity web) throws Exception {
}
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.anyRequest().authenticated()
.and()
.formLogin().and()
.httpBasic();
}
数据库表结构设计
用户角色权限相关表
字段名 | 字段类型 | 非空 | 注释 |
id | bigint(20) | 是 | ID |
avatar | varchar | 否 | 头像链接 |
create_time | datetime | 否 | 创建时间 |
email | varchar | 否 | 邮箱 |
enabled | bigint | 否 | 是否启用 |
username | varchar | 否 | 用户名 |
passwor | varchar | 否 | 密码 |
last_password_reset_time | datetime | 否 | 最后修改密码时间 |
| | | |
字段名 | 字段类型 | 非空 | 注释 |
user_id | bigint(20) | 是 | 用户ID |
role_id | bigint(20) | 是 | 角色ID |
| | | |
字段名 | 字段类型 | 非空 | 注释 |
id | bigint | 是 | 角色id |
create_time | datetime | 否 | 创建时间 |
name | varchar | 是 | 角色名称 |
remark | varchar | 否 | 备注 |
- roles_permissions 角色权限关系表
字段名 | 字段类型 | 非空 | 注释 |
role_id | bigint | 是 | 角色ID |
permission_id | bigint | 是 | 权限ID |
字段名 | 字段类型 | 非空 | 注释 |
id | bigint | 是 | |
alias | varchar | 否 | 别名 |
create_time | datetime | 否 | 创建时间 |
name | varchar | 否 | 名称 |
pid | int | 是 | 上级权限 |
菜单设计与展
字段名 | 字段名类型 | 是否非空 | 备注 |
id | bigint | 是 |
|
create_time | datetime | 否 | 创建日期 |
name | varchar | 否 | 菜单名称 |
component | varchar | 否 | 组件 |
pid | bigint | 是 | 上级菜单ID |
sort | bigint | 是 | 排序 |
icon | varchar | 否 | 图标 |
path | varchar | 否 | 链接地址 |
i_frame | bit | 否 | 是否外链 |
menu表 查询结果示例