SpringSecurity series of custom login verification result of treatment success and failure

First, the need to customize the scene login results

In my previous article, the verification process done login source resolution. The more important thing is

  • When we have a successful login, login is handled by the result AuthenticationSuccessHandler, jump to the default path defaultSuccessUrl configuration corresponding resource page (usually home index.html).
  • When we failed login is to log results were processed by AuthenticationfailureHandler, jump to the default path failureUrl configuration corresponding resource page (typically login page login.html).

But in the process of web application development needs are ever-changing, sometimes we do need to sign in for personalized treatment results, such as:

  • After landing we hope that different people see different Home
  • We use a separate front and rear ends, the result is the authentication response data JSON format, instead of the page jump

More of these cases, the use of Spring Security as a security framework when we need to use the knowledge learned in this section to verify the results of a custom login process.

Second, the results of a custom landing successful treatment

In order to meet the above requirements, how do we do it? Here we have a section to explain. AuthenticationSuccessHandler interface is a successful authentication Security provides the processor interface, we just need to realize it can be. But generally speaking, we do not go directly to achieve AuthenticationSuccessHandler interfaces, but inherit SavedRequestAwareAuthenticationSuccessHandler class, remembers resource path on the user's first request, for example: a user request books.html, so there is no landing was blocked to the login page, Man Shing when you log in will automatically jump to books.html, instead of the main page.

@Component
public class MyAuthenticationSuccessHandler 
                        extends SavedRequestAwareAuthenticationSuccessHandler {

    //在application配置文件中配置登陆的类型是JSON数据响应还是做页面响应
    @Value("${spring.security.logintype}")
    private String loginType;

    private  static ObjectMapper objectMapper = new ObjectMapper();

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

        if (loginType.equalsIgnoreCase("JSON")) {
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().write(objectMapper.writeValueAsString(AjaxResponse.success()));
        } else {
            // 会帮我们跳转到上一次请求的页面上
            super.onAuthenticationSuccess(request, response, authentication);
        }
    }
}
  • In the above custom landing successfully processed, the result not only adapt to the application login process JSON separate front and rear end, also applies to the application's login page jump template processing results
  • Spring Boot ObjectMapper is integrated by default Jackson JSON data processing library classes.
  • AjaxResponse JSON data interface is universal response of a custom class.

Third, the results of a custom login failure treatment

Here we also did not directly implement AuthenticationFailureHandler interfaces, but inherit SimpleUrlAuthenticationFailureHandler class. This class implements the default login authentication failed logical jump that failed after landing back to the login page. We can use this fact to simplify our code.

@Component
public class MyAuthenticationFailureHandler extends SimpleUrlAuthenticationFailureHandler {

    //在application配置文件中配置登陆的类型是JSON数据响应还是做页面响应
    @Value("${spring.security.logintype}")
    private String loginType;

    private  static ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public void onAuthenticationFailure(HttpServletRequest request,
                                        HttpServletResponse response, 
                                        AuthenticationException exception) 
                                        throws IOException, ServletException {

        if (loginType.equalsIgnoreCase("JSON")) {
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().write(
                    objectMapper.writeValueAsString(
                            AjaxResponse.error(
                                    new CustomException(
                                        CustomExceptionType.USER_INPUT_ERROR,
                                        "用户名或密码存在错误,请检查后再次登录"))));
        } else {
            response.setContentType("text/html;charset=UTF-8");
            super.onAuthenticationFailure(request, response, exception);
        }

    }
}
  • In the above custom login failed treatment, not only to meet the application processing JSON result of login failures before and after the end of the separation, but also applies to the login fails result of processing the application template page jump
  • After landing failure, the default jump to the default failureUrl, namely the login screen.

Fourth, configure SecurityConfig

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Resource
    private MyAuthenticationSuccessHandler myAuthenticationSuccessHandler;

    @Resource
    private MyAuthenticationFailureHandler myAuthenticationFailureHandler;

   @Override
   protected void configure(HttpSecurity http) throws Exception {
       http.csrf().disable() //禁用跨站csrf攻击防御,后面的章节会专门讲解
           .formLogin()
           .successHandler(myAuthenticationSuccessHandler)
           .failureHandler(myAuthenticationFailureHandler)
           .defaultSuccessUrl("/index")//登录认证成功后默认转跳的路径
           .failureUrl("/login.html") //登录认证是被跳转页面
}
  • The self AuthenticationSuccessHandler and injected into AuthenticationFailureHandler defined class configuration Spring Security
  • Use fromlogin mode, and arranged successHandler failureHandler.
  • And the configuration and failureUrl defaultSuccessUrl

    Look forward to your attention

  • Blogger recently wrote a book: "hand touch hand to teach you to learn SpringBoot series chapter 97 section -16"
  • This article is reproduced indicate the source (en must not turn only the text): letters Gebo off .

Guess you like

Origin www.cnblogs.com/zimug/p/11895429.html