I still new with Spring especially spring security. This application is Restful application.
Following is snippet from @RestController
:
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 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