使用 Grails 实现 OAuth2 提供者

implementing an OAuth2 provider with Grails

我正在尝试使用我用来测试它的 Spring Security OAuth2 Provider plugin. The provider app and a client app 实现提供 OAuth2 的 Grails 应用程序,它们都在 GitHub.

上可用

我遵循了 instructions in the plugin's docs,它解释了如何实施提供程序。为了测试它,我在 Bootstrap.groovy

中保存了以下 oauth 客户端和用户
def init = { servletContext ->

    def saveArgs = [flush: true, failOnError: true]

    def userRole = new Role(authority: 'ROLE_USER').save(saveArgs)
    def clientRole = new Role(authority: 'ROLE_CLIENT').save(saveArgs)

    // create an OAuth client
    new Client(
            clientId: 'my-client',
            authorizedGrantTypes: ['authorization_code', 'refresh_token', 'implicit', 'password', 'client_credentials'],
            authorities: ['ROLE_CLIENT'],
            scopes: ['read', 'write'],
            redirectUris: ['http://localhost:9090/oauth-client/auth/callback']
    ).save(saveArgs)

    // create a regular user
    def user = new User(username: 'me', password: 'password').save(saveArgs)
    UserRole.create user, userRole, true
}

在客户端应用程序中,我单击以下启动授权码授予流程的link

<g:set var="redirectUrl" value="${g.createLink(controller: 'auth', action: 'callback', absolute: true)}"/>
<h2>
    <a href="http://localhost:8080/oauth2-provider/oauth/authorize?response_type=code&client_id=my-client&scope=read&redirect_uri=${redirectUrl}">OAuth Login</a>
</h2>

我在登录表单中输入上述用户的用户名和密码,然后点击确认对话框中显示的"Authorize"按钮。授权代码已成功返回到客户端应用程序,但当它尝试将其交换为访问令牌时,出现以下错误

invalid_scope: Empty scope (either the client or the user is not allowed the requested scopes)

用于交换访问令牌授权码的代码如下所示。

String getAccessToken(String authCode) {

    def url = 'http://localhost:8080/oauth2-provider/oauth/token'

    def params = [
            grant_type: 'authorization_code',
            code: authCode,
            client_id: 'my-client'
    ]

    new HTTPBuilder(url).request(POST, JSON) {
        uri.query = params

        response.success = { resp, json ->
            json.access_token
        }

        response.failure = { resp, json ->
            log.error "HTTP error code: $resp.status, status line: $resp.statusLine, "

            json.each { key, value ->
                log.error "$key: $value"
            }
        }
    }
}

启动 OAuth 流程的 link 请求访问 read 范围。此 包含在 Client 对象的 scopes 属性 中,因此没有明显的理由禁止访问此范围。

您可以按照以下说明重现错误:

对于将来偶然发现此问题的任何人:

这是插件中一个小错误的结果。临时解决方法是在令牌端点请求中包含范围参数,其值与发送到授权端点的范围参数相同。

有关该问题的更多详细信息,请参阅插件 GitHub 存储库中的 issue #64