Spring Boot OAuth2带有自定义安全过滤器

时间:2016-10-31 15:56:58

标签: java spring-security spring-boot oauth-2.0 spring-security-oauth2

我有一个带有OAuth2授权和资源服务器的spring boot设置。用户可以通过向/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();
    }
}

如何实现这一目标的一些简单示例将非常有用。谢谢!

1 个答案:

答案 0 :(得分:0)

@Configuration
@EnableAuthorizationServer
public class OAuth2AuthorizationServer extends AuthorizationServerConfigurerAdapter {

    @Override
    public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception {
        oauthServer.allowFormAuthenticationForClients().addTokenEndpointAuthenticationFilter(new AligenieFilter());
    }

    //....
}

对我有用。