Reputation: 123
I have the following hasRole() protection on antMatchers:
.antMatchers(HttpMethod.GET, "/api/posts/myPosts").hasRole("USER")
How to handle response if user doesn't have role USER? When I do GET on /api/posts/myPosts
with user without USER role I get response:
{
"timestamp": "2019-04-14T12:43:31.233+0000",
"status": 403,
"error": "Forbidden",
"message": "Forbidden",
"path": "/api/posts/myPosts"
}
Is it possible to throw own exception and handle it later in class annotated @RestControllerAdvice
?
I tried other way to achieve that by adding @PreAuthorize("hasRole('USER')")
on the method level, then Spring throws AccessDeniedException
and it's fine.
Upvotes: 0
Views: 184
Reputation: 2131
Filters happens before controllers are even resolved so exceptions thrown from filters can't be caught by a Controller Advice. Instead, Create an Authentication Entry Point like
@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");
}
}
Register this CustomAuthenticationEntryPoint within WebSecurityConfigurerAdapter like
@Override
public void configure(HttpSecurity http) throws Exception {
...
.antMatchers(HttpMethod.GET, "/api/posts/myPosts").hasRole("USER")
...
.and()
.exceptionHandling()
.authenticationEntryPoint(customAuthenticationEntryPoint)
...
}
Upvotes: 0