SpringSecurity之异常处理

本文介绍了SpringSecurity中的异常体系,包括AuthenticationException(认证异常)和AccessDeniedException(授权异常)。在实际项目中,当默认异常不满足需求时,可以通过自定义异常类来扩展。示例代码展示了如何配置HttpSecurity,设置自定义的认证失败和权限不足的异常处理,禁用CSRF,并返回JSON格式的错误信息。
摘要由CSDN通过智能技术生成

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
    }
}

Spring Security 是一个基于 Spring 的安全框架,其支持多种认证方式、授权方式以及自定义安全过滤器等。在使用 Spring Security 进行开发时,自定义异常处理是非常重要的一部分。下面是 Spring Security 自定义异常处理的步骤: 1. 实现 AuthenticationEntryPoint 接口,该接口用于处理未认证用户的请求。通过实现该接口,可以自定义未认证用户的返回结果,例如返回自定义的 JSON 格式数据或者跳转到自定义的登录页面。 2. 实现 AccessDeniedHandler 接口,该接口用于处理已认证用户但没有权限访问资源的请求。同样可以通过实现该接口,自定义返回结果。 实现以上两个接口之后,需要在 Spring Security 配置中进行配置,将自定义实现的类添加到配置中即可生效。下面是一个示例配置: ``` @Configuration @EnableWebSecurity public class WebSecurityConfig extends WebSecurityConfigurerAdapter { @Autowired private MyAuthenticationEntryPoint myAuthenticationEntryPoint; @Autowired private MyAccessDeniedHandler myAccessDeniedHandler; @Override protected void configure(HttpSecurity http) throws Exception { http.exceptionHandling() .authenticationEntryPoint(myAuthenticationEntryPoint) .accessDeniedHandler(myAccessDeniedHandler) .and() .authorizeRequests() .antMatchers("/admin/**").hasRole("ADMIN") .antMatchers("/user/**").hasAnyRole("USER", "ADMIN") .anyRequest().authenticated() .and() .formLogin().loginPage("/login").permitAll() .and() .logout().permitAll(); } } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值