Spring?Security短信驗證碼實現(xiàn)詳解
需求
- 輸入手機號碼,點擊獲取按鈕,服務端接受請求發(fā)送短信
- 用戶輸入驗證碼點擊登錄
- 手機號碼必須屬于系統(tǒng)的注冊用戶,并且唯一
- 手機號與驗證碼正確性及其關系必須經(jīng)過校驗
- 登錄后用戶具有手機號對應的用戶的角色及權限
實現(xiàn)步驟
- 獲取短信驗證碼
- 短信驗證碼校驗過濾器
- 短信驗證碼登錄認證過濾器
- 綜合配置
獲取短信驗證碼
在這一步我們需要寫一個controller接收用戶的獲取驗證碼請求。注意:一定要為“/smscode”訪問路徑配置為permitAll訪問權限,因為spring security默認攔截所有路徑,除了默認配置的/login請求,只有經(jīng)過登錄認證過后的請求才會默認可以訪問。
@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 { //先從數(shù)據(jù)庫中查找,判斷對應的手機號是否存在 UserDetails userDetails = userDetailsService.loadUserByUsername(mobile); //這個地方userDetailsService如果使用spring security提供的話,找不到用戶名會直接拋出異常,走不到這里來 //即直接去了登錄失敗的處理器 if(userDetails == null){ return "您輸入的手機號不是系統(tǒng)注冊用戶"; } //commons-lang3包下的工具類,生成指定長度為4的隨機數(shù)字字符串 String randomNumeric = RandomStringUtils.randomNumeric(4); //驗證碼,過期時間,手機號 SmsCode smsCode = new SmsCode(randomNumeric,60,mobile); //TODO 此處調(diào)用驗證碼發(fā)送服務接口 //這里只是模擬調(diào)用 log.info(smsCode.getCode() + "=》" + mobile); //將驗證碼存放到session中 session.setAttribute("sms_key",smsCode); return "短信息已經(jīng)發(fā)送到您的手機"; } }
上文中我們只做了短信驗證碼接口調(diào)用的模擬,沒有真正的向手機發(fā)送驗證碼。此部分接口請結(jié)合短信發(fā)送服務提供商接口實現(xiàn)。
短信驗證碼發(fā)送之后,將驗證碼“謎底”保存在session中。
使用SmsCode封裝短信驗證碼的謎底,用于后續(xù)登錄過程中進行校驗。
public class SmsCode { private String code; //短信驗證碼 private LocalDateTime expireTime; //驗證碼的過期時間 private String mobile; //發(fā)送手機號 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/**"); } //數(shù)據(jù)源注入 @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() //退出登錄的請求,是再沒退出前發(fā)出的,因此此時還有登錄憑證 //可以訪問 .logoutUrl("/logout") //此時已經(jīng)退出了登錄,登錄憑證沒了 //那么想要訪問非登錄頁面的請求,就必須保證這個請求無需憑證即可訪問 .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; } }
短信驗證碼校驗過濾器
短信驗證碼的校驗過濾器,和圖片驗證碼的驗證實現(xiàn)原理是一致的。都是通過繼承OncePerRequestFilter實現(xiàn)一個Spring環(huán)境下的過濾器。其核心校驗規(guī)則如下:
- 用戶登錄時手機號不能為空
- 用戶登錄時短信驗證碼不能為空
- 用戶登陸時在session中必須存在對應的校驗謎底(獲取驗證碼時存放的)
- 用戶登錄時輸入的短信驗證碼必須和“謎底”中的驗證碼一致
- 用戶登錄時輸入的手機號必須和“謎底”中保存的手機號一致
- 用戶登錄時輸入的手機號必須是系統(tǒng)注冊用戶的手機號,并且唯一
@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("短信發(fā)送目標與該手機號不一致!"); } //數(shù)據(jù)庫查詢當前手機號是否注冊過 UserDetails myUserDetails = userDetailsService.loadUserByUsername(mobileInRequest); if(Objects.isNull(myUserDetails)){ throw new SessionAuthenticationException("您輸入的手機號不是系統(tǒng)的注冊用戶"); } //校驗完畢并且沒有拋出異常的情況下,移除session中保存的驗證碼信息 session.removeAttribute("sms_key"); } }
注意:一定要為"/smslogin"訪問路徑配置為permitAll訪問權限
到這里,我們可以講一下整體的短信驗證登錄流程,如上面的時序圖。
- 首先用戶發(fā)起“獲取短信驗證碼”請求,SmsCodeController中調(diào)用短信服務商接口發(fā)送短信,并將短信發(fā)送的“謎底”保存在session中。
- 當用戶發(fā)起登錄請求,首先要經(jīng)過SmsCodeValidateFilter對謎底和用戶輸入進行比對,比對失敗則返回短信驗證碼校驗失敗
- 當短信驗證碼校驗成功,繼續(xù)執(zhí)行過濾器鏈中的SmsCodeAuthenticationFilter對用戶進行認證授權。
短信驗證碼登錄認證
我們可以仿照用戶密碼登錄的流程,完成相關類的動態(tài)替換
由上圖可以看出,短信驗證碼的登錄認證邏輯和用戶密碼的登錄認證流程是一樣的。所以:
SmsCodeAuthenticationFilter仿造UsernamePasswordAuthenticationFilter進行開發(fā)
SmsCodeAuthenticationProvider仿造DaoAuthenticationProvider進行開發(fā)。
模擬實現(xiàn):只不過將用戶名、密碼換成手機號進行認證,短信驗證碼在此部分已經(jīng)沒有用了,因為我們在SmsCodeValidateFilter已經(jīng)驗證過了。
/** * 仿造UsernamePasswordAuthenticationFilter開發(fā) */ public class SmsCodeAuthenticationFilter extends AbstractAuthenticationProcessingFilter { public static final String SPRING_SECURITY_FORM_MOBILE_KEY = "mobile"; private String mobileParameter = SPRING_SECURITY_FORM_MOBILE_KEY ; //請求中攜帶手機號的參數(shù)名稱 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(); } }
當前還需要提供能夠?qū)ξ覀儺斍白远x令牌對象起到認證作用的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()); //根據(jù)手機號碼拿到用戶信息 if(user == null){ throw new InternalAuthenticationServiceException("無法獲取用戶信息"); } //設置新的認證主體 SmsCodeAuthenticationToken authenticationResult = new SmsCodeAuthenticationToken(user,user.getAuthorities()); //copy details authenticationResult.setDetails(authenticationToken.getDetails()); //返回新的令牌對象 return authenticationResult; } /** * AuthenticationManager挑選一個AuthenticationProvider * 來處理傳入進來的Token就是根據(jù)supports方法來判斷的 * @param aClass * @return */ @Override public boolean supports(Class<?> aClass) { //isAssignableFrom: 判斷當前的Class對象所表示的類, // 是不是參數(shù)中傳遞的Class對象所表示的類的父類,超接口,或者是相同的類型。 // 是則返回true,否則返回false。 return SmsCodeAuthenticationToken.class.isAssignableFrom(aClass); } }
配置類進行綜合組裝
最后我們將以上實現(xiàn)進行組裝,并將以上接口實現(xiàn)以配置的方式告知Spring Security。因為配置代碼比較多,所以我們單獨抽取一個關于短信驗證碼的配置類SmsCodeSecurityConfig,繼承自SecurityConfigurerAdapter。
@Component public class SmsCodeSecurityConfig extends SecurityConfigurerAdapter<DefaultSecurityFilterChain, HttpSecurity> { @Resource private MyFailHandler myAuthenticationFailureHandler; //這里不能直接注入,否則會造成依賴注入的問題發(fā)生 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/**");
}
//數(shù)據(jù)源注入
@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()
//退出登錄的請求,是再沒退出前發(fā)出的,因此此時還有登錄憑證
//可以訪問
.logoutUrl("/logout")
//此時已經(jīng)退出了登錄,登錄憑證沒了
//那么想要訪問非登錄頁面的請求,就必須保證這個請求無需憑證即可訪問
.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;
}
}
以上就是Spring Security短信驗證碼實現(xiàn)詳解的詳細內(nèi)容,更多關于Spring Security短信驗證碼的資料請關注腳本之家其它相關文章!
- SpringBoot實現(xiàn)短信驗證碼校驗方法思路詳解
- Spring Security Oauth2.0 實現(xiàn)短信驗證碼登錄示例
- SpringBoot + SpringSecurity 短信驗證碼登錄功能實現(xiàn)
- SpringBoot+Security 發(fā)送短信驗證碼的實現(xiàn)
- Spring Security 實現(xiàn)短信驗證碼登錄功能
- SpringSceurity實現(xiàn)短信驗證碼登陸
- springboot短信驗證碼登錄功能的實現(xiàn)
- SpringBoot發(fā)送短信驗證碼的實例
- Spring中使用騰訊云發(fā)送短信驗證碼的實現(xiàn)示例
相關文章
java執(zhí)行SQL語句實現(xiàn)查詢的通用方法詳解
這篇文章主要介紹了java執(zhí)行SQL語句實現(xiàn)查詢的通用方法詳解,具有一定借鑒價值,需要的朋友可以參考下。2017-12-12解決springboot中配置過濾器以及可能出現(xiàn)的問題
這篇文章主要介紹了解決springboot中配置過濾器以及可能出現(xiàn)的問題,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-09-09@valid 無法觸發(fā)BindingResult的解決
這篇文章主要介紹了@valid 無法觸發(fā)BindingResult的解決方案,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-12-12SpringBoot下使用MyBatis-Puls代碼生成器的方法
這篇文章主要介紹了SpringBoot下使用MyBatis-Puls代碼生成器的方法,本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-10-10Java中實現(xiàn)在一個方法中調(diào)用另一個方法
下面小編就為大家分享一篇Java中實現(xiàn)在一個方法中調(diào)用另一個方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-02-02