概述
在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簡訊登入配置
@Component
public 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
程式碼下載
從我的 github 中下載,github.com/longfeizhen…