spring security 自定义认证登录

短命女 2023-02-20 06:43 178阅读 0赞

**

spring security 自定义认证登录

**
1.概要
1.1.简介

spring security是一种基于 Spring AOP 和 Servlet 过滤器的安全框架,以此来管理权限认证等。

1.2.spring security 自定义认证流程
1)认证过程

  1. 生成未认证的AuthenticationToken
  2. ↑(获取信息) (根据AuthenticationToken分配provider
  3. AuthenticationFilter -> AuthenticationManager -> AuthenticationProvider
  4. ↓(认证)
  5. UserDetails(一般查询数据库获取)
  6. ↓(通过)
  7. 生成认证成功的AuthenticationToken
  8. ↓(存放)
  9. SecurityContextHolder

2)将AuthenticationFilter加入到security过滤链(资源服务器中配置),如:

http.addFilterBefore(AuthenticationFilter, AbstractPreAuthenticatedProcessingFilter.class)
或者:

http.addFilterAfter(AuthenticationFilter, UsernamePasswordAuthenticationFilter.class)
2.以手机号短信登录为例
2.1.开发环境
SpringBoot
Spring security
Redis
2.2.核心代码分析
2.2.1.自定义登录认证流程
2.2.1.1.自定义认证登录Token

  1. /** * 手机登录Token * * @author : CatalpaFlat */
  2. public class MobileLoginAuthenticationToken extends AbstractAuthenticationToken {
  3. private static final long serialVersionUID = SpringSecurityCoreVersion.SERIAL_VERSION_UID;
  4. private static final Logger logger = LoggerFactory.getLogger(MobileLoginAuthenticationToken.class.getName());
  5. private final Object principal;
  6. public MobileLoginAuthenticationToken(String mobile) {
  7. super(null);
  8. this.principal = mobile;
  9. this.setAuthenticated(false);
  10. logger.info("MobileLoginAuthenticationToken setAuthenticated ->false loading ...");
  11. }
  12. public MobileLoginAuthenticationToken(Object principal,
  13. Collection<? extends GrantedAuthority> authorities) {
  14. super(authorities);
  15. this.principal = principal;
  16. // must use super, as we override
  17. super.setAuthenticated(true);
  18. logger.info("MobileLoginAuthenticationToken setAuthenticated ->true loading ...");
  19. }
  20. @Override
  21. public void setAuthenticated(boolean authenticated) {
  22. if (authenticated) {
  23. throw new IllegalArgumentException(
  24. "Cannot set this token to trusted - use constructor which takes a GrantedAuthority list instead");
  25. }
  26. super.setAuthenticated(false);
  27. }
  28. @Override
  29. public Object getCredentials() {
  30. return null;
  31. }
  32. @Override
  33. public Object getPrincipal() {
  34. return this.principal;
  35. }
  36. @Override
  37. public void eraseCredentials() {
  38. super.eraseCredentials();
  39. }
  40. }

注:
setAuthenticated():判断是否已认证

在过滤器时,会生成一个未认证的AuthenticationToken,此时调用的是自定义token的setAuthenticated(),此时设置为false -> 未认证
在提供者时,会生成一个已认证的AuthenticationToken,此时调用的是父类的setAuthenticated(),此时设置为true -> 已认证
2.2.1.1.自定义认证登录过滤器

  1. /** * 手机短信登录过滤器 * * @author : CatalpaFlat */
  2. public class MobileLoginAuthenticationFilter extends AbstractAuthenticationProcessingFilter {
  3. private boolean postOnly = true;
  4. private static final Logger logger = LoggerFactory.getLogger(MobileLoginAuthenticationFilter.class.getName());
  5. @Getter
  6. @Setter
  7. private String mobileParameterName;
  8. public MobileLoginAuthenticationFilter(String mobileLoginUrl, String mobileParameterName,
  9. String httpMethod) {
  10. super(new AntPathRequestMatcher(mobileLoginUrl, httpMethod));
  11. this.mobileParameterName = mobileParameterName;
  12. logger.info("MobileLoginAuthenticationFilter loading ...");
  13. }
  14. @Override
  15. public Authentication attemptAuthentication(HttpServletRequest request,
  16. HttpServletResponse response) throws AuthenticationException, IOException, ServletException {
  17. if (postOnly && !request.getMethod().equals(HttpMethod.POST.name())) {
  18. throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod());
  19. }
  20. //get mobile
  21. String mobile = obtainMobile(request);
  22. //assemble token
  23. MobileLoginAuthenticationToken authRequest = new MobileLoginAuthenticationToken(mobile);
  24. // Allow subclasses to set the "details" property
  25. setDetails(request, authRequest);
  26. return this.getAuthenticationManager().authenticate(authRequest);
  27. }
  28. /** * 设置身份认证的详情信息 */
  29. private void setDetails(HttpServletRequest request, MobileLoginAuthenticationToken authRequest) {
  30. authRequest.setDetails(authenticationDetailsSource.buildDetails(request));
  31. }
  32. /** * 获取手机号 */
  33. private String obtainMobile(HttpServletRequest request) {
  34. return request.getParameter(mobileParameterName);
  35. }
  36. public void setPostOnly(boolean postOnly) {
  37. this.postOnly = postOnly;
  38. }
  39. }

注:attemptAuthentication()方法:

过滤指定的url、httpMethod
获取所需请求参数数据封装生成一个未认证的AuthenticationToken
传递给AuthenticationManager认证
2.2.1.1.自定义认证登录提供者

  1. /** * 手机短信登录认证提供者 * * @author : CatalpaFlat */
  2. public class MobileLoginAuthenticationProvider implements AuthenticationProvider {
  3. private static final Logger logger = LoggerFactory.getLogger(MobileLoginAuthenticationProvider.class.getName());
  4. @Getter
  5. @Setter
  6. private UserDetailsService customUserDetailsService;
  7. public MobileLoginAuthenticationProvider() {
  8. logger.info("MobileLoginAuthenticationProvider loading ...");
  9. }
  10. /** * 认证 */
  11. @Override
  12. public Authentication authenticate(Authentication authentication) throws AuthenticationException {
  13. //获取过滤器封装的token信息
  14. MobileLoginAuthenticationToken authenticationToken = (MobileLoginAuthenticationToken) authentication;
  15. //获取用户信息(数据库认证)
  16. UserDetails userDetails = customUserDetailsService.loadUserByUsername((String) authenticationToken.getPrincipal());
  17. //不通过
  18. if (userDetails == null) {
  19. throw new InternalAuthenticationServiceException("Unable to obtain user information");
  20. }
  21. //通过
  22. MobileLoginAuthenticationToken authenticationResult = new MobileLoginAuthenticationToken(userDetails, userDetails.getAuthorities());
  23. authenticationResult.setDetails(authenticationToken.getDetails());
  24. return authenticationResult;
  25. }
  26. /** * 根据token类型,来判断使用哪个Provider */
  27. @Override
  28. public boolean supports(Class<?> authentication) {
  29. return MobileLoginAuthenticationToken.class.isAssignableFrom(authentication);
  30. }
  31. }

注:authenticate()方法

