Spring 使用自定义安全过滤器启动 OAuth2
Spring Boot OAuth2 with custom security filter
我有一个带有 OAuth2 授权和资源服务器的 spring 启动设置。用户可以通过向 /oauth/token
发出 POST 请求来获取令牌。到目前为止,还不错。
但是,我不想通过 BASIC 身份验证保护 /oauth/token
,而是通过自定义安全过滤器。
我尝试了以下方法,但从未调用过 DemoAuthenticationFilter
:
@Configuration
@EnableResourceServer
protected static class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {
// ...
@Override
public void configure(HttpSecurity http) throws Exception {
// ...
http.addFilterBefore(new DemoAuthenticationFilter(), BasicAuthenticationFilter.class);
http.authorizeRequests().antMatchers("/oauth/token").authenticated();
}
}
此外,如果我尝试将其添加到 WebSecurityConfigurerAdapter
,则过滤器仅在 请求通过 OAuth2 进行身份验证后才被调用:
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
// ...
@Override
protected void configure(HttpSecurity http) throws Exception {
// ...
http.addFilterBefore(new DemoAuthenticationFilter(), BasicAuthenticationFilter.class);
http.authorizeRequests().antMatchers("/oauth/token").authenticated();
}
}
如何实现这一点的一些简单示例将非常有帮助。谢谢!
@Configuration
@EnableAuthorizationServer
public class OAuth2AuthorizationServer extends AuthorizationServerConfigurerAdapter {
@Override
public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception {
oauthServer.allowFormAuthenticationForClients().addTokenEndpointAuthenticationFilter(new AligenieFilter());
}
//....
}
对我有用。
我有一个带有 OAuth2 授权和资源服务器的 spring 启动设置。用户可以通过向 /oauth/token
发出 POST 请求来获取令牌。到目前为止,还不错。
但是,我不想通过 BASIC 身份验证保护 /oauth/token
,而是通过自定义安全过滤器。
我尝试了以下方法,但从未调用过 DemoAuthenticationFilter
:
@Configuration
@EnableResourceServer
protected static class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {
// ...
@Override
public void configure(HttpSecurity http) throws Exception {
// ...
http.addFilterBefore(new DemoAuthenticationFilter(), BasicAuthenticationFilter.class);
http.authorizeRequests().antMatchers("/oauth/token").authenticated();
}
}
此外,如果我尝试将其添加到 WebSecurityConfigurerAdapter
,则过滤器仅在 请求通过 OAuth2 进行身份验证后才被调用:
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
// ...
@Override
protected void configure(HttpSecurity http) throws Exception {
// ...
http.addFilterBefore(new DemoAuthenticationFilter(), BasicAuthenticationFilter.class);
http.authorizeRequests().antMatchers("/oauth/token").authenticated();
}
}
如何实现这一点的一些简单示例将非常有帮助。谢谢!
@Configuration
@EnableAuthorizationServer
public class OAuth2AuthorizationServer extends AuthorizationServerConfigurerAdapter {
@Override
public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception {
oauthServer.allowFormAuthenticationForClients().addTokenEndpointAuthenticationFilter(new AligenieFilter());
}
//....
}
对我有用。