我正试图在几个小时内解决这个简单的问题。读过每一篇似乎过时的博客/文章,也搜索过stackoverflow,我无法解决它。
理论上,当您想要使用自定义身份验证提供程序时,您可以创建一个实现AuthenticationProvider
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方法。
我错过了什么?
请确保将@Configuration
放在SecurityConfig
的顶部。
您可能正在将Spring本身启动的默认AuthenticationProvider
注入到您的customAuthProvider
中。确保启动CustomAuthProvider
并将其注入customAuthProvider
:
public SecurityConfig(AuthenticationProvider customAuthProvider) {
super(true);
this.customAuthProvider = new CustomAuthProvider();
}
对于任何可能有同样问题的人。在不完全确定的情况下,我认为没有使用该提供程序,因为我没有使用用户名/密码身份验证/http标头我想访问一个令牌并使用该令牌,这意味着在调用authorizeRequests()
和authenticated()
之前必须使用过滤器