Spring|Spring Security短信验证码实现详解
目录
- 需求
- 实现步骤
- 获取短信验证码
- 短信验证码校验过滤器
- 短信验证码登录认证
- 配置类进行综合组装
需求
文章图片
- 输入手机号码,点击获取按钮,服务端接受请求发送短信
- 用户输入验证码点击登录
- 手机号码必须属于系统的注册用户,并且唯一
- 手机号与验证码正确性及其关系必须经过校验
- 登录后用户具有手机号对应的用户的角色及权限
实现步骤
- 获取短信验证码
- 短信验证码校验过滤器
- 短信验证码登录认证过滤器
- 综合配置
获取短信验证码 在这一步我们需要写一个controller接收用户的获取验证码请求。注意:一定要为“/smscode”访问路径配置为permitAll访问权限,因为spring security默认拦截所有路径,除了默认配置的/login请求,只有经过登录认证过后的请求才会默认可以访问。
@Slf4j@RestControllerpublic class SmsController {@Autowiredprivate UserDetailsService userDetailsService; //获取短信验证码@RequestMapping(value="https://www.it610.com/smscode",method = RequestMethod.GET)public String sms(@RequestParam String mobile, HttpSession session) throws IOException {//先从数据库中查找,判断对应的手机号是否存在UserDetails userDetails = userDetailsService.loadUserByUsername(mobile); //这个地方userDetailsService如果使用spring security提供的话,找不到用户名会直接抛出异常,走不到这里来//即直接去了登录失败的处理器if(userDetails == null){return "您输入的手机号不是系统注册用户"; }//commons-lang3包下的工具类,生成指定长度为4的随机数字字符串String randomNumeric = RandomStringUtils.randomNumeric(4); //验证码,过期时间,手机号SmsCode smsCode = new SmsCode(randomNumeric,60,mobile); //TODO 此处调用验证码发送服务接口//这里只是模拟调用log.info(smsCode.getCode() + "=》" + mobile); //将验证码存放到session中session.setAttribute("sms_key",smsCode); return "短信息已经发送到您的手机"; }}
上文中我们只做了短信验证码接口调用的模拟,没有真正的向手机发送验证码。此部分接口请结合短信发送服务提供商接口实现。
短信验证码发送之后,将验证码“谜底”保存在session中。
使用SmsCode封装短信验证码的谜底,用于后续登录过程中进行校验。
public class SmsCode {private String code; //短信验证码private LocalDateTime expireTime; //验证码的过期时间private String mobile; //发送手机号public SmsCode(String code,int expireAfterSeconds,String mobile){this.code = code; this.expireTime = LocalDateTime.now().plusSeconds(expireAfterSeconds); this.mobile = mobile; }public boolean isExpired(){returnLocalDateTime.now().isAfter(expireTime); }public String getCode() {return code; }public String getMobile() {return mobile; }}
前端初始化短信登录界面
短信登陆
文章图片
spring security配置类
@Configurationpublic class SecurityConfig extends WebSecurityConfigurerAdapter {private ObjectMapper objectMapper=new ObjectMapper(); @Resourceprivate CaptchaCodeFilter captchaCodeFilter; @BeanPasswordEncoder passwordEncoder() {return NoOpPasswordEncoder.getInstance(); }@Overridepublic void configure(WebSecurity web) throws Exception {web.ignoring().antMatchers("/js/**", "/css/**","/images/**"); }//数据源注入@AutowiredDataSource dataSource; //持久化令牌配置@BeanJdbcTokenRepositoryImpl jdbcTokenRepository() {JdbcTokenRepositoryImpl jdbcTokenRepository = new JdbcTokenRepositoryImpl(); jdbcTokenRepository.setDataSource(dataSource); return jdbcTokenRepository; }//用户配置@Override@Beanprotected UserDetailsService userDetailsService() {JdbcUserDetailsManager manager = new JdbcUserDetailsManager(); manager.setDataSource(dataSource); if (!manager.userExists("dhy")) {manager.createUser(User.withUsername("dhy").password("123").roles("admin").build()); }if (!manager.userExists("大忽悠")) {manager.createUser(User.withUsername("大忽悠").password("123").roles("user").build()); }//模拟电话号码if (!manager.userExists("123456789")) {manager.createUser(User.withUsername("123456789").password("").roles("user").build()); }return manager; }@Overrideprotected void configure(HttpSecurity http) throws Exception {http.//处理需要认证的请求authorizeRequests()//放行请求,前提:是对应的角色才行.antMatchers("/admin/**").hasRole("admin").antMatchers("/user/**").hasRole("user")//无需登录凭证,即可放行.antMatchers("/kaptcha","/smscode").permitAll()//放行验证码的显示请求//剩余的请求都需要认证才可以放行.anyRequest().authenticated().and()//表单形式登录的个性化配置.formLogin().loginPage("/login.html").permitAll().loginProcessingUrl("/login").permitAll().defaultSuccessUrl("/main.html")//可以记住上一次的请求路径//登录失败的处理器.failureHandler(new MyFailHandler()).and()//退出登录相关设置.logout()//退出登录的请求,是再没退出前发出的,因此此时还有登录凭证//可以访问.logoutUrl("/logout")//此时已经退出了登录,登录凭证没了//那么想要访问非登录页面的请求,就必须保证这个请求无需凭证即可访问.logoutSuccessUrl("/logout.html").permitAll()//退出登录的时候,删除对应的cookie.deleteCookies("JSESSIONID").and()//记住我相关设置.rememberMe()//预定义key相关设置,默认是一串uuid.key("dhy")//令牌的持久化.tokenRepository(jdbcTokenRepository()).and().addFilterBefore(captchaCodeFilter, UsernamePasswordAuthenticationFilter.class)//csrf关闭.csrf().disable(); }//角色继承@BeanRoleHierarchy roleHierarchy() {RoleHierarchyImpl hierarchy = new RoleHierarchyImpl(); hierarchy.setHierarchy("ROLE_admin > ROLE_user"); return hierarchy; }}
短信验证码校验过滤器 短信验证码的校验过滤器,和图片验证码的验证实现原理是一致的。都是通过继承OncePerRequestFilter实现一个Spring环境下的过滤器。其核心校验规则如下:
- 用户登录时手机号不能为空
- 用户登录时短信验证码不能为空
- 用户登陆时在session中必须存在对应的校验谜底(获取验证码时存放的)
- 用户登录时输入的短信验证码必须和“谜底”中的验证码一致
- 用户登录时输入的手机号必须和“谜底”中保存的手机号一致
- 用户登录时输入的手机号必须是系统注册用户的手机号,并且唯一
@Componentpublic class SmsCodeValidateFilter extends OncePerRequestFilter {@ResourceUserDetailsService userDetailsService; @ResourceMyFailHandler myAuthenticationFailureHandler; @Overrideprotected void doFilterInternal(HttpServletRequest request,HttpServletResponse response,FilterChain filterChain)throws ServletException, IOException {//该过滤器只负责拦截验证码登录的请求//并且请求必须是postif (request.getRequestURI().equals("/smslogin")&& request.getMethod().equalsIgnoreCase("post")) {try {validate(new ServletWebRequest(request)); }catch (AuthenticationException e){myAuthenticationFailureHandler.onAuthenticationFailure(request,response,e); return; }}filterChain.doFilter(request,response); }private void validate(ServletWebRequest request) throws ServletRequestBindingException {HttpSession session = request.getRequest().getSession(); //从session取出获取验证码时,在session中存放验证码相关信息的类SmsCode codeInSession = (SmsCode) session.getAttribute("sms_key"); //取出用户输入的验证码String codeInRequest = request.getParameter("smsCode"); //取出用户输入的电话号码String mobileInRequest = request.getParameter("mobile"); //common-lang3包下的工具类if(StringUtils.isEmpty(mobileInRequest)){throw new SessionAuthenticationException("手机号码不能为空!"); }if(StringUtils.isEmpty(codeInRequest)){throw new SessionAuthenticationException("短信验证码不能为空!"); }if(Objects.isNull(codeInSession)){throw new SessionAuthenticationException("短信验证码不存在!"); }if(codeInSession.isExpired()){//从session中移除保存的验证码相关信息session.removeAttribute("sms_key"); throw new SessionAuthenticationException("短信验证码已过期!"); }if(!codeInSession.getCode().equals(codeInRequest)){throw new SessionAuthenticationException("短信验证码不正确!"); }if(!codeInSession.getMobile().equals(mobileInRequest)){throw new SessionAuthenticationException("短信发送目标与该手机号不一致!"); }//数据库查询当前手机号是否注册过UserDetails myUserDetails = userDetailsService.loadUserByUsername(mobileInRequest); if(Objects.isNull(myUserDetails)){throw new SessionAuthenticationException("您输入的手机号不是系统的注册用户"); }//校验完毕并且没有抛出异常的情况下,移除session中保存的验证码信息session.removeAttribute("sms_key"); }}
注意:一定要为"/smslogin"访问路径配置为permitAll访问权限
文章图片
到这里,我们可以讲一下整体的短信验证登录流程,如上面的时序图。
- 首先用户发起“获取短信验证码”请求,SmsCodeController中调用短信服务商接口发送短信,并将短信发送的“谜底”保存在session中。
- 当用户发起登录请求,首先要经过SmsCodeValidateFilter对谜底和用户输入进行比对,比对失败则返回短信验证码校验失败
- 当短信验证码校验成功,继续执行过滤器链中的SmsCodeAuthenticationFilter对用户进行认证授权。
短信验证码登录认证
文章图片
我们可以仿照用户密码登录的流程,完成相关类的动态替换
由上图可以看出,短信验证码的登录认证逻辑和用户密码的登录认证流程是一样的。所以:
SmsCodeAuthenticationFilter仿造UsernamePasswordAuthenticationFilter进行开发
SmsCodeAuthenticationProvider仿造DaoAuthenticationProvider进行开发。
模拟实现:只不过将用户名、密码换成手机号进行认证,短信验证码在此部分已经没有用了,因为我们在SmsCodeValidateFilter已经验证过了。
/** * 仿造UsernamePasswordAuthenticationFilter开发 */public class SmsCodeAuthenticationFilter extends AbstractAuthenticationProcessingFilter {public static final String SPRING_SECURITY_FORM_MOBILE_KEY = "mobile"; private String mobileParameter = SPRING_SECURITY_FORM_MOBILE_KEY ; //请求中携带手机号的参数名称private boolean postOnly = true; //指定当前过滤器是否只处理POST请求//默认处理的请求private static final AntPathRequestMatcher DEFAULT_ANT_PATH_REQUEST_MATCHER = new AntPathRequestMatcher("/smslogin", "POST"); public SmsCodeAuthenticationFilter() {//指定当前过滤器处理的请求super(DEFAULT_ANT_PATH_REQUEST_MATCHER); }//尝试进行认证public Authentication attemptAuthentication(HttpServletRequest request,HttpServletResponse response)throws AuthenticationException {if (this.postOnly && !request.getMethod().equals("POST")) {throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod()); } else {String mobile = this.obtainMobile(request); if (mobile == null) {mobile = ""; }mobile = mobile.trim(); //认证前---手机号码是认证主体SmsCodeAuthenticationToken authRequest = new SmsCodeAuthenticationToken(mobile); //设置details---默认是sessionid和remoteaddrthis.setDetails(request, authRequest); return this.getAuthenticationManager().authenticate(authRequest); }}protected String obtainMobile(HttpServletRequest request) {return request.getParameter(this.mobileParameter); }protected void setDetails(HttpServletRequest request, SmsCodeAuthenticationToken authRequest) {authRequest.setDetails(this.authenticationDetailsSource.buildDetails(request)); }public void setMobileParameter(String mobileParameter) {Assert.hasText(mobileParameter, "Username parameter must not be empty or null"); this.mobileParameter = mobileParameter; }public void setPostOnly(boolean postOnly) {this.postOnly = postOnly; }public final String getMobileParameter() {return this.mobileParameter; }}
认证令牌也需要替换:
public class SmsCodeAuthenticationToken extends AbstractAuthenticationToken {private static final long serialVersionUID = SpringSecurityCoreVersion.SERIAL_VERSION_UID; //存放认证信息,认证之前存放手机号,认证之后存放登录的用户private final Object principal; //认证前public SmsCodeAuthenticationToken(String mobile) {super((Collection)null); this.principal = mobile; this.setAuthenticated(false); }//认证后,会设置相关的权限public SmsCodeAuthenticationToken(Object principal, Collection extends GrantedAuthority> authorities) {super(authorities); this.principal = principal; super.setAuthenticated(true); }public Object getCredentials() {return null; }public Object getPrincipal() {return this.principal; }public void setAuthenticated(boolean isAuthenticated) throws IllegalArgumentException {if (isAuthenticated) {throw new IllegalArgumentException("Cannot set this token to trusted - use constructor which takes a GrantedAuthority list instead"); } else {super.setAuthenticated(false); }}public void eraseCredentials() {super.eraseCredentials(); }}
当前还需要提供能够对我们当前自定义令牌对象起到认证作用的provider,仿照DaoAuthenticationProvider
public class SmsCodeAuthenticationProvider implements AuthenticationProvider{private UserDetailsService userDetailsService; public UserDetailsService getUserDetailsService() {return userDetailsService; }public void setUserDetailsService(UserDetailsService userDetailsService) {this.userDetailsService = userDetailsService; }/*** 进行身份认证的逻辑* @param authentication就是我们传入的Token* @return* @throws AuthenticationException*/@Overridepublic Authentication authenticate(Authentication authentication) throws AuthenticationException {//利用UserDetailsService获取用户信息,拿到用户信息后重新组装一个已认证的AuthenticationSmsCodeAuthenticationToken authenticationToken = (SmsCodeAuthenticationToken)authentication; UserDetails user = userDetailsService.loadUserByUsername((String) authenticationToken.getPrincipal()); //根据手机号码拿到用户信息if(user == null){throw new InternalAuthenticationServiceException("无法获取用户信息"); }//设置新的认证主体SmsCodeAuthenticationToken authenticationResult = new SmsCodeAuthenticationToken(user,user.getAuthorities()); //copy detailsauthenticationResult.setDetails(authenticationToken.getDetails()); //返回新的令牌对象return authenticationResult; }/*** AuthenticationManager挑选一个AuthenticationProvider* 来处理传入进来的Token就是根据supports方法来判断的* @param aClass* @return*/@Overridepublic boolean supports(Class> aClass) {//isAssignableFrom: 判断当前的Class对象所表示的类,// 是不是参数中传递的Class对象所表示的类的父类,超接口,或者是相同的类型。// 是则返回true,否则返回false。return SmsCodeAuthenticationToken.class.isAssignableFrom(aClass); }}
配置类进行综合组装 最后我们将以上实现进行组装,并将以上接口实现以配置的方式告知Spring Security。因为配置代码比较多,所以我们单独抽取一个关于短信验证码的配置类SmsCodeSecurityConfig,继承自SecurityConfigurerAdapter。
@Componentpublic class SmsCodeSecurityConfig extends SecurityConfigurerAdapter{@Resourceprivate MyFailHandler myAuthenticationFailureHandler; //这里不能直接注入,否则会造成依赖注入的问题发生private UserDetailsService myUserDetailsService; @Resourceprivate SmsCodeValidateFilter smsCodeValidateFilter; @Overridepublic void configure(HttpSecurity http) throws Exception {SmsCodeAuthenticationFilter smsCodeAuthenticationFilter = new SmsCodeAuthenticationFilter(); smsCodeAuthenticationFilter.setAuthenticationManager(http.getSharedObject(AuthenticationManager.class)); //有则配置,无则不配置//smsCodeAuthenticationFilter.setAuthenticationSuccessHandler(myAuthenticationSuccessHandler); smsCodeAuthenticationFilter.setAuthenticationFailureHandler(myAuthenticationFailureHandler); // 获取验证码登录令牌校验的提供者SmsCodeAuthenticationProvider smsCodeAuthenticationProvider = new SmsCodeAuthenticationProvider(); smsCodeAuthenticationProvider.setUserDetailsService(myUserDetailsService); //在用户密码过滤器前面加入短信验证码校验过滤器http.addFilterBefore(smsCodeValidateFilter, UsernamePasswordAuthenticationFilter.class); //在用户密码过滤器后面加入短信验证码认证授权过滤器http.authenticationProvider(smsCodeAuthenticationProvider).addFilterAfter(smsCodeAuthenticationFilter, UsernamePasswordAuthenticationFilter.class); }}
该配置类可以用以下代码,集成到SecurityConfig中。
文章图片
完整配置
@Configurationpublic class SecurityConfig extends WebSecurityConfigurerAdapter {private ObjectMapper objectMapper=new ObjectMapper(); @Resourceprivate CaptchaCodeFilter captchaCodeFilter; @Resourceprivate SmsCodeSecurityConfig smsCodeSecurityConfig; @BeanPasswordEncoder passwordEncoder() {return NoOpPasswordEncoder.getInstance(); }@Overridepublic void configure(WebSecurity web) throws Exception {web.ignoring().antMatchers("/js/**", "/css/**","/images/**"); }//数据源注入@AutowiredDataSource dataSource; //持久化令牌配置@BeanJdbcTokenRepositoryImpl jdbcTokenRepository() {JdbcTokenRepositoryImpl jdbcTokenRepository = new JdbcTokenRepositoryImpl(); jdbcTokenRepository.setDataSource(dataSource); return jdbcTokenRepository; }//用户配置@Override@Beanprotected UserDetailsService userDetailsService() {JdbcUserDetailsManager manager = new JdbcUserDetailsManager(); manager.setDataSource(dataSource); if (!manager.userExists("dhy")) {manager.createUser(User.withUsername("dhy").password("123").roles("admin").build()); }if (!manager.userExists("大忽悠")) {manager.createUser(User.withUsername("大忽悠").password("123").roles("user").build()); }//模拟电话号码if (!manager.userExists("123456789")) {manager.createUser(User.withUsername("123456789").password("").roles("user").build()); }return manager; }@Overrideprotected void configure(HttpSecurity http) throws Exception { //设置一下userDetailServicesmsCodeSecurityConfig.setMyUserDetailsService(userDetailsService()); http.//处理需要认证的请求authorizeRequests()//放行请求,前提:是对应的角色才行.antMatchers("/admin/**").hasRole("admin").antMatchers("/user/**").hasRole("user")//无需登录凭证,即可放行.antMatchers("/kaptcha","/smscode","/smslogin").permitAll()//放行验证码的显示请求//剩余的请求都需要认证才可以放行.anyRequest().authenticated().and()//表单形式登录的个性化配置.formLogin().loginPage("/login.html").permitAll().loginProcessingUrl("/login").permitAll().defaultSuccessUrl("/main.html")//可以记住上一次的请求路径//登录失败的处理器.failureHandler(new MyFailHandler()).and()//退出登录相关设置.logout()//退出登录的请求,是再没退出前发出的,因此此时还有登录凭证//可以访问.logoutUrl("/logout")//此时已经退出了登录,登录凭证没了//那么想要访问非登录页面的请求,就必须保证这个请求无需凭证即可访问.logoutSuccessUrl("/logout.html").permitAll()//退出登录的时候,删除对应的cookie.deleteCookies("JSESSIONID").and()//记住我相关设置.rememberMe()//预定义key相关设置,默认是一串uuid.key("dhy")//令牌的持久化.tokenRepository(jdbcTokenRepository()).and()//应用手机验证码的配置.apply(smsCodeSecurityConfig).and()//图形验证码.addFilterBefore(captchaCodeFilter, UsernamePasswordAuthenticationFilter.class)//csrf关闭.csrf().disable(); }//角色继承@BeanRoleHierarchy roleHierarchy() {RoleHierarchyImpl hierarchy = new RoleHierarchyImpl(); hierarchy.setHierarchy("ROLE_admin > ROLE_user"); return hierarchy; }}
【Spring|Spring Security短信验证码实现详解】以上就是Spring Security短信验证码实现详解的详细内容,更多关于Spring Security短信验证码的资料请关注脚本之家其它相关文章!
推荐阅读
- Activiti(一)SpringBoot2集成Activiti6
- SpringBoot调用公共模块的自定义注解失效的解决
- 解决SpringBoot引用别的模块无法注入的问题
- 2018-07-09|2018-07-09 Spring 的DBCP,c3p0
- spring|spring boot项目启动websocket
- Spring|Spring Boot 整合 Activiti6.0.0
- Spring集成|Spring集成 Mina
- springboot使用redis缓存
- Spring|Spring 框架之 AOP 原理剖析已经出炉!!!预定的童鞋可以识别下发二维码去看了
- Spring|Spring Boot之ImportSelector