0

我正在使用 Spring-Security-OAuth2 来实现我自己的 oauth 服务器和资源服务器。我在我的 ResourceServer 上使用RemoteTokenServiceResourceServerTokenService的,它将使用CheckTokenEndpointOAuth 服务器上的 (/oauth/check_token) 对任何 accessToken 进行身份验证。

我已经为 api url 添加了一个 antMatcher,例如 /data/list 这将需要客户端应用程序角色/权限:“ ROLE_ADMIN ”像这样.antMatcher('/data/list').access("#oauth2.clientHasRole('ROLE_ADMIN')")

但它不工作。我在这个端点上做了一些试验和错误,我得到的结果如下:::

当 oauth 授权是仅限客户端时,即 client_credential 授权。我们从 /oauth/check_token 得到什么

{
 "scope":["read"],
 "exp":1412955393,
 "client_id":"sample_test_client_app"
}

我们没有得到任何客户授权。那么spring security如何执行上述授权检查"#oauth2.clientHasRole('ROLE_ADMIN')"

当 oauth 授予是用户 + 客户端时,即 Authorization_code 授予我们从 /oauth/check_token 获得的内容

{
 "aud":["resource_id"],
 "exp":1412957540,
 "user_name":"developer",
 "authorities":["ROLE_USER"],
 "client_id":"sample_test_client_app",
 "scope":["read"]
}

对于authorization_code grnat,我们仍然没有获得客户端权限/角色。那么谁能告诉我我们如何在任何 api url 上执行 clientHasRole 身份验证?

4

1 回答 1

3

为了使“#oauth2.clientHasRole('ROLE_ADMIN')”工作,我们必须实现我们的 AccessTokenConverter 并将其注入身份验证服务器和资源服务器。

所以创建一个扩展和DefaultAccessTokenConverter覆盖方法的新类。convertAccessTokenextractAuthentication

convertAccessToken方法中添加

Map<String, Object> response = (Map<String, Object>) super.convertAccessToken(token, authentication);
OAuth2Request clientToken = authentication.getOAuth2Request();
response.put("clientAuthorities", clientToken.getAuthorities());

并在extractAuthentication方法中添加

Collection<HashMap<String, String>> clientAuthorities = (Collection<HashMap<String, String>>) map.get("client_authority");

Collection<GrantedAuthority> grantedAuthorities = new ArrayList<GrantedAuthority>();

for (HashMap<String, String> grantedAuthority : clientAuthorities) {
   for (String authority : grantedAuthority.values()) {
       grantedAuthorities.add(new SimpleGrantedAuthority(authority));
   }
}

Set<String> resourceIds = new LinkedHashSet<String>(map.containsKey(AUD) ? (Collection<String>) map.get(AUD) : Collections.<String> emptySet());
OAuth2Request request = new OAuth2Request(parameters, clientId, grantedAuthorities, true, scope, resourceIds, null, null, null);
  • 在认证服务器:

    设置这个类AuthorizationServerEndpointsConfigurer

  • 在资源服务器:

    设置这个类RemoteTokenServices

于 2014-10-11T10:09:07.643 回答