Spring Security实现短信验证码登录( 四 )


@Configurationpublic class SecurityBrowserConfig extends WebSecurityConfigurerAdapter {@Autowiredprivate AuthenticationFailureHandler myAuthenticationFailureHandler;@Autowiredprivate SmsCodeAuthenticationSecurityConfig smsCodeAuthenticationSecurityConfig;@Overrideprotected void configure(HttpSecurity http) throws Exception {ValidateCodeFilter validateCodeFilter = new ValidateCodeFilter();validateCodeFilter.setAuthenticationFailureHandler(myAuthenticationFailureHandler);http.addFilterBefore(validateCodeFilter, UsernamePasswordAuthenticationFilter.class)//在UsernamePasswordAuthenticationFilter之前加上验证码过滤器.formLogin().loginPage("/mobile-login.html").and().authorizeRequests().antMatchers("/mobile-login.html").permitAll().antMatchers("/code/*").permitAll().anyRequest().authenticated().and().csrf().disable()//把SmsCodeAuthenticationSecurityConfig配置加进来.apply(smsCodeAuthenticationSecurityConfig);}}
自定义简单的登录界面
登录标准登录页面短信登录

手机号:短信验证码:发送验证码

启动程序测试一下,访问自定义登录页面:8080/-login.html
Spring Security实现短信验证码登录

文章插图
登录页面
点击发送验证码,控制台打印
Spring Security实现短信验证码登录

文章插图
控制台打印
返回登录页面输入验证码进行登录,成功打印出登录用户的信息
Spring Security实现短信验证码登录

文章插图
成功登录
如果随便输入一个验证码进行登录,校验也没问题
Spring Security实现短信验证码登录

文章插图
验证码不匹配
再写一个测试一下
@Controller@RequestMapping("/")public class HelloController {private Logger logger = LoggerFactory.getLogger(HelloController.class);@RequestMapping(value = "http://www.kingceram.com/post/hello", method = RequestMethod.GET)@ResponseBodypublic String hello(){return "ok";}}
不登录的情况情况下访问:8080/hello会被引导至登录页面,验证码登录后可成功访问
总结
【Spring Security实现短信验证码登录】源码地址: