我在antMatchers上具有以下hasRole()保护:
.antMatchers(HttpMethod.GET, "/api/posts/myPosts").hasRole("USER")
如果用户没有角色USER,如何处理响应?当我以没有USER角色的用户在/api/posts/myPosts
上执行GET时,会收到响应:
{
"timestamp": "2019-04-14T12:43:31.233+0000",
"status": 403,
"error": "Forbidden",
"message": "Forbidden",
"path": "/api/posts/myPosts"
}
是否可以引发自己的异常并稍后在带注释的@RestControllerAdvice
类中处理它?</ p>
我尝试了另一种方法来实现此目标,方法是在方法级别添加@PreAuthorize("hasRole('USER')")
,然后Spring抛出AccessDeniedException
,就可以了。
答案 0 :(得分:0)
过滤器发生在控制器尚未解决之前,因此控制器建议无法捕获从过滤器引发的异常。而是创建一个像
这样的身份验证入口点@Component
public class CustomAuthenticationEntryPoint implements AuthenticationEntryPoint {
public void commence(HttpServletRequest request,
HttpServletResponse response,
AuthenticationException ae) throws IOException, ServletException {
//Here do whatever you want to do with the exception: ae
response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Access Denied");
}
}
在WebSecurityConfigurerAdapter之类的
中注册此CustomAuthenticationEntryPoint@Override
public void configure(HttpSecurity http) throws Exception {
...
.antMatchers(HttpMethod.GET, "/api/posts/myPosts").hasRole("USER")
...
.and()
.exceptionHandling()
.authenticationEntryPoint(customAuthenticationEntryPoint)
...
}