Spring Security authentication/authorization via REST endpoint Spring Security authentication/authorization via REST endpoint spring spring

Spring Security authentication/authorization via REST endpoint


You can configure what to return on successful authentication by overriding methods in SimpleUrlAuthenticationSuccessHandler


public class CustomAuthenticationSuccessHandler extends SimpleUrlAuthenticationSuccessHandler {    public CustomAuthenticationSuccessHandler() {        super();        setRedirectStrategy(new NoRedirectStrategy());    }    @Override    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,            Authentication authentication) throws IOException, ServletException {        super.onAuthenticationSuccess(request, response, authentication);        ObjectMapper mapper = new ObjectMapper();        response.setContentType("application/json;charset=UTF-8");        response.getWriter().print(mapper.writeValueAsString(objectToBereturned);        response.getWriter().flush();    }    protected class NoRedirectStrategy implements RedirectStrategy {        @Override        public void sendRedirect(HttpServletRequest request, HttpServletResponse response, String url)                throws IOException {            // any redirect if required. leave the implementation black if not needed        }    }}

Additionally you can also handle the failure response:


public class CustomAuthenticationFailureHandler extends SimpleUrlAuthenticationFailureHandler {    @Override    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,            AuthenticationException exception) throws IOException, ServletException {        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);    }}


Restful calls should always return response code. In your case it should be just 200 OK. On failure 401 Unauthorized. Having different tokens is absolutely fine, you cannot use the same anyway.

I personally would prefer to handle login endpoints through Spring Security filters and not controllers as you can control the flow better.