亲宝软件园·资讯

展开

Spring Security短信验证码

大忽悠爱忽悠 人气:0

需求

实现步骤

获取短信验证码

在这一步我们需要写一个controller接收用户的获取验证码请求。注意:一定要为“/smscode”访问路径配置为permitAll访问权限,因为spring security默认拦截所有路径,除了默认配置的/login请求,只有经过登录认证过后的请求才会默认可以访问。

@Slf4j
@RestController
public class SmsController {

    @Autowired
    private UserDetailsService userDetailsService;

    //获取短信验证码
    @RequestMapping(value="/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(){
        return  LocalDateTime.now().isAfter(expireTime);
    }

    public String getCode() {
        return code;
    }

    public String getMobile() {
       return mobile;
    }

}

前端初始化短信登录界面

<h1>短信登陆</h1>
<form action="/smslogin" method="post">
    <span>手机号码:</span><input type="text" name="mobile" id="mobile"> <br>
    <span>短信验证码:</span><input type="text" name="smsCode" id="smsCode" >
    <input type="button" onclick="getSmsCode()" value="获取"><br>
    <input type="button" onclick="smslogin()" value="登陆">
</form>

<script>

   function getSmsCode()
   {
     $.ajax({
       type: "GET",
       url: "/smscode",
        data:{"mobile":$("#mobile").val()},
       success: function (res) {
         console.log(res)
       },
       error: function (e) {
         console.log(e.responseText);
       }
     });
   }

    function smslogin() {
      var mobile = $("#mobile").val();
      var smsCode = $("#smsCode").val();
      if (mobile === "" || smsCode === "") {
        alert('手机号和短信验证码均不能为空');
        return;
      }
      $.ajax({
        type: "POST",
        url: "/smslogin",
        data: {
          "mobile": mobile,
          "smsCode": smsCode
        },
        success: function (res) {
          console.log(res)
        },
        error: function (e) {
          console.log(e.responseText);
        }
      });
    }
</script>

spring security配置类

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

   private ObjectMapper objectMapper=new ObjectMapper();

   @Resource
   private CaptchaCodeFilter captchaCodeFilter;

   @Bean
   PasswordEncoder passwordEncoder() {
      return NoOpPasswordEncoder.getInstance();
   }

   @Override
   public void configure(WebSecurity web) throws Exception {
      web.ignoring().antMatchers("/js/**", "/css/**","/images/**");
   }

   //数据源注入
   @Autowired
   DataSource dataSource;

   //持久化令牌配置
   @Bean
   JdbcTokenRepositoryImpl jdbcTokenRepository() {
      JdbcTokenRepositoryImpl jdbcTokenRepository = new JdbcTokenRepositoryImpl();
      jdbcTokenRepository.setDataSource(dataSource);
      return jdbcTokenRepository;
   }


   //用户配置
   @Override
   @Bean
   protected 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;
   }

   @Override
   protected 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();

   }

   //角色继承
   @Bean
   RoleHierarchy roleHierarchy() {
      RoleHierarchyImpl hierarchy = new RoleHierarchyImpl();
      hierarchy.setHierarchy("ROLE_admin > ROLE_user");
      return hierarchy;
   }

}

短信验证码校验过滤器

短信验证码的校验过滤器,和图片验证码的验证实现原理是一致的。都是通过继承OncePerRequestFilter实现一个Spring环境下的过滤器。其核心校验规则如下:

@Component
public class SmsCodeValidateFilter extends OncePerRequestFilter {

    @Resource
    UserDetailsService userDetailsService;

    @Resource
    MyFailHandler myAuthenticationFailureHandler;

    @Override
    protected void doFilterInternal(HttpServletRequest request,
                                    HttpServletResponse response,
                                    FilterChain filterChain)
            throws ServletException, IOException {
       //该过滤器只负责拦截验证码登录的请求
       //并且请求必须是post
        if (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访问权限

到这里,我们可以讲一下整体的短信验证登录流程,如上面的时序图。

短信验证码登录认证

我们可以仿照用户密码登录的流程,完成相关类的动态替换

由上图可以看出,短信验证码的登录认证逻辑和用户密码的登录认证流程是一样的。所以:

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和remoteaddr
            this.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
     */
    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {

        //利用UserDetailsService获取用户信息,拿到用户信息后重新组装一个已认证的Authentication
        SmsCodeAuthenticationToken authenticationToken = (SmsCodeAuthenticationToken)authentication;
        UserDetails user = userDetailsService.loadUserByUsername((String) authenticationToken.getPrincipal());  //根据手机号码拿到用户信息
        if(user == null){
            throw new InternalAuthenticationServiceException("无法获取用户信息");
        }
        //设置新的认证主体
        SmsCodeAuthenticationToken authenticationResult = new SmsCodeAuthenticationToken(user,user.getAuthorities());
        //copy details
        authenticationResult.setDetails(authenticationToken.getDetails());
        //返回新的令牌对象
        return authenticationResult;
    }

    /**
     * AuthenticationManager挑选一个AuthenticationProvider
     * 来处理传入进来的Token就是根据supports方法来判断的
     * @param aClass
     * @return
     */
    @Override
    public boolean supports(Class<?> aClass) {
        //isAssignableFrom: 判断当前的Class对象所表示的类,
        // 是不是参数中传递的Class对象所表示的类的父类,超接口,或者是相同的类型。
        // 是则返回true,否则返回false。
        return SmsCodeAuthenticationToken.class.isAssignableFrom(aClass);
    }
}

配置类进行综合组装

最后我们将以上实现进行组装,并将以上接口实现以配置的方式告知Spring Security。因为配置代码比较多,所以我们单独抽取一个关于短信验证码的配置类SmsCodeSecurityConfig,继承自SecurityConfigurerAdapter。

@Component
public class SmsCodeSecurityConfig extends SecurityConfigurerAdapter<DefaultSecurityFilterChain, HttpSecurity> {

    @Resource
    private MyFailHandler myAuthenticationFailureHandler;

      //这里不能直接注入,否则会造成依赖注入的问题发生
    private UserDetailsService myUserDetailsService;

    @Resource
    private SmsCodeValidateFilter smsCodeValidateFilter;

    @Override
    public 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中。

完整配置

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

   private ObjectMapper objectMapper=new ObjectMapper();

   @Resource
   private CaptchaCodeFilter captchaCodeFilter;

   @Resource
   private SmsCodeSecurityConfig smsCodeSecurityConfig;

   @Bean
   PasswordEncoder passwordEncoder() {
      return NoOpPasswordEncoder.getInstance();
   }

   @Override
   public void configure(WebSecurity web) throws Exception {
      web.ignoring().antMatchers("/js/**", "/css/**","/images/**");
   }

   //数据源注入
   @Autowired
   DataSource dataSource;

   //持久化令牌配置
   @Bean
   JdbcTokenRepositoryImpl jdbcTokenRepository() {
      JdbcTokenRepositoryImpl jdbcTokenRepository = new JdbcTokenRepositoryImpl();
      jdbcTokenRepository.setDataSource(dataSource);
      return jdbcTokenRepository;
   }


   //用户配置
   @Override
   @Bean
   protected 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;
   }

   @Override
   protected void configure(HttpSecurity http) throws Exception {

 //设置一下userDetailService
      smsCodeSecurityConfig.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();

   }

   //角色继承
   @Bean
   RoleHierarchy roleHierarchy() {
      RoleHierarchyImpl hierarchy = new RoleHierarchyImpl();
      hierarchy.setHierarchy("ROLE_admin > ROLE_user");
      return hierarchy;
   }

} 

加载全部内容

相关教程
猜你喜欢
用户评论