Learn from zero spring security login success and failure handling

Keywords: JSON

After successful login, we need to implement the AuthenticationSuccessHandler interface to handle our logic. Of course, you can inherit its implementation class SavedRequestAwareAuthenticationSuccessHandler.
After login failure, we need to implement the AuthenticationFailureHandler interface to handle our logic. Of course, you can inherit its implementation class simpleurauthenticationfailurehandler.

/**
* @ClassName: IAuthenticationFailHandler
* @Description: Login failure processing class
* @Author: zhbin
* @CreateDate: 2019/7/8 17:02
* @Version: 1.0
*/
@Slf4j
@Component
//public class IAuthenticationFailHandler implements AuthenticationFailureHandler {
public class IAuthenticationFailHandler extends SimpleUrlAuthenticationFailureHandler {
    @Autowired
    private SecurityProperties securityProperties;
    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException, ServletException {

        log.info("Login failed");
        if(LoginType.JSON.equals(securityProperties.getProperties().getLoginType())){
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().write(JSONObject.toJSONString(e));
        }else{
            super.onAuthenticationFailure(request,response,e);
        }

    }
}

/**
* @ClassName: IAuthenticationSuccessHandler
* @Description: Login successfully processed class
* @Author: zhbin
* @CreateDate: 2019/7/8 17:02
* @Version: 1.0
*/
@Slf4j
@Component
//public class IAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
public class IAuthenticationSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {

    @Autowired
    private SecurityProperties securityProperties;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {

        log.info("Login successfully");
        if(LoginType.JSON.equals(securityProperties.getProperties().getLoginType())){
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().write(JSONObject.toJSONString(authentication));
        }else{
            super.onAuthenticationSuccess(request,response,authentication);
        }

    }
}

Here we simply judge that if the request is in JSON mode, the corresponding JSON content, if not, will call the parent class method to jump to the page.
We can configure the handling method of login success and failure in BrowserConfig.

@Configuration
public class BrowserConfig extends WebSecurityConfigurerAdapter {

    @Bean
    public PasswordEncoder passwordEncoder(){

        return new BCryptPasswordEncoder();
    }

    @Autowired
    private IAuthenticationSuccessHandler authentication;

    @Autowired
    private IAuthenticationFailHandler failHandler;

    @Autowired
    private SecurityProperties securityProperties;
    @Override
    protected void configure(HttpSecurity http) throws Exception {


        http.formLogin()
                .loginPage("/authentication/require")
                .loginProcessingUrl("/authentication/form")
                // Login successfully
                .successHandler(authentication)
                // Login failed
                .failureHandler(failHandler)
                .and()
                .authorizeRequests()
                .antMatchers("/authentication/require",securityProperties.getProperties().getLoginPage()).permitAll()
                .anyRequest()
                .authenticated()
                .and()
                .csrf().disable();
    }
}

Posted by RazorICE on Fri, 01 Nov 2019 01:46:41 -0700