基于spring security实现登录注销功能过程解析
这篇文章主要介绍了基于springsecurity实现登录注销功能过程解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
1、引入maven依赖
org.springframework.boot spring-boot-starter-security
2、Security配置类说明登录方式、登录页面、哪个url需要认证、注入登录失败/成功过滤器
@Configuration publicclassBrowserSecurityConfigextendsWebSecurityConfigurerAdapter{ /** *注入Security属性类配置 */ @Autowired privateSecurityPropertiessecurityProperties; /** *注入自定义的登录成功处理类 */ @Autowired privateMyAuthenticationSuccessHandlermySuccessHandler; /** *注入自定义的登录失败处理类 */ @Autowired privateMyAuthenticationFailHandlermyFailHandler; /** *重写PasswordEncoder接口中的方法,实例化加密策略 *@return返回BCrypt加密策略 */ @Bean publicPasswordEncoderpasswordEncoder(){ returnnewBCryptPasswordEncoder(); } @Override protectedvoidconfigure(HttpSecurityhttp)throwsException{ //登录成功的页面地址 StringredirectUrl=securityProperties.getLoginPage(); //basic登录方式 //http.httpBasic() //表单登录方式 http.formLogin() .loginPage("/authentication/require") //登录需要经过的url请求 .loginProcessingUrl("/authentication/form") .successHandler(mySuccessHandler) .failureHandler(myFailHandler) .and() //请求授权 .authorizeRequests() //不需要权限认证的url .antMatchers("/authentication/*",redirectUrl).permitAll() //任何请求 .anyRequest() //需要身份认证 .authenticated() .and() //关闭跨站请求防护 .csrf().disable(); //默认注销地址:/logout http.logout(). //注销之后跳转的页面 logoutSuccessUrl("/authentication/require"); }
3、自定义登录成功和失败的处理器
(1)、登录成功
@Component @Slf4j publicclassMyAuthenticationSuccessHandlerextendsSavedRequestAwareAuthenticationSuccessHandler{ @Override publicvoidonAuthenticationSuccess(HttpServletRequesthttpServletRequest,HttpServletResponsehttpServletResponse,Authenticationauthentication)throwsIOException,ServletException{ logger.info("登录成功"); //将authention信息打包成json格式返回 httpServletResponse.setContentType("application/json;charset=UTF-8"); httpServletResponse.getWriter().write("登录成功"); }}
(2)、登录失败
@Component @Slf4j publicclassMyAuthenticationFailHandlerextendsSimpleUrlAuthenticationFailureHandler{ @Override publicvoidonAuthenticationFailure(HttpServletRequesthttpServletRequest,HttpServletResponsehttpServletResponse,AuthenticationExceptione)throwsIOException,ServletException{ logger.info("登录失败"); //设置状态码 httpServletResponse.setStatus(500); //将登录失败信息打包成json格式返回 httpServletResponse.setContentType("application/json;charset=UTF-8"); httpServletResponse.getWriter().write("登录失败:"+e.getMessage()); }}
4、UserDetail类加载用户数据,返回UserDetail实例(里面包含用户信息)
@Component @Slf4j publicclassMyUserDetailsServiceimplementsUserDetailsService{ @Autowired privatePasswordEncoderpasswordEncoder; /** *根据进行登录 *@paramusername *@return *@throwsUsernameNotFoundException */ @Override publicUserDetailsloadUserByUsername(Stringusername)throwsUsernameNotFoundException{ log.info("登录用户名:"+username); Stringpassword=passwordEncoder.encode("123456"); //User三个参数(用户名+密码+权限) //根据查找到的用户信息判断用户是否被冻结 log.info("数据库密码:"+password); returnnewUser(username,password,AuthorityUtils.commaSeparatedStringToAuthorityList("admin")); } }
5、登录路径请求类,.loginPage("/authentication/require")
@RestController @Slf4j @ResponseStatus(code=HttpStatus.UNAUTHORIZED) publicclassBrowerSecurityController{ /** *把当前的请求缓存到session里去 */ privateRequestCacherequestCache=newHttpSessionRequestCache(); /** *重定向策略 */ privateRedirectStrategyredirectStrategy=newDefaultRedirectStrategy(); /** *注入Security属性类配置 */ @Autowired privateSecurityPropertiessecurityProperties; /** *当需要身份认证时跳转到这里 */ @RequestMapping("/authentication/require") publicSimpleResponserequireAuthentication(HttpServletRequestrequest,HttpServletResponseresponse)throwsIOException{ //拿到请求对象 SavedRequestsavedRequest=requestCache.getRequest(request,response); if(savedRequest!=null){ //获取跳转url StringtargetUrl=savedRequest.getRedirectUrl(); log.info("引发跳转的请求是:"+targetUrl); //判断targetUrl是不是.html结尾,如果是:跳转到登录页(返回view) if(StringUtils.endsWithIgnoreCase(targetUrl,".html")){ StringredirectUrl=securityProperties.getLoginPage(); redirectStrategy.sendRedirect(request,response,redirectUrl); } } //如果不是,返回一个json字符串 returnnewSimpleResponse("访问的服务需要身份认证,请引导用户到登录页"); }
6、postman请求测试
(1)未登录请求
(2)、登录
(3)、再次访问
(4)、注销
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:czq8825#qq.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。