我有以下3个微服务
我希望根据用户的角色限制访问REST控制器的GET方法。 资源配置如下
@Configuration
@EnableResourceServer
public class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {
@Override
public void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers(HttpMethod.GET, "/**").hasAuthority("ROLE_ADMIN")
.anyRequest()
.authenticated();
}
@Override
public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
resources.resourceId("admin-api");
}
}
要测试我只是尝试锁定除角色ADMIN之外的所有用户的用户服务。但是,我获得了401 Access Denied。我也试过hasRole(“ADMIN”)同样的结果。如果我删除该授权标准,则用户被正确认证(不接受错误的访问令牌)。 auth服务器的userInfoUri响应如下
{
"details": {
"remoteAddress": "0:0:0:0:0:0:0:1",
"sessionId": null,
"tokenValue": "a4244b33-80b2-48db-909d-f8aaaaf45985",
"tokenType": "Bearer",
"decodedDetails": null
},
"authorities": [
{
"authority": "ROLE_ADMIN"
}
],
"authenticated": true,
"userAuthentication": {
"details": null,
"authorities": [
{
"authority": "ROLE_ADMIN"
}
],
"authenticated": true,
"principal": "admin@ikarma.com",
"credentials": null,
"client": false,
"name": "admin@ikarma.com"
},
"credentials": "",
"clientOnly": false,
"oauth2Request": {
"clientId": "admin-web",
"scope": [
"trust",
"read",
"write"
],
"requestParameters": {
"grant_type": "password",
"username": "admin@ikarma.com"
},
"resourceIds": null,
"authorities": [],
"approved": true,
"refresh": false,
"redirectUri": null,
"responseTypes": [],
"extensions": {},
"refreshTokenRequest": null,
"grantType": "password"
},
"principal": "admin@ikarma.com",
"name": "admin@ikarma.com"
}
我无法弄清楚为什么基于角色的授权不起作用。非常感谢任何帮助。
答案 0 :(得分:0)
将spring-security-oauth2依赖项更改为此
<dependency>
<groupId>org.springframework.security.oauth</groupId>
<artifactId>spring-security-oauth2</artifactId>
<version>2.0.7.RELEASE</version>
</dependency>
答案 1 :(得分:0)
确保在双方资源服务器和auth服务器上JWT编码/解码的实现是相同的。另外,请尝试在oauth服务器上创建inMemory 3个具有3个角色的用户:
Organisation Name
尝试为这些用户接收access_token,然后向资源服务器发出请求,包括请求头部授权:bearer [access_token] 如果你得到同样的错误意味着你的JWT实现不正确...... 请在这里查看JWT https://bshaffer.github.io/oauth2-server-php-docs/overview/jwt-access-tokens/