GCP服务帐户JWT有多个范围?

时间:2019-10-15 15:11:27

标签: google-cloud-platform gsuite service-accounts google-cloud-iam

如何在JWT中设置多个范围以获取服务帐户的访问令牌?

这是我的代码JWT代码。它适用于单个作用域,但不适用于多个作用域。我尝试用逗号分隔值,但没有运气。

private func makeSignedJWT() throws -> String {
    let header = Header()
    struct MyClaims: Claims {
        /// The email address of the service account.
        var iss:String
        /// A space-delimited list of the permissions that the application requests.
        var scope: String
        /// A descriptor of the intended target of the assertion. When making an access token request this value is always https://oauth2.googleapis.com/token.
        var aud: String
        /// The expiration time of the assertion, specified as seconds since 00:00:00 UTC, January 1, 1970. This value has a maximum of 1 hour after the issued time.
        var exp: Date
        /// The time the assertion was issued, specified as seconds since 00:00:00 UTC, January 1, 1970.
        var iat: Date
    }
    let now = Date()
    let claims = MyClaims(
        iss: "my.account@my.account.gserviceaccount.com",
//        scope: "https://www.googleapis.com/auth/admin.directory.user.readonly",
        scope: [
            "https://www.googleapis.com/auth/admin.directory.user.alias.readonly",
            "https://www.googleapis.com/auth/admin.directory.user.readonly",
        ].joined(separator: ","),
        aud: "https://oauth2.googleapis.com/token",
        exp: now.addingTimeInterval(60 * 60),
        iat: now)
    var jwt = JWT(header: header, claims: claims)
    let jwtKeyData = "-----BEGIN PRIVATE KEY-----...-----END PRIVATE KEY-----\n".data(using: .utf8)!
    let jwtSigner = JWTSigner.rs256(privateKey: jwtKeyData)
    let signedJWT = try jwt.sign(using: jwtSigner)
    return signedJWT
}

此错误失败。

{
  "error": "invalid_scope",
  "error_description": "https://www.googleapis.com/auth/admin.directory.user.alias.readonly,https://www.googleapis.com/auth/admin.directory.user.readonly is not a valid audience string."
}
  • 使用多个用逗号分隔值的范围是否正确?
  • 还是我配置错误?

我正在使用Xcode 11,Swift 5.x和IBM Swift-JWT库。

1 个答案:

答案 0 :(得分:1)

合并范围由空格而不是逗号,串联和分隔。

].joined(separator: " "),