我有一个简单的 AuthenticationEntryPoint
,它应该为未经授权的请求设置 WWW-Authenticate header 。
@Component
public class CustomAuthenticationEntryPoint implements AuthenticationEntryPoint {
@Override
public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException)
throws IOException, ServletException {
response.setHeader("WWW-Authenticate", "FormBased");
response.sendError(401, authException.getMessage());
}
}
我在
AuthorizationServerConfigurer
的配置方法之一中使用它@Override
public void configure(AuthorizationServerSecurityConfigurer authorizationServerSecurityConfigurer) throws Exception {
authorizationServerSecurityConfigurer.authenticationEntryPoint(authenticationEntryPoint);
}
但是,并不总是调用此开始方法。当请求中没有 Authorize header 或 Authorize header 值不以“Basic”开头时,它会被调用。但是,如果 Authorize header 以“Basic”开头,则不会调用开始方法(并且响应的值为
Basic realm="oauth2/client"
)。如何确保调用此方法? 最佳答案
正如 AliDehghani 所指出的,这是因为 BasicAuthenticationFilter
使用 BasicApplicationEntryPoint
而不管 ApplicationEntryPoint
中声明的 AuthorizationServerSecurityConfigurer
。为了让 BasicAuthenticationFilter
使用我的 CustomApplicationEntryPoint
,我需要创建一个新的 CustomBasicAuthenticationFilter
并将 @Autowire
注释添加到构造函数中:
@Component
public class CustomBasicAuthenticationFilter extends BasicAuthenticationFilter {
@Autowired
public CustomBasicAuthenticationFilter(AuthenticationManager authenticationManager,
AuthenticationEntryPoint authenticationEntryPoint) {
super(authenticationManager, authenticationEntryPoint);
}
}
然后将其添加到
AuthorizationServerConfigurer
的配置方法之一@Override
public void configure(AuthorizationServerSecurityConfigurer authorizationServerSecurityConfigurer) throws Exception {
authorizationServerSecurityConfigurer
.authenticationEntryPoint(authenticationEntryPoint)
.addTokenEndpointAuthenticationFilter(customBasicAuthenticationFilter);
}
现在应用程序使用我的
CustomBasicAuthenticationFilter
- 它在功能上等同于 BasicAuthenticationFilter
。但是,它现在在构造过程中包含声明的 AuthenticationEntryPoint
bean - 这是我的 CustomAuthenticationEntryPoint
。