spring security token鉴权时返回403,我想返回自定义异常
时间: 2023-06-28 10:06:01 浏览: 148
自定义异常
可以通过实现 Spring Security 中的 AccessDeniedHandler 接口来自定义处理访问被拒绝的情况。具体实现可以参考以下代码:
```java
@Component
public class CustomAccessDeniedHandler implements AccessDeniedHandler {
@Override
public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
response.setStatus(HttpServletResponse.SC_FORBIDDEN);
response.setContentType("application/json;charset=utf-8");
PrintWriter out = response.getWriter();
out.write("{\"status\":\"error\",\"msg\":\"权限不足,请联系管理员!\"}");
out.flush();
out.close();
}
}
```
然后在 Spring Security 的配置类中将该处理器添加进去:
```java
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private CustomAccessDeniedHandler customAccessDeniedHandler;
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.anyRequest().authenticated()
.and()
.exceptionHandling()
.accessDeniedHandler(customAccessDeniedHandler);
}
}
```
这样,当访问被拒绝时,就会返回自定义的异常信息了。
阅读全文