I\'ve an application in spring/spring-mvc that totally uses JSON communications. Now I need to authenticate my application with spring security 3 (that uses LdapAuthenticati
Another way, according with this post, is to manage manually the spring security authentication directly in the Controller.
In this manner is very simple to manage JSON input and avoid login redirect:
@Autowired
AuthenticationManager authenticationManager;
@ResponseBody
@RequestMapping(value="/login.json", method = RequestMethod.POST)
public JsonResponse mosLogin(@RequestBody LoginRequest loginRequest, HttpServletRequest request) {
JsonResponse response = null;
try {
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(loginRequest.getUsername(), loginRequest.getPassword());
token.setDetails(new WebAuthenticationDetails(request));
Authentication auth = authenticationManager.authenticate(token);
SecurityContext securityContext = SecurityContextHolder.getContext();
securityContext.setAuthentication(auth);
if(auth.isAuthenticated()){
HttpSession session = request.getSession(true);
session.setAttribute("SPRING_SECURITY_CONTEXT", securityContext);
LoginResponse loginResponse = new LoginResponse();
loginResponse.setResponseCode(ResponseCodeType.SUCCESS);
response = loginResponse;
}else{
SecurityContextHolder.getContext().setAuthentication(null);
ErrorResponse errorResponse = new ErrorResponse();
errorResponse.setResponseCode(ResponseCodeType.ERROR);
response = errorResponse;
}
} catch (Exception e) {
ErrorResponse errorResponse = new ErrorResponse();
errorResponse.setResponseCode(ResponseCodeType.ERROR);
response = errorResponse;
}
return response;
}