Spring Security(五):认证(Authentication)

您所在的位置:网站首页 取消阿里云短信验证码登录 Spring Security(五):认证(Authentication)

Spring Security(五):认证(Authentication)

#Spring Security(五):认证(Authentication)| 来源: 网络整理| 查看: 265

Spring Security(五):认证(Authentication)-短信验证码登录 原创

wx646209fa8f818 2023-05-16 00:06:45 博主文章分类:Spring Security ©著作权

文章标签 验证码 ide ajax 文章分类 JavaScript 前端开发

©著作权归作者所有:来自51CTO博客作者wx646209fa8f818的原创作品,请联系作者获取转载授权,否则将追究法律责任

有些登录是输入手机号然后获取短信验证码进行登录的。短信验证码和图片验证码原理一样,都是自定义一个过滤器用于校验验证码是否正确。

login.html

短信验证码 获取验证码

function getSmsCode() { var ajax = new XMLHttpRequest(); ajax.open('get','/code/sms'); ajax.send(); } controller@Data @ToString @AllArgsConstructor @RequiredArgsConstructor public class SmsCode { private String code; private LocalDateTime expireTime; public SmsCode(String code, int expireIn) { this.code = code; this.expireTime = LocalDateTime.now().plusSeconds(expireIn); } public boolean isExpried() { return LocalDateTime.now().isAfter(expireTime); } }@RestController public class SmsValidateCodeController { private SessionStrategy sessionStrategy = new HttpSessionSessionStrategy(); public static final String SESSION_KEY = "SESSION_KEY_SMS_CODE"; @GetMapping("/code/sms") public void createCode(HttpServletRequest request) { SmsCode smsCode = createSmsCode(); System.out.println("验证码发送成功:" + smsCode); sessionStrategy.setAttribute(new ServletWebRequest(request), SESSION_KEY, smsCode); } private SmsCode createSmsCode() { String code = (int) ((Math.random() * 9 + 1) * 100000) + ""; return new SmsCode(code, 600); } }filterpublic class SmsValidateCodeFilter extends OncePerRequestFilter { @Autowired private AuthenticationFailureHandler authenticationFailureHandler; // spring-social-web private SessionStrategy sessionStrategy = new HttpSessionSessionStrategy(); @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { if ("/login".equals(request.getRequestURI()) && "POST".equals(request.getMethod())) { try { validate(new ServletWebRequest(request)); } catch (ValidateCodeException e) { authenticationFailureHandler.onAuthenticationFailure(request, response, e); return; } } filterChain.doFilter(request, response); } private void validate(ServletWebRequest request) throws ServletRequestBindingException { SmsCode codeInSession = (SmsCode) sessionStrategy.getAttribute(request, SmsValidateCodeController.SESSION_KEY); String codeInRequest = ServletRequestUtils.getStringParameter(request.getRequest(), "smsCode"); if (StringUtils.isEmpty(codeInRequest)) { throw new ValidateCodeException("验证码不能为空"); } if (codeInSession == null) { throw new ValidateCodeException("验证码不存在"); } if (codeInSession.isExpried()) { sessionStrategy.removeAttribute(request, SmsValidateCodeController.SESSION_KEY); throw new ValidateCodeException("验证码已过期"); } if (!codeInRequest.equals(codeInSession.getCode())) { throw new ValidateCodeException("验证码不匹配"); } sessionStrategy.removeAttribute(request, SmsValidateCodeController.SESSION_KEY); } public AuthenticationFailureHandler getAuthenticationFailureHandler() { return authenticationFailureHandler; } public void setAuthenticationFailureHandler(AuthenticationFailureHandler authenticationFailureHandler) { this.authenticationFailureHandler = authenticationFailureHandler; } }configuration@Configuration @EnableWebSecurity public class SecurityConfiguration extends WebSecurityConfigurerAdapter { @Autowired private MyUserDetailsService myUserDetailsService; @Autowired private MyAuthenticationSuccessHandler myAuthenticationSuccessHandler; @Autowired private MyAuthenticationFailureHandler myAuthenticationFailureHandler; @Override protected void configure(HttpSecurity http) throws Exception { SmsValidateCodeFilter smsValidateCodeFilter = new SmsValidateCodeFilter(); smsValidateCodeFilter.setAuthenticationFailureHandler(myAuthenticationFailureHandler); http.csrf().disable() // 配置需要认证的请求 .authorizeRequests() .antMatchers("/login", "/code/image", "/code/sms").permitAll() .anyRequest() .authenticated() .and() // 登录表单相关配置 .addFilterBefore(smsValidateCodeFilter, UsernamePasswordAuthenticationFilter.class) .formLogin() .loginPage("/login") .usernameParameter("username") .passwordParameter("password") .successHandler(myAuthenticationSuccessHandler) .failureUrl("/login?error") .permitAll() .and() // 登出相关配置 .logout() .permitAll(); } @Override public void configure(AuthenticationManagerBuilder auth) throws Exception { auth.userDetailsService(myUserDetailsService).passwordEncoder(passwordEncoder()); } @Override public void configure(WebSecurity web) { web.ignoring().antMatchers("/static/**"); } @Bean public PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } }

收藏 评论 分享 举报

上一篇:Spring Security(九):会话管理(Session)

下一篇:Scala(二) 基础语法



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3