gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 21:13:46 24 4
gpt4 key购买 nike

我使用 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com