I still new with Spring especially spring security. This application is Restful application.
Following is snippet from @RestController
:
You may be able to create a custom filter that can catch an AccessDeniedException
and add the filter after ExceptionTranslationFilter
in the configuration file in the following way:
http.addFilterAfter(customExceptionTranslationFilter, ExceptionTranslationFilter.class)
After catching the exception, you can use the response object to respond in the way you'd like.
You can then also add the ability to work with other exception you may want to throw in your Controllers.
There is a better way for this. You should add authenticationEntryPoint
in spring security config and class, which implements AuthenticationEntryPoint
interface. Something like this:
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/login").permitAll()
.anyRequest().authenticated()
.and()
.requestCache()
.requestCache(new NullRequestCache())
.and()
.httpBasic()
// --> begin change: new lines added
.and()
.exceptionHandling().authenticationEntryPoint(new AuthExceptionEntryPoint())
// <-- end change
.and()
.csrf().disable();
}
AuthExceptionEntryPoint class, for producing JSON Jackson ObjectMapper
used:
public class AuthExceptionEntryPoint implements AuthenticationEntryPoint {
@Override
public void commence(HttpServletRequest request, HttpServletResponse response,
AuthenticationException authException)
throws IOException, ServletException {
List<String> errors = new ArrayList<>();
errors.add("Unauthorized");
response.setContentType("application/json");
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
try {
ObjectMapper mapper = new ObjectMapper();
mapper.writeValue(response.getOutputStream(), errors);
} catch (Exception e) {
throw new ServletException();
}
}
}
More information about spring security config you can read on Spring docs