SpringSecurity从入门到精通
快速入门
SpringSecurity是spring家族中的一个安全管理框架,核心功能是认证和授权
认证:验证当前访问系统的是不是系统的用户,并且要确认具体是哪个用户
授权:经过认证后判断当前用户时候有权限进行某个操作
1、引入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
新建一个简单的helloController,然后我们访问hello接口,就需要先登录才能访问
认证
基本原理
SpringSecurity的原理其实就是一个过滤器链,内部包含了提供各种功能的过滤器,如下展示几个重要的过滤器
SpringSecurity过滤器链如图
其中最常用的三个过滤器:
- UsernamePasswordAuthenticationFilter:负责处理我们在登录页面填写了用户名和密码后的登录请求。默认的账号密码认证主要是他来负责
- ExceptionTranslationFilter:处理过滤器链中抛出的任何AccessDeniedException和AuthenticationException
- FilterSecurityInterceptor:负责权限校验的过滤器
Authentication接口:它的实现类,表示当前访问系统的用户,封装了前端传入的用户相关信息
AuthenticationManager接口:定义了认证Authentication的方法
UserDetailsService接口:加载用户特定数据的核心接口。里面定义了一个更具用户名查询用户信息的方法
UserDetails接口:提供核心用户信息。通过UserDetailService根据用户名获取处理的用户信息要封装成UserDetails对象放回。然后将这些信息封装到Authentication对象中
认证配置讲解
@Override
protected void configure(HttpSecurity httpSecurity) throws Exception{
httpSecurity
//关闭csrf
.csrf().disable()
//不通过Session获取SecurityContext
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.authorizeRequests()
//对于登录接口,允许匿名访问
.antMatchers("/login").anonymous()
//除上面外的所有请求全部需要鉴权认证
.anyRequest().authenticated();
httpSecurity.addFilterBefore(jwtAuthenticationTokenFilter, UsernamePasswordAuthenticationFilter.class);
}
授权
不同的用户可以有不同的功能
在SpringSecurity中,会使用默认的FilterSecurityInterceptor来进行权限校验,在FilterSecurityInterceptor中会从SecurityContextHolder获取其中的Authentication,然后获取其中的权限信息,当前用户是否拥有访问当前资源所需要的权限,所以我们在项目中只需要把当前用户的权限信息存入Authentication
限制访问资源所需要的权限
// 放在配置类上
@EnableGlobalMethodSecurity(prePostEnable=true)
@RestController
public class LoginController {
@RequestMapping("/login")
// 有test权限才可以访问
@PreAuthorize("hasAuthority('test')")
// 有test和admin中的任意权限即可
@PreAuthorize("hasAnyAuthority('test','admin')")
// 必须有ROLE_test和ROLE_admin两个权限,hasRole会默认给角色添加前缀
@PreAuthorize("hasRole('ROLE_test','ROLE_admin')")
// 有ROLE_test和ROLE_admin中的任意权限即可,hasRole会默认给角色添加前缀
@PreAuthorize("hasAnyRole('ROLE_test','ROLE_admin')")
public String login(@RequestBody User user){
// 登录
return loginService.login(user);
}
}
正常企业开发是不会选择在代码中控制权限的,而是从数据库中,通过用户、角色、权限来配置(RBAC权限模型)
自定义权限校验方法
@Component("ex")
public class SGExpressionRoot {
public boolean hasAuthority(String authority){
// 获取当前用户权限
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
LoginUser loginUser = (LoginUser)authentication.getPrincipal();
List<String> permissions = loginUser.getPermissions();
return permissions.contains(authority);
}
}
调用我们自定义的检查规则
@RequestMapping("/login")
// SPEL表达式,@ex相当于获取容器中bean的名字是ex的对象
@PreAuthorize("@ex.hasAuthority('test')")
// @PreAuthorize("hasAuthority('test')")
public String login(@RequestBody User user){
// 登录
return loginService.login(user);
}
配置文件配置访问权限
httpSecurity
//关闭csrf
.csrf().disable()
//不通过Session获取SecurityContext
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.authorizeRequests()
//对于登录接口,允许匿名访问
.antMatchers("/login").anonymous()
//具有admin权限才能访问helloController
.antMatchers("/hello").hasAuthority("admin")
//除上面外的所有请求全部需要鉴权认证
.anyRequest().authenticated();
自定义失败提示
SpringSecurity自定义的异常过滤器,ExceptionTranslationFilter
认证过程出现异常,会被封装成AuthenticationException然后调用AuthenticationEntryPoint对象的方法
授权过程中出现异常会被封装成AccessDeniedException然后调用AccessDeniedHandler对象的方法
所以如果我们想要自定义异常处理,只需要自定义AuthenticationEntryPoint和AccessDeniedHandler然后配置给SpringSecurity即可
@Component
public class AuthenticationEntryPointImpl implements AuthenticationEntryPoint {
@Override
public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOE