spring security 自定义认证登录

spring security 自定义认证登录

1.概要

1.1.简介

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

1.2.spring security 自定义认证流程

1)认证过程

生成未认证的AuthenticationToken                 
       ↑(获取信息)           (根据AuthenticationToken分配provider)                                    
 AuthenticationFilter   ->     AuthenticationManager    ->    AuthenticationProvider
                                                                      ↓(认证)
                                                              UserDetails(一般查询数据库获取)
                                                                      ↓(通过)
                                                             生成认证成功的AuthenticationToken
                                                                      ↓(存放)
                                                                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

/**
 * 手机登录Token
 *
 * @author : CatalpaFlat
 */
public class MobileLoginAuthenticationToken extends AbstractAuthenticationToken {
    private static final long serialVersionUID = SpringSecurityCoreVersion.SERIAL_VERSION_UID;
    private static final Logger logger = LoggerFactory.getLogger(MobileLoginAuthenticationToken.class.getName());

    private final Object principal;

    public MobileLoginAuthenticationToken(String mobile) {
        super(null);
        this.principal = mobile;
        this.setAuthenticated(false);
        logger.info("MobileLoginAuthenticationToken setAuthenticated ->false loading ...");
    }

    public MobileLoginAuthenticationToken(Object principal,
                                          Collection<? extends GrantedAuthority> authorities) {
        super(authorities);
        this.principal = principal;
        // must use super, as we override
        super.setAuthenticated(true);
        logger.info("MobileLoginAuthenticationToken setAuthenticated ->true loading ...");
    }

    @Override
    public void setAuthenticated(boolean authenticated) {
        if (authenticated) {
            throw new IllegalArgumentException(
                    "Cannot set this token to trusted - use constructor which takes a GrantedAuthority list instead");
        }
        super.setAuthenticated(false);
    }

    @Override
    public Object getCredentials() {
        return null;
    }

    @Override
    public Object getPrincipal() {
        return this.principal;
    }

    @Override
    public void eraseCredentials() {
        super.eraseCredentials();
    }
}

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

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

2.2.1.1.自定义认证登录过滤器

/**
 * 手机短信登录过滤器
 *
 * @author : CatalpaFlat
 */
public class MobileLoginAuthenticationFilter extends AbstractAuthenticationProcessingFilter {

    private boolean postOnly = true;
    private static final Logger logger = LoggerFactory.getLogger(MobileLoginAuthenticationFilter.class.getName());

    @Getter
    @Setter
    private String mobileParameterName;

    public MobileLoginAuthenticationFilter(String mobileLoginUrl, String mobileParameterName,
                                           String httpMethod) {
        super(new AntPathRequestMatcher(mobileLoginUrl, httpMethod));
        this.mobileParameterName = mobileParameterName;
        logger.info("MobileLoginAuthenticationFilter loading ...");
    }

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request,
                                                HttpServletResponse response) throws AuthenticationException, IOException, ServletException {

        if (postOnly && !request.getMethod().equals(HttpMethod.POST.name())) {
            throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod());
        }

        //get mobile
        String mobile = obtainMobile(request);

        //assemble token
        MobileLoginAuthenticationToken authRequest = new MobileLoginAuthenticationToken(mobile);

        // Allow subclasses to set the "details" property
        setDetails(request, authRequest);

        return this.getAuthenticationManager().authenticate(authRequest);
    }
    /**
     * 设置身份认证的详情信息
     */
    private void setDetails(HttpServletRequest request, MobileLoginAuthenticationToken authRequest) {
        authRequest.setDetails(authenticationDetailsSource.buildDetails(request));
    }
    /**
     * 获取手机号
     */
    private String obtainMobile(HttpServletRequest request) {
        return request.getParameter(mobileParameterName);
    }

    public void setPostOnly(boolean postOnly) {
        this.postOnly = postOnly;
    }
}

注:attemptAuthentication()方法:

  • 过滤指定的url、httpMethod
  • 获取所需请求参数数据封装生成一个未认证的AuthenticationToken
  • 传递给AuthenticationManager认证

