SpringBoot Security 自定义 DaoAuthenticationProvider,重写additionalAuthenticationChecks方法

开发遇到一件很尴尬的事情,springboot里面使用security做登录验证,但是默认的就是验证username和password,现在的第三方或者短信登录非常流行。我现在的需求是做账号+短信登录(ps:后面还不知道要加啥… so:旧的不能废,只能扩展),接rongcloud sdk

post:/login
params:{
username:mobile,
sessionid:rongcloud_sessionid,
code:验证码
}

我的想法如标题,于是开始找各种娘、哥。。。。。
这个时候度娘都不起作用了o(╥﹏╥)o,谷哥了半天也没详细的解决方案
大多都是使用的xml方式配置
我想用的是springboot 注解(ー`´ー)
最终不知道把谁和谁的想法揉在了一起(尴尬)

@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
...
    //-------------------------------①----------------------------------
    @Autowired
    private UserDetailsService userDetailsService;
  //-------------------------------①----------------------------------

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
      UserDetailsService userDetailsService= //自定义或者使用①
      auth.authenticationProvider(new LoginAuthenticationProvider(userDetailsService));
          //这东西千万不能忘
      auth.userDetailsService(userDetailsService)
          .passwordEncoder(new Md5PasswordEncoder());
  }
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        ...
        // 加入自定义UsernamePasswordAuthenticationFilter替代原有Filter
        http.addFilterAt(
                new ApiUsernamePasswordAuthenticationFilter(super.authenticationManager()),
                UsernamePasswordAuthenticationFilter.class);
        ...
    }
...
}

自定义LoginAuthenticationProvider继承DaoAuthenticationProvider重写additionalAuthenticationChecks()这里就是做密码比较的

public class LoginAuthenticationProvider extends DaoAuthenticationProvider {
    public LoginAuthenticationProvider(UserDetailsService userDetailsService) {
        super();
        // 这个地方一定要对userDetailsService赋值,不然userDetailsService是null (这个坑有点深)
        setUserDetailsService(userDetailsService);
    }
    @SuppressWarnings("deprecation")
    protected void additionalAuthenticationChecks(UserDetails userDetails,
            UsernamePasswordAuthenticationToken authentication) throws AuthenticationException {
        Object salt = null;

        if (this.getSaltSource() != null) {
            salt = this.getSaltSource().getSalt(userDetails);
        }

        if (authentication.getCredentials() == null) {
            logger.debug("Authentication failed: no credentials provided");

            throw new BadCredentialsException(
                    messages.getMessage("AbstractUserDetailsAuthenticationProvider.badCredentials", "Bad credentials"));
        }

        String presentedPassword = authentication.getCredentials().toString();
        //我就改了这个地方,增加一个验证码登录标识(具体怎么做就看自己了)
        // 【原本的是登录密码和数据密码不等就抛出异常,我用验证码登录时压根都不知道密码(ー`´ー)】
        //so 我给短信登录时赋值一个默认密码(验证码登录标识)来判断,不让这儿报异常
        if (!presentedPassword.equals("YZMLG_KSssdS1D145Sd4S")) {
            if (!getPasswordEncoder().isPasswordValid(userDetails.getPassword(), presentedPassword, salt)) {
                logger.debug("Authentication failed: password does not match stored value");

                throw new BadCredentialsException(messages
                        .getMessage("AbstractUserDetailsAuthenticationProvider.badCredentials", "Bad credentials"));
            }
        }
    }

至于这个 #验证码登录标识# 怎么来的就在下面
自定义的Filter

public class ApiUsernamePasswordAuthenticationFilter extends AbstractAuthenticationProcessingFilter {
    public ApiUsernamePasswordAuthenticationFilter(AuthenticationManager authenticationManager) {
        super(new AntPathRequestMatcher("/login", "POST"));
      ...
    }
    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
            throws AuthenticationException, IOException, ServletException {
        ....
      //验证码登录
        if(passcode!=null){
            if(sessionid!=null){
                try {
                   //接rongcloud sdk 验证
                    SMSVerifyCodeResult result = smsWapper.verifyCode(sessionid, passcode);
                    if (result.getCode() == 200 && result.getSuccess()) {//验证成功
                        password = "YZMLG_KSssdS1D145Sd4S";//验证码登录标识
                    }else{
                        throw new SessionAuthenticationException("验证码错误");
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    throw new SessionAuthenticationException("验证码错误");
                }
            }
        }
        username = username.trim();

        UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(username, password);
        ....
        return this.getAuthenticationManager().authenticate(authRequest);
        
    }
}

大概的就是这样
恩,做个笔记(坑+1)

作者:yexue
链接:https://www.jianshu.com/p/955e30866121
来源:简书

你可能感兴趣的:(SpringBoot)