有些登录是输入手机号然后获取短信验证码进行登录的。短信验证码和图片验证码原理一样,都是自定义一个过滤器用于校验验证码是否正确。
- login.html
<p>
<label for="imageCode">短信验证码</label>
<input type="input" id="smsCode" name="smsCode" required>
<button onclick="getSmsCode()">获取验证码</button>
</p>
<script>
function getSmsCode() {
var ajax = new XMLHttpRequest();
ajax.open('get','/code/sms');
ajax.send();
}
</script>
- 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);
}
}
- filter
public 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();
}
}