如何仅在Spring Security OAuth2中允许从客户端访问资源?

时间:2015-03-23 02:01:01

标签: spring spring-security spring-boot spring-security-oauth2

我使用带有Spring Security OAuth2的Spring-Boot开发了一个简单的Web应用程序,我想只允许从Client应用程序访问所有资源。有些资源需要对客户端进行身份验证,而有些资源则不需要。

我有以下配置:

@Configuration
@EnableResourceServer
protected static class ResourceServerConfig extends ResourceServerConfigurerAdapter {

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.requestMatchers()
            .and()
            .authorizeRequests()
            .antMatchers("/account/**").permitAll()
            .antMatchers("/user/**").access("#oauth2.hasScope('read')")
            .antMatchers("/transaction/**").access("#oauth2.hasScope('read')");
    }

}
@Configuration
@EnableAuthorizationServer
protected static class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) {
        endpoints.authenticationManager(authenticationManager);
    }

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.inMemory()
            .withClient("my-trusted-client")
            .authorizedGrantTypes("authorization_code", "password", "refresh_token")
            .authorities("ROLE_CLIENT", "ROLE_TRUSTED_CLIENT")
            .scopes("read", "write", "trust")
            .accessTokenValiditySeconds(3600);
    }

    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
        security.allowFormAuthenticationForClients();
    }

}

我尝试做的是资源" / account / **",它不应该要求客户端进行身份验证,但仍然只允许通过客户端进行访问。

对于其他资源,它只允许通过客户端进行访问,并且必须进行身份验证。

不幸的是,在上面的当前设置中,我仍然可以访问" / account / **"来自客户以外。

感谢任何帮助。

更新1

其他信息我忘记包含,我使用grant_type密码。

所以我想要的就是这个。例如:

/ account - 只能通过client_id / client_secret访问。不要求用户进行身份验证,这意味着用户不需要具有访问令牌。

/ user - 只能通过client_id / client_secret访问。并要求用户进行身份验证,这意味着用户必须具有访问令牌。

客户我指的是具有client_id和client_secret的移动应用程序。

如果我还不清楚,请告诉我。

1 个答案:

答案 0 :(得分:2)

那样的话:

.authorizeRequests()
   .antMatchers("/account/**").access("#oauth2.isClient()")
   .antMatchers("/user/**").access("#oauth2.isUser() && #oauth2.hasScope('read')")