7.自定义登录成功处理和失败处理
自定义登录成功处理和失败处理
在某些场景下,用户登录成功或者数失败的情况下用户需要执行一些后续操作,比如登录日志搜集,或者在现在目前前后端分离的情况下,用户登录成功和失败后需要给前台页面返回对应的错误信息,有前台主导成功或者失败的页面跳转,这个时候需要用到 AuthenticationSucessHandle 与 AnthenticationFailureHandle;
默认的成功和失败处理逻辑源自于下图:
进入源码查看
success
fail
他们分别实现了 AuthenticationSucessHandle 接口和 AnthenticationFailureHandle 接口
自定义成功处理 实现 AuthenticationSucessHandle 接口,并重写 onAnthenticationSucess()方法;
自定义失败处理 实现 AnthenticationFailureHandle 接口,并重写 onAnthenticationFailure() 方法
代码实现:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 | 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" ); } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 | 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; } |
测试结果(失败和成功分别演示一次)
分类:
spring security
标签:
spring security
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY