目前常见的社交软件、购物软件、支付软件、理财软件等,均须要用户进行登陆才可享受软件提供的服务。目前主流的登陆方式主要有 3 种:帐号密码登陆、短信验证码登陆和第三方受权登陆。咱们已经实现了帐号密码和第三方受权登陆。本章咱们将使用
Spring Security
实现短信验证码登陆。java
在Spring Security源码分析一:Spring Security认证过程和Spring Security源码分析二:Spring Security受权过程两章中。咱们已经详细解读过Spring Security
如何处理用户名和密码登陆。(其实就是过滤器链)本章咱们将仿照用户名密码来显示短信登陆。git
SmsCodeAuthenticationFilter
对应用户名密码登陆的UsernamePasswordAuthenticationFilter一样继承AbstractAuthenticationProcessingFiltergithub
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
Authenticaiton
的实现类SmsCodeAuthenticationToken
(未认证)AuthenticationManager
的 authenticate
方法进行验证(即SmsCodeAuthenticationProvider
)SmsCodeAuthenticationToken
对应用户名密码登陆的UsernamePasswordAuthenticationToken
app
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
对应用户名密码登陆的DaoAuthenticationProvideride
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;
}
}
复制代码
@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);
}
}
复制代码
@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
post
从个人 github 中下载,github.com/longfeizhen…this