一.简介
在Spring Security中异常分为两种:
- AuthenticationException 认证异常
- AccessDeniedException 权限异常 我们先给大家演示下如何自定义异常处理器,然后再结合源码帮助大家进行分析
二.创建项目
如何创建一个SpringSecurity项目,前面文章已经有说明了,这里就不重复写了。文章来源:https://www.toymoban.com/news/detail-464679.html
三.自定义异常处理器
3.1配置SecurityConfig
这里主要是authenticationEntryPoint和accessDeniedHandler配置,代码如下:文章来源地址https://www.toymoban.com/news/detail-464679.html
@Bean
public SecurityFilterChain config(HttpSecurity http) throws Exception {
http.authorizeHttpRequests()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login.html")
.loginProcessingUrl("/login")
.permitAll()
.and()
.cors()
.configurationSource(corsConfigurationSource())
.and()
.exceptionHandling()
.authenticationEntryPoint(new AuthenticationEntryPoint() {
@Override
public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
Map<String, Object> result = new HashMap<>();
result.put("code", -1);
result.put("msg", "authenticationEntryPoint");
result.put("data", authException.getMessage());
System.out.println("调用次数");
writeResp(result, response);
}
}).accessDeniedHandler(new AccessDeniedHandler() {
@Override
public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
Map<String, Object> result = new HashMap<>();
result.put("code", -1);
result.put("msg", "accessDeniedHandler");
result.put("data", accessDeniedException.getMessage());
到了这里,关于Springboot +spring security,自定义认证和授权异常处理器的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!