Spring Boot /安全自定义身份验证

时间:2020-08-15 13:42:48

标签: spring-boot spring-security

我正在尝试解决几个 简单 问题。 阅读了似乎过时的每个博客/文章,也通过stackoverflow搜索,我无法解决它。

理论上,当您要使用自定义身份验证提供程序时,可以创建一个实现 AuthenticiationProvider

public class CustomAuthProvider implements AuthProvider {}

并实施验证支持方法。

@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    return MyCustomAuthentication();
}

@Override
public boolean supports(Class<?> authentication) {
    return (MyCustomAuthentication.class
            .isAssignableFrom(authentication));
}

然后创建一个SecurityConfig类,该类扩展了设置您的身份验证提供程序的 WebSecurityConfigurerAdapter

public class SecurityConfig extends WebSecurityConfigurerAdapter {

    public SecurityConfig(AuthenticationProvider customAuthProvider) {
      super(true);
      this.customAuthProvider = customAuthProvider;
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
      auth.authenticationProvider(customAuthProvider);
    }
}

从理论上讲,应该是可以的,但应该不能。 使用调试器,我可以看到该提供程序已在ProviderManager中注册,并且它是唯一的,但从未使用 authenticate 方法。

我想念什么?

2 个答案:

答案 0 :(得分:0)

请确保将@Configuration放在您的SecurityConfig上方。

您可能正在将由Spring本身启动的默认AuthenticationProvider注入您的customAuthProvider中。确保启动CustomAuthProvider并将其注入customAuthProvider

public SecurityConfig(AuthenticationProvider customAuthProvider) {
    super(true);
    this.customAuthProvider = new CustomAuthProvider();
}

答案 1 :(得分:0)

对于任何对此有相同问题的人。 不确定,我相信没有使用提供程序,因为我没有使用用户名/密码验证/ http标头。 我想访问令牌并使用该令牌,这意味着您必须在调用authorizeRequests()authenticated()

之前使用过滤器