Spring Security and JSON Authentication

前端 未结 8 1696
我在风中等你
我在风中等你 2020-11-28 05:11

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

8条回答
  •  无人及你
    2020-11-28 05:37

    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;
    }
    

提交回复
热议问题