7.自定义登录成功处理和失败处理

自定义登录成功处理和失败处理

在某些场景下,用户登录成功或者数失败的情况下用户需要执行一些后续操作,比如登录日志搜集,或者在现在目前前后端分离的情况下,用户登录成功和失败后需要给前台页面返回对应的错误信息,有前台主导成功或者失败的页面跳转,这个时候需要用到 AuthenticationSucessHandle 与 AnthenticationFailureHandle

默认的成功和失败处理逻辑源自于下图:

进入源码查看

success

fail

 

 

 

 

他们分别实现了 AuthenticationSucessHandle 接口和 AnthenticationFailureHandle 接口

自定义成功处理 实现 AuthenticationSucessHandle 接口,并重写 onAnthenticationSucess()方法;

自定义失败处理 实现 AnthenticationFailureHandle 接口,并重写 onAnthenticationFailure() 方法

代码实现:

package com.po.service.impl;


import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.DefaultRedirectStrategy;
import org.springframework.security.web.RedirectStrategy;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Service;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Service
public class MyAuthenticationService implements AuthenticationSuccessHandler, AuthenticationFailureHandler {
    RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();
    /**
     * 登录成功后的处理逻辑
     * @param request
     * @param response
     * @param authentication
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        System.out.println("登录成功后继续处理。。。。。。。。");
        //重定向到index。html
        redirectStrategy.sendRedirect(request,response,"/");
    }
    /**
     * 登录失败后的处理逻辑
     * @param request
     * @param response
     * @param exception
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        System.out.println("登录失败后继续处理。。。。。。。。");
        redirectStrategy.sendRedirect(request,response,"/toLoginPage");
    }
}

  

package com.po.config;

import com.po.service.impl.MyAuthenticationService;
import com.po.service.impl.MyUserDetailsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.web.authentication.rememberme.JdbcTokenRepositoryImpl;
import org.springframework.security.web.authentication.rememberme.PersistentTokenRepository;

import javax.sql.DataSource;


@Configuration
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
    @Autowired
    private MyUserDetailsService myUserDetailsService;
    /**
     * http请求方法
     *
     * @param http
     * @throws Exception
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        /** http.httpBasic() //开启httpBasic认证
         .and().authorizeRequests().anyRequest().authenticated(); //所有请求都需要认证之后访问
         */
/*        http.formLogin().loginPage("/login.html")//开启表单认证
              //  .and().authorizeRequests() //放行登录页面
            //    .anyRequest().authenticated();
             //   .and().authorizeRequests().antMatchers("/login.html").permitAll() //放行登录页面
                .and().authorizeRequests().antMatchers("/toLoginPage").permitAll() //放行登录页面
                .anyRequest().authenticated();*/
                 http.formLogin() //开启表单认证
                .loginPage("/toLoginPage") // 自定义登陆页面
                .loginProcessingUrl("/login") //表单提交路径
                .usernameParameter("username").passwordParameter("password") //自定义input额name值和password
                .successForwardUrl("/") //登录成功之后跳转的路径
                         .successHandler(myAuthenticationService) // 登录成功处理
                         .failureHandler(myAuthenticationService) //登录失败处理
                .and().authorizeRequests().antMatchers("/toLoginPage").permitAll() //放行登录页面
                .anyRequest().authenticated()
                 .and().rememberMe() //开启记住我功能
                  .tokenValiditySeconds(1209600) //token失效时间,默认失效时间是两周
                  .rememberMeParameter("remember-me") // 自定义表单name值
                  .tokenRepository(getPersistentTokenRepository()) //设置PersistentTokenRepository
                 .and().headers().frameOptions().sameOrigin() //加载同源域名下iframe页面
                .and().csrf().disable();//关闭csrf防护
    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        //解决静态资源被拦截的问题
        web.ignoring().antMatchers("/css/**","/images/**","/js/**");
    }

    /**
     *身份安全管理器
     * @param auth
     * @throws Exception
     */
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(myUserDetailsService);
    }

    @Autowired
    DataSource dataSource;
    /**
     * 负责token与数据库之间的操作
     * @return
     */
    @Bean
    public PersistentTokenRepository getPersistentTokenRepository(){
        JdbcTokenRepositoryImpl tokenRepository = new JdbcTokenRepositoryImpl();
        tokenRepository.setDataSource(dataSource); //设置数据源
        tokenRepository.setCreateTableOnStartup(false); //启动时帮助我们自动创建一张表,第一次启动设置为true,第二次启动程序的时候设置false或者注释掉;
        return tokenRepository;
    }

    @Autowired
    private MyAuthenticationService myAuthenticationService;

}

测试结果(失败和成功分别演示一次)

 

 

 

 

 

posted @ 2023-03-15 17:22  __破  阅读(99)  评论(0)    收藏  举报