获取过滤器封装的token信息
调取UserDetailsService获取用户信息(数据库认证)->判断通过与否
通过则封装一个新的AuthenticationToken,并返回
2.2.1.1.自定义认证登录认证配置

  1. @Configuration(SpringBeanNameConstant.DEFAULT_CUSTOM_MOBILE_LOGIN_AUTHENTICATION_SECURITY_CONFIG_BN)
  2. public class MobileLoginAuthenticationSecurityConfig extends SecurityConfigurerAdapter<DefaultSecurityFilterChain, HttpSecurity> {
  3. private static final Logger logger = LoggerFactory.getLogger(MobileLoginAuthenticationSecurityConfig.class.getName());
  4. @Value("${login.mobile.url}")
  5. private String defaultMobileLoginUrl;
  6. @Value("${login.mobile.parameter}")
  7. private String defaultMobileLoginParameter;
  8. @Value("${login.mobile.httpMethod}")
  9. private String defaultMobileLoginHttpMethod;
  10. @Autowired
  11. private CustomYmlConfig customYmlConfig;
  12. @Autowired
  13. private UserDetailsService customUserDetailsService;
  14. @Autowired
  15. private AuthenticationSuccessHandler customAuthenticationSuccessHandler;
  16. @Autowired
  17. private AuthenticationFailureHandler customAuthenticationFailureHandler;
  18. public MobileLoginAuthenticationSecurityConfig() {
  19. logger.info("MobileLoginAuthenticationSecurityConfig loading ...");
  20. }
  21. @Override
  22. public void configure(HttpSecurity http) throws Exception {
  23. MobilePOJO mobile = customYmlConfig.getLogins().getMobile();
  24. String url = mobile.getUrl();
  25. String parameter = mobile.getParameter().getMobile();
  26. String httpMethod = mobile.getHttpMethod();
  27. MobileLoginAuthenticationFilter mobileLoginAuthenticationFilter = new MobileLoginAuthenticationFilter(StringUtils.isBlank(url) ? defaultMobileLoginUrl : url,
  28. StringUtils.isBlank(parameter) ? defaultMobileLoginUrl : parameter, StringUtils.isBlank(httpMethod) ? defaultMobileLoginHttpMethod : httpMethod);
  29. mobileLoginAuthenticationFilter.setAuthenticationManager(http.getSharedObject(AuthenticationManager.class));
  30. mobileLoginAuthenticationFilter.setAuthenticationSuccessHandler(customAuthenticationSuccessHandler);
  31. mobileLoginAuthenticationFilter.setAuthenticationFailureHandler(customAuthenticationFailureHandler);
  32. MobileLoginAuthenticationProvider mobileLoginAuthenticationProvider = new MobileLoginAuthenticationProvider();
  33. mobileLoginAuthenticationProvider.setCustomUserDetailsService(customUserDetailsService);
  34. http.authenticationProvider(mobileLoginAuthenticationProvider)
  35. .addFilterAfter(mobileLoginAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
  36. }
  37. }

注:configure()方法

实例化AuthenticationFilter和AuthenticationProvider
将AuthenticationFilter和AuthenticationProvider添加到spring security中。
2.2.2.基于redis自定义验证码校验
2.2.2.1.基于redis自定义验证码过滤器

  1. /** * 验证码过滤器 * * @author : CatalpaFlat */
  2. @Component(SpringBeanNameConstant.DEFAULT_VALIDATE_CODE_FILTER_BN)
  3. public class ValidateCodeFilter extends OncePerRequestFilter implements InitializingBean {
  4. private static final Logger logger = LoggerFactory.getLogger(ValidateCodeFilter.class.getName());
  5. @Autowired
  6. private CustomYmlConfig customYmlConfig;
  7. @Autowired
  8. private RedisTemplate<Object, Object> redisTemplate;
  9. /** * 验证请求url与配置的url是否匹配的工具类 */
  10. private AntPathMatcher pathMatcher = new AntPathMatcher();
  11. public ValidateCodeFilter() {
  12. logger.info("Loading ValidateCodeFilter...");
  13. }
  14. @Override
  15. protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
  16. FilterChain filterChain) throws ServletException, IOException {
  17. String url = customYmlConfig.getLogins().getMobile().getUrl();
  18. if (pathMatcher.match(url, request.getRequestURI())) {
  19. String deviceId = request.getHeader("deviceId");
  20. if (StringUtils.isBlank(deviceId)) {
  21. throw new CustomException(HttpStatus.NOT_ACCEPTABLE.value(), "Not deviceId in the head of the request");
  22. }
  23. String codeParamName = customYmlConfig.getLogins().getMobile().getParameter().getCode();
  24. String code = request.getParameter(codeParamName);
  25. if (StringUtils.isBlank(code)) {
  26. throw new CustomException(HttpStatus.NOT_ACCEPTABLE.value(), "Not code in the parameters of the request");
  27. }
  28. String key = SystemConstant.DEFAULT_MOBILE_KEY_PIX + deviceId;
  29. SmsCodePO smsCodePo = (SmsCodePO) redisTemplate.opsForValue().get(key);
  30. if (smsCodePo.isExpried()){
  31. throw new CustomException(HttpStatus.BAD_REQUEST.value(), "The verification code has expired");
  32. }
  33. String smsCode = smsCodePo.getCode();
  34. if (StringUtils.isBlank(smsCode)) {
  35. throw new CustomException(HttpStatus.BAD_REQUEST.value(), "Verification code does not exist");
  36. }
  37. if (StringUtils.equals(code, smsCode)) {
  38. redisTemplate.delete(key);
  39. //let it go
  40. filterChain.doFilter(request, response);
  41. } else {
  42. throw new CustomException(HttpStatus.BAD_REQUEST.value(), "Validation code is incorrect");
  43. }
  44. }else {
  45. //let it go
  46. filterChain.doFilter(request, response);
  47. }
  48. }
  49. }

注:doFilterInternal()

自定义验证码过滤校验
2.2.2.2.将自定义验证码过滤器添加到spring security过滤器链

  1. http.addFilterBefore(validateCodeFilter, AbstractPreAuthenticatedProcessingFilter.class)

注:添加到认证预处理过滤器前

3.测试效果
发送验证码
在这里插入图片描述
假装发送
在这里插入图片描述
校验并登陆
在这里插入图片描述
校验并认证
在这里插入图片描述
最后附上源码地址:https://gitee.com/CatalpaFlat/springSecurity.git

作者:CatalpaFlat
链接:https://www.jianshu.com/p/7f913e0681fc
来源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

发表评论

表情:
评论列表 (有 0 条评论,178人围观)

还没有评论,来说两句吧...

相关阅读