第一步:新建filter,这里以手机验证码登录为例子
/**
* @Author: 朱维
* @Date 16:52 2019/11/27
* /phoneLogin?telephone=13000000000&smsCode=1000
*/
public class PhoneLoginAuthenticationFilter extends AbstractAuthenticationProcessingFilter {
/**
* 验证码登录请求参数:手机号码
*/
private static final String SPRING_SECURITY_RESTFUL_PHONE_KEY = "telephone";
/**
* 验证码登录请求参数:短信验证码
*/
private static final String SPRING_SECURITY_RESTFUL_VERIFY_CODE_KEY = "smsCode";
/**
* 验证码登录请求参数:登录地址
*/
private static final String SPRING_SECURITY_RESTFUL_LOGIN_URL = "/phone-login";
private boolean postOnly = true;
public PhoneLoginAuthenticationFilter() {
super(new AntPathRequestMatcher(SPRING_SECURITY_RESTFUL_LOGIN_URL, "POST"));
}
@Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
if (postOnly && !request.getMethod().equals("POST")) {
throw new AuthenticationServiceException(
"Authentication method not supported: " + request.getMethod());
}
AbstractAuthenticationToken authRequest;
String principal;
String credentials;
// 手机验证码登陆
principal = obtainParameter(request, SPRING_SECURITY_RESTFUL_PHONE_KEY);
credentials = obtainParameter(request, SPRING_SECURITY_RESTFUL_VERIFY_CODE_KEY);
principal = principal.trim();
authRequest = new PhoneAuthenticationToken(principal, credentials);
// Allow subclasses to set the "details" property
setDetails(request, authRequest);
return this.getAuthenticationManager().authenticate(authRequest);
}
private void setDetails(HttpServletRequest request,
AbstractAuthenticationToken authRequest) {
authRequest.setDetails(authenticationDetailsSource.buildDetails(request));
}
private String obtainParameter(HttpServletRequest request, String parameter) {
String result = request.getParameter(parameter);
return result == null ? "" : result;
}
第二步新建provider
/**
* 手机验证码登录
* @Author: 朱维
* @Date 16:26 2019/11/27
*/
public class PhoneAuthenticationProvider extends MyAbstractUserDetailsAuthenticationProvider {
private UserDetailsService userDetailsService;
@Autowired
private RedisTemplate redisTemplate;
@Override
protected void additionalAuthenticationChecks(UserDetails var1, Authentication authentication) throws AuthenticationException {
if(authentication.getCredentials() == null) {
this.logger.debug("