Spring Security and JSON Authentication

2020-01-26 04:14发布

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 LdapAuthenticationProvider) via JSON.

The default spring seurity submit form requires a POST like this:

POST /myapp/j_spring_security_check HTTP/1.1
Accept-Encoding: gzip,deflate
Content-Type: application/x-www-form-urlencoded
Content-Length: 32
Host: 127.0.0.1:8080
Connection: Keep-Alive
User-Agent: Apache-HttpClient/4.1.1 (java 1.5)

j_username=myUsername&j_password=myPass

But I want to pass a JSON object like this:

{"j_username":"myUsername","j_password":"myPass"}

I read many post like this, this other or this one without luck, in all ajax cases is done a POST like above.

Any Ideas?

8条回答
乱世女痞
2楼-- · 2020-01-26 05:00

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;
}
查看更多
相关推荐>>
3楼-- · 2020-01-26 05:00

Here is the java configuration for the above solutions:

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.csrf().disable()
            .addFilterBefore(authenticationFilter(),UsernamePasswordAuthenticationFilter.class)
            .authorizeRequests()
            .anyRequest().authenticated()
            .and()
            .formLogin()
            .loginPage("/login")
            .permitAll();
}

@Bean
public AuthenticationFilter authenticationFilter() throws Exception{
    AuthenticationFilter authenticationFilter = new AuthenticationFilter();
    authenticationFilter.setUsernameParameter("username");
    authenticationFilter.setPasswordParameter("password");
    authenticationFilter.setAuthenticationManager(authenticationManager());
    authenticationFilter.setFilterProcessesUrl("/login");
    authenticationFilter.setAuthenticationSuccessHandler(successHandler());
    return authenticationFilter;
}

@Bean
public SuccessHandler successHandler(){
    return new SuccessHandler();
}
查看更多
登录 后发表回答