1

这里有一个问题:我想保护一个 URI,直到获得一些第三方 OAuth2 的授权。基于http://docs.spring.io/spring-security/oauth/apidocs/org/springframework/security/oauth2/config/annotation/web/configuration/EnableOAuth2Client.html,我有这些:

@Configuration
@EnableOAuth2Client
public class OAuth2Client extends OAuth2ClientConfiguration {

    @Bean
    public Filter filter() {
        DelegatingFilterProxy f = new DelegatingFilterProxy();
        f.setTargetBeanName("oauth2ClientContextFilter");
        return f;
    }

    @Resource
    @Qualifier("oauth2ClientContextFilter")
    private OAuth2ClientContextFilter oauth2ClientContextFilter;

    @Resource
    @Qualifier("accessTokenRequest")
    private AccessTokenRequest accessTokenRequest;

    @Bean
    public OAuth2ProtectedResourceDetails remote() {
        AuthorizationCodeResourceDetails details = new AuthorizationCodeResourceDetails();
        details.setUserAuthorizationUri("http://localhost2/oauth/authorize");
        return details;
    }

    @Bean
    public OAuth2RestOperations restTemplate() {
        return new OAuth2RestTemplate(remote(), new DefaultOAuth2ClientContext(
                accessTokenRequest));
    }

}

@Configuration
@EnableResourceServer
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {
    // Empty for now...
}

最后

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(AuthenticationManagerBuilder auth)
            throws Exception {
        super.configure(auth);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.requestMatchers().antMatchers("/protectedUri").and()
                .authorizeRequests().requestMatchers()
                .hasRole("#oauth2.hasScope('read')");

    }
}

但这给出了:

java.lang.IllegalStateException: 至少需要一个映射(即authorizeRequests().anyRequest.authenticated())

我已经尝试了很多 HttpSecurity 构建器的组合,但都无济于事 - 有什么帮助,还是这种方法完全不符合标准?

4

1 回答 1

1

这种方法完全没有根据吗?

是的。一个空ResourceServerConfigurerAdapter的不会帮助你。您应该配置受保护的路径,例如

@Override
public void configure(HttpSecurity http) throws Exception {
    http.authorizeRequests().antMatchers("/protectedUri").authenticated();
}

(并省略你的WebSecurityConfigurerAdapter)。

顶部的客户端配置看起来也有问题,但它与受保护的资源无关(如果您想知道如何配置客户端,请提出一个新问题)。

于 2014-09-24T09:22:39.210 回答