1.异常体系
Spring Security中异常主要分为两大类:
- AuthenticationException:认证异常
- AccessDeniedException:授权异常
其中认证所涉及异常类型比较多,默认提供的异常类型如下:
相比于认证异常,权限异常类就要少了很多,默认提供的权限异常如下:
2.自定义异常类
在实际项目开发中,如果默认提供异常无法满足需求时,就需要根据实际需要来自定义异常类。
public class MySecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeHttpRequests()
.mvcMatchers("/hello").hasRole("admin") //访问/hello 必须具有admin权限
.anyRequest().authenticated()
.and()
.formLogin()
.and()
.exceptionHandling() //异常处理
.authenticationEntryPoint((request, response, e) -> {
response.setContentType("application/json;charset=UTF-8");
response.setStatus(HttpStatus.FORBIDDEN.value());
response.getWriter().write("尚未认证,请进行认证操作");
})
.accessDeniedHandler((request, response, e) -> {
response.setContentType("application/json;charset=UTF-8");
response.setStatus(HttpStatus.FORBIDDEN.value());
response.getWriter().write("无权访问");
})
.and()
.csrf().disable();//开启csrf
}
}