2.2.1.1.自定义认证登录提供者

/**
 * 手机短信登录认证提供者
 *
 * @author : CatalpaFlat
 */
public class MobileLoginAuthenticationProvider implements AuthenticationProvider {

    private static final Logger logger = LoggerFactory.getLogger(MobileLoginAuthenticationProvider.class.getName());

    @Getter
    @Setter
    private UserDetailsService customUserDetailsService;

    public MobileLoginAuthenticationProvider() {
        logger.info("MobileLoginAuthenticationProvider loading ...");
    }

    /**
     * 认证
     */
    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        //获取过滤器封装的token信息
        MobileLoginAuthenticationToken authenticationToken = (MobileLoginAuthenticationToken) authentication;
        //获取用户信息(数据库认证)
        UserDetails userDetails = customUserDetailsService.loadUserByUsername((String) authenticationToken.getPrincipal());
        //不通过
        if (userDetails == null) {
            throw new InternalAuthenticationServiceException("Unable to obtain user information");
        }
        //通过
        MobileLoginAuthenticationToken authenticationResult = new MobileLoginAuthenticationToken(userDetails, userDetails.getAuthorities());

        authenticationResult.setDetails(authenticationToken.getDetails());

        return authenticationResult;
    }

    /**
     * 根据token类型,来判断使用哪个Provider
     */
    @Override
    public boolean supports(Class<?> authentication) {
        return MobileLoginAuthenticationToken.class.isAssignableFrom(authentication);
    }
}

注:authenticate()方法

  • 获取过滤器封装的token信息
  • 调取UserDetailsService获取用户信息(数据库认证)->判断通过与否
  • 通过则封装一个新的AuthenticationToken,并返回

2.2.1.1.自定义认证登录认证配置

@Configuration(SpringBeanNameConstant.DEFAULT_CUSTOM_MOBILE_LOGIN_AUTHENTICATION_SECURITY_CONFIG_BN)
public class MobileLoginAuthenticationSecurityConfig extends SecurityConfigurerAdapter<DefaultSecurityFilterChain, HttpSecurity> {
    private static final Logger logger = LoggerFactory.getLogger(MobileLoginAuthenticationSecurityConfig.class.getName());
    @Value("${login.mobile.url}")
    private String defaultMobileLoginUrl;
    @Value("${login.mobile.parameter}")
    private String defaultMobileLoginParameter;
    @Value("${login.mobile.httpMethod}")
    private String defaultMobileLoginHttpMethod;

    @Autowired
    private CustomYmlConfig customYmlConfig;
    @Autowired
    private UserDetailsService customUserDetailsService;
    @Autowired
    private AuthenticationSuccessHandler customAuthenticationSuccessHandler;
    @Autowired
    private AuthenticationFailureHandler customAuthenticationFailureHandler;


    public MobileLoginAuthenticationSecurityConfig() {
        logger.info("MobileLoginAuthenticationSecurityConfig loading ...");
    }

    @Override
    public void configure(HttpSecurity http) throws Exception {
        MobilePOJO mobile = customYmlConfig.getLogins().getMobile();
        String url = mobile.getUrl();
        String parameter = mobile.getParameter().getMobile();
        String httpMethod = mobile.getHttpMethod();

        MobileLoginAuthenticationFilter mobileLoginAuthenticationFilter = new MobileLoginAuthenticationFilter(StringUtils.isBlank(url) ? defaultMobileLoginUrl : url,
                StringUtils.isBlank(parameter) ? defaultMobileLoginUrl : parameter, StringUtils.isBlank(httpMethod) ? defaultMobileLoginHttpMethod : httpMethod);

        mobileLoginAuthenticationFilter.setAuthenticationManager(http.getSharedObject(AuthenticationManager.class));
        mobileLoginAuthenticationFilter.setAuthenticationSuccessHandler(customAuthenticationSuccessHandler);
        mobileLoginAuthenticationFilter.setAuthenticationFailureHandler(customAuthenticationFailureHandler);

        MobileLoginAuthenticationProvider mobileLoginAuthenticationProvider = new MobileLoginAuthenticationProvider();
        mobileLoginAuthenticationProvider.setCustomUserDetailsService(customUserDetailsService);

        http.authenticationProvider(mobileLoginAuthenticationProvider)
                .addFilterAfter(mobileLoginAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
    }
}

注:configure()方法

