spring boot整合spring security(自定义验证方式)

spring security支持传统的查询数据库方式,也即根据用户名查询出用户信息,然后再比较前端传来的密码和数据库中的密码。

这种方式很常用。但不适合通过第三方进行的授权认证模式。这时候,我们需要自己处理登录验证过程。

针对这些情况,我们需要自定义Authentication Provider

@Component
public class CustomAuthenticationProvider implements AuthenticationProvider {

    @Autowired
    private UserDetailsService userDetailsService;
 
    @Override
    public Authentication authenticate(Authentication authentication) 
      throws AuthenticationException {
  
        String name = authentication.getName();
        String password = authentication.getCredentials().toString();
         //以下自定义方法,判断是否登录成功
        if (isAuthenticated()) {
  
            // 下面的权限,可以通过UserDetailsService获取得到
            return new UsernamePasswordAuthenticationToken(
              name, password, new ArrayList<>());
        } else {
            return null;
        }
    }
 
    @Override
    public boolean supports(Class<?> authentication) {
        return authentication.equals(
          UsernamePasswordAuthenticationToken.class);
    }
}

之后,再写一个配置类,继承WebSecurityConfigurerAdapter类,在该类中注入 上面的provider。并重写其configure方法,如下所示。

@Autowired
    private CustomAuthenticationProvider authProvider;
 
    @Override
    protected void configure(
      AuthenticationManagerBuilder auth) throws Exception {
  
        auth.authenticationProvider(authProvider);
    }
经验分享 程序员 微信小程序 职场和发展