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

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

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

我有以下配置:

@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 访问。不需要用户进行身份验证,这意味着用户不需要访问 token 。

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

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

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

最佳答案

然后是这样的:

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

关于spring - 如何仅在 Spring Security OAuth2 中允许从客户端访问资源?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29202224/

相关文章:

spring - PermitAll 在 Spring Security 中不起作用

ajax - 如何从 Controller 调用身份验证-Spring Security Core插件

spring - 如何在 YML 中表示带有值和子属性的 Spring 属性?

java - Spring Security初学者的问题。构建失败

java - Derby 嵌入式驱动程序在哪里?

java - 获取 Spring Boot 应用程序中的日志记录级别

java - Spring security 在登录失败时返回 String 作为主体而不是 UserDetails?

java - NoSuchMethodError :registerAutoProxyCreatorIfNecessary(ParserContext;Object;) exception with Spring config 错误

java - Spring Boot + DynamoDB 本地与 Docker : Connect to localhost:8000 failed

spring - 配置服务器配置无效