  • 实例化AuthenticationFilter和AuthenticationProvider
  • 将AuthenticationFilter和AuthenticationProvider添加到spring security中。

2.2.2.基于redis自定义验证码校验

2.2.2.1.基于redis自定义验证码过滤器

/**
 * 验证码过滤器
 *
 * @author : CatalpaFlat
 */
@Component(SpringBeanNameConstant.DEFAULT_VALIDATE_CODE_FILTER_BN)
public class ValidateCodeFilter extends OncePerRequestFilter implements InitializingBean {

    private static final Logger logger = LoggerFactory.getLogger(ValidateCodeFilter.class.getName());

    @Autowired
    private CustomYmlConfig customYmlConfig;

    @Autowired
    private RedisTemplate<Object, Object> redisTemplate;

    /**
     * 验证请求url与配置的url是否匹配的工具类
     */
    private AntPathMatcher pathMatcher = new AntPathMatcher();

    public ValidateCodeFilter() {
        logger.info("Loading ValidateCodeFilter...");
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
                                    FilterChain filterChain) throws ServletException, IOException {
        String url = customYmlConfig.getLogins().getMobile().getUrl();
        if (pathMatcher.match(url, request.getRequestURI())) {
            String deviceId = request.getHeader("deviceId");
            if (StringUtils.isBlank(deviceId)) {
                throw new CustomException(HttpStatus.NOT_ACCEPTABLE.value(), "Not deviceId in the head of the request");
            }
            String codeParamName = customYmlConfig.getLogins().getMobile().getParameter().getCode();
            String code = request.getParameter(codeParamName);
            if (StringUtils.isBlank(code)) {
                throw new CustomException(HttpStatus.NOT_ACCEPTABLE.value(), "Not code in the parameters of the request");
            }
            String key = SystemConstant.DEFAULT_MOBILE_KEY_PIX + deviceId;
            SmsCodePO smsCodePo = (SmsCodePO) redisTemplate.opsForValue().get(key);
            if (smsCodePo.isExpried()){
                throw new CustomException(HttpStatus.BAD_REQUEST.value(), "The verification code has expired");
            }
            String smsCode = smsCodePo.getCode();
            if (StringUtils.isBlank(smsCode)) {
                throw new CustomException(HttpStatus.BAD_REQUEST.value(), "Verification code does not exist");
            }
            if (StringUtils.equals(code, smsCode)) {
                redisTemplate.delete(key);
                //let it go
                filterChain.doFilter(request, response);
            } else {
                throw new CustomException(HttpStatus.BAD_REQUEST.value(), "Validation code is incorrect");
            }
        }else {
            //let it go
            filterChain.doFilter(request, response);
        }
    }
}

注:doFilterInternal()

  • 自定义验证码过滤校验

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

http.addFilterBefore(validateCodeFilter, AbstractPreAuthenticatedProcessingFilter.class)

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

3.测试效果

发送验证码

假装发送

校验并登陆

校验并认证

最后附上源码地址:https://gitee.com/CatalpaFlat/springSecurity.git

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 159,716评论 4 364
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,558评论 1 294
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 109,431评论 0 244
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,127评论 0 209
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,511评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,692评论 1 222
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,915评论 2 313
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,664评论 0 202
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,412评论 1 246
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,616评论 2 245
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,105评论 1 260
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,424评论 2 254
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,098评论 3 238
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,096评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,869评论 0 197
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,748评论 2 276
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,641评论 2 271

推荐阅读更多精彩内容