【发布时间】:2018-02-06 21:53:27
【问题描述】:
我正在开发一个使用 API 密钥进行身份验证的 Spring Boot。我创建了一个自定义身份验证提供程序,并且身份验证方法被调用了两次。谁能告诉我为什么它被调用了两次?
这是我的身份验证方法:
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
ApiAuthenticationToken authenticationToken = (ApiAuthenticationToken) authentication;
/**
* Authenticate the token
*/
ValidateApiKeyRequest request = new ValidateApiKeyRequest(authenticationToken.getApiKey());
ValidateApiKeyResp resp = getValidateApiKeyCommand().execute(request);
/**
* Populate and return a new authenticaiton token
*/
return createSuccessAuthentication(resp);
}
这是 createSuccessAuthentication 方法:
protected Authentication createSuccessAuthentication(final ValidateApiKeyResp resp) {
List<GrantedAuthority> authorities = Lists.newArrayList();
authorities.add(new SimpleGrantedAuthority("API_KEY"));
return new ApiAuthenticationToken(resp.getApiKey(), authorities, true);
}
这是 ApiAuthenticationToken 构造函数:
public ApiAuthenticationToken(final ApiKey apiKey, Collection<? extends GrantedAuthority> authorities, boolean authenticated) {
super(authorities);
setAuthenticated(true);
this.apiKey = apiKey;
}
这是我的安全配置:
protected void configure(HttpSecurity http) throws Exception {
http.antMatcher(CONFIGURATION_MATCHER)
.exceptionHandling().authenticationEntryPoint(restAuthenticationEntryPoint())
.and()
.addFilterBefore(apiKeyAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class)
.csrf().disable()
.authorizeRequests().antMatchers(CONFIGURATION_MATCHER).authenticated()
.and()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.authenticationProvider(apiKeyAuthenticationProvider());
【问题讨论】:
-
你是否碰巧在某处定义了 configure(AuthenticationManagerBuilder)?
-
不,我没有。我在类似的帖子上看到过这个答案,所以我知道这个问题。
-
还有其他建议吗?
-
您有重现该问题的小型示例项目吗?
标签: spring authentication spring-security