Spring Security源碼分析五:Spring Security實現簡訊登錄
目前常見的社交軟體、購物軟體、支付軟體、理財軟體等,均需要用戶進行登錄才可享受軟體提供的服務。目前主流的登錄方式主要有 3 種:賬號密碼登錄、簡訊驗證碼登錄和第三方授權登錄。我們已經實現了賬號密碼和第三方授權登錄。本章我們將使用Spring Security
實現簡訊驗證碼登錄。
概述
在Spring Security源碼分析一:Spring Security認證過程和Spring Security源碼分析二:Spring Security授權過程兩章中。我們已經詳細解讀過Spring Security
如何處理用戶名和密碼登錄。(其實就是過濾器鏈)本章我們將仿照用戶名密碼來顯示簡訊登錄。
目錄結構
SmsCodeAuthenticationFilter
SmsCodeAuthenticationFilter
對應用戶名密碼登錄的UsernamePasswordAuthenticationFilter同樣繼承AbstractAuthenticationProcessingFilter
public class SmsCodeAuthenticationFilter extends AbstractAuthenticationProcessingFilter { /** * request中必須含有mobile參數 */ private String mobileParameter = SecurityConstants.DEFAULT_PARAMETER_NAME_MOBILE; /** * post請求 */ private boolean postOnly = true; protected SmsCodeAuthenticationFilter() { /** * 處理的手機驗證碼登錄請求處理url */ super(new AntPathRequestMatcher(SecurityConstants.DEFAULT_SIGN_IN_PROCESSING_URL_MOBILE, "POST")); } @Override public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException, IOException, ServletException { //判斷是是不是post請求 if (postOnly && !request.getMethod().equals("POST")) { throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod()); } //從請求中獲取手機號碼 String mobile = obtainMobile(request); if (mobile == null) { mobile = ""; } mobile = mobile.trim(); //創建SmsCodeAuthenticationToken(未認證) SmsCodeAuthenticationToken authRequest = new SmsCodeAuthenticationToken(mobile); //設置用戶信息 setDetails(request, authRequest); //返回Authentication實例 return this.getAuthenticationManager().authenticate(authRequest); } /** * 獲取手機號 */ protected String obtainMobile(HttpServletRequest request) { return request.getParameter(mobileParameter); } protected void setDetails(HttpServletRequest request, SmsCodeAuthenticationToken authRequest) { authRequest.setDetails(authenticationDetailsSource.buildDetails(request)); } public void setMobileParameter(String usernameParameter) { Assert.hasText(usernameParameter, "Username parameter must not be empty or null"); this.mobileParameter = usernameParameter; } public void setPostOnly(boolean postOnly) { this.postOnly = postOnly; } public final String getMobileParameter() { return mobileParameter; }}
- 認證請求的方法必須為
POST
- 從request中獲取手機號
- 封裝成自己的
Authenticaiton
的實現類SmsCodeAuthenticationToken
(未認證) - 調用
AuthenticationManager
的authenticate
方法進行驗證(即SmsCodeAuthenticationProvider
)
SmsCodeAuthenticationToken
SmsCodeAuthenticationToken
對應用戶名密碼登錄的UsernamePasswordAuthenticationToken
public class SmsCodeAuthenticationToken extends AbstractAuthenticationToken { private static final long serialVersionUID = 2383092775910246006L; /** * 手機號 */ private final Object principal; /** * SmsCodeAuthenticationFilter中構建的未認證的Authentication * @param mobile */ public SmsCodeAuthenticationToken(String mobile) { super(null); this.principal = mobile; setAuthenticated(false); } /** * SmsCodeAuthenticationProvider中構建已認證的Authentication * @param principal * @param authorities */ public SmsCodeAuthenticationToken(Object principal, Collection<? extends GrantedAuthority> authorities) { super(authorities); this.principal = principal; super.setAuthenticated(true); // must use super, as we override } @Override public Object getCredentials() { return null; } @Override public Object getPrincipal() { return this.principal; } /** * @param isAuthenticated * @throws IllegalArgumentException */ 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"); } super.setAuthenticated(false); } @Override public void eraseCredentials() { super.eraseCredentials(); }}
SmsCodeAuthenticationProvider
SmsCodeAuthenticationProvider
對應用戶名密碼登錄的DaoAuthenticationProvider
public class SmsCodeAuthenticationProvider implements AuthenticationProvider { private UserDetailsService userDetailsService; @Override public Authentication authenticate(Authentication authentication) throws AuthenticationException { SmsCodeAuthenticationToken authenticationToken = (SmsCodeAuthenticationToken) authentication; //調用自定義的userDetailsService認證 UserDetails user = userDetailsService.loadUserByUsername((String) authenticationToken.getPrincipal()); if (user == null) { throw new InternalAuthenticationServiceException("無法獲取用戶信息"); } //如果user不為空重新構建SmsCodeAuthenticationToken(已認證) SmsCodeAuthenticationToken authenticationResult = new SmsCodeAuthenticationToken(user, user.getAuthorities()); authenticationResult.setDetails(authenticationToken.getDetails()); return authenticationResult; } /** * 只有Authentication為SmsCodeAuthenticationToken使用此Provider認證 * @param authentication * @return */ @Override public boolean supports(Class<?> authentication) { return SmsCodeAuthenticationToken.class.isAssignableFrom(authentication); } public UserDetailsService getUserDetailsService() { return userDetailsService; } public void setUserDetailsService(UserDetailsService userDetailsService) { this.userDetailsService = userDetailsService; }}
SmsCodeAuthenticationSecurityConfig簡訊登錄配置
@Componentpublic class SmsCodeAuthenticationSecurityConfig extends SecurityConfigurerAdapter<DefaultSecurityFilterChain, HttpSecurity> { @Autowired private AuthenticationFailureHandler merryyouAuthenticationFailureHandler; @Autowired private UserDetailsService userDetailsService; @Override public void configure(HttpSecurity http) throws Exception { //自定義SmsCodeAuthenticationFilter過濾器 SmsCodeAuthenticationFilter smsCodeAuthenticationFilter = new SmsCodeAuthenticationFilter(); smsCodeAuthenticationFilter.setAuthenticationManager(http.getSharedObject(AuthenticationManager.class)); smsCodeAuthenticationFilter.setAuthenticationFailureHandler(merryyouAuthenticationFailureHandler); //設置自定義SmsCodeAuthenticationProvider的認證器userDetailsService SmsCodeAuthenticationProvider smsCodeAuthenticationProvider = new SmsCodeAuthenticationProvider(); smsCodeAuthenticationProvider.setUserDetailsService(userDetailsService); //在UsernamePasswordAuthenticationFilter過濾前執行 http.authenticationProvider(smsCodeAuthenticationProvider) .addFilterAfter(smsCodeAuthenticationFilter, UsernamePasswordAuthenticationFilter.class); }}
MerryyouSecurityConfig 主配置文件
@Override protected void configure(HttpSecurity http) throws Exception {// http.addFilterBefore(validateCodeFilter, UsernamePasswordAuthenticationFilter.class) http .formLogin()//使用表單登錄,不再使用默認httpBasic方式 .loginPage(SecurityConstants.DEFAULT_UNAUTHENTICATION_URL)//如果請求的URL需要認證則跳轉的URL .loginProcessingUrl(SecurityConstants.DEFAULT_SIGN_IN_PROCESSING_URL_FORM)//處理表單中自定義的登錄URL .and() .apply(validateCodeSecurityConfig)//驗證碼攔截 .and() .apply(smsCodeAuthenticationSecurityConfig) .and() .apply(merryyouSpringSocialConfigurer)//社交登錄 .and() .rememberMe()......
調試過程
簡訊登錄攔截請求/authentication/mobile
自定義SmsCodeAuthenticationProvider
效果如下:
代碼下載
從我的 github 中下載,https://github.com/longfeizheng/logback
作者:longfeizheng
鏈接:Spring Security源碼分析五:Spring Security實現簡訊登錄聲明:本文來源於極樂科技合作網站,版權歸作者所有,不代表本專欄觀點,若有什麼問題,請聯繫我們,謝謝!
推薦閱讀:
※用小說的形式講解Spring(1) —— 為什麼需要依賴注入
※周末薦書 | 《Spring實戰》(第4版)
※實體類的欄位的驗證應該寫在service層嗎?
※如何學好ssh框架,spring學起來怎麼這麼難呢?