Spring Boot Resource Server无法使用oAuth 2访问令牌授权角色

时间:2016-04-23 10:42:29

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

我有以下3个微服务

  • 配置服务器
  • 使用MongoDB引用link的Auth服务器。我成功地将项目从1.2.4迁移到1.3.3
  • 用户服务。具有3个Get方法的Rest控制器和资源服务器(每个用于ADMIN,MERCHANT和CONSUMER)

我希望根据用户的角色限制访问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"
}

我无法弄清楚为什么基于角色的授权不起作用。非常感谢任何帮助。

2 个答案:

答案 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/