无法从auth服务器获取Oauth2令牌

时间:2015-08-10 16:03:41

标签: spring authentication spring-security oauth-2.0 resttemplate

我在春天配置了

的auth-server
clients
        .inMemory()
        .withClient("my-web-app")
        .secret("my-web-app-secret")
        .authorizedGrantTypes(//
            "authorization_code",//
            "refresh_token",//
            "password"//
        ).scopes("openid")

现在我想为webapp开发一个命令行应用程序。因此,我需要使用单独的客户端ID和密码注册另一个客户端。 我做过类似的事情

.and()
        .inMemory()
        .withClient("my-cli")
        .secret("my-cli-secret")
        .authorizedGrantTypes("authorization_code","client_credentials")
        .scopes("read","write","trust").authorities("ROLE_USER");

我想要实现的只是提供用户名/密码,客户端应用程序应该能够从auth服务器获取身份验证令牌。

我尝试和理解的是我应该使用资源所有者密码授予。在此之后我必须使用spring Oauth2restTemplate。 这种配置的问题是当我点击令牌时我正在

{
error: "unauthorized"
error_description: "Full authentication is required to access this resource"
}

并且每次与匿名用户打。

1 个答案:

答案 0 :(得分:1)

如果您想使用用户名/密码来获取访问令牌,您肯定需要使用grant_type=password

您也不需要指定.inMemory()两次 - 只有两个客户端.and()

所以配置必须像

@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
    clients
            .inMemory()
                    // First client 
            .withClient("my-web-app")
            .secret("my-web-app-secret")
            .authorizedGrantTypes(//
                    "authorization_code",//
                    "refresh_token",//
                    "password"//
            ).scopes("openid")
            // Second Client(CLI)
            .and()
            .withClient("my-cli")
            .secret("my-cli-secret")
            .authorizedGrantTypes("password")
            .scopes("read", "write", "trust")
            .authorities("ROLE_USER");
}

以及其他非常重要的事情 - 您需要在令牌的http请求中设置Authorization:标头。所以标题应该是

"Authorization: Basic " + Base64.encodeBase64String((clientId + ":" + clientSecret).getBytes())

在用户名\密码之前检查此标头,并定义客户端(在您的情况下为CLI)是授权客户端(这可能会导致您的问题出错)。

如果您可以添加代码,请确切使用Oauth2RestTemplate

,那将是非常好的
相关问题