Search code examples
google-cloud-platformgoogle-workspaceservice-accountsgoogle-cloud-iam

Multiple scope on GCP service account JWT?


How to set multiple scopes in JWT to get access token for a service account?

This is my code JWT code. It works well for single scope, but doesn't work for multiple scopes. I tried comma separated value, but with no luck.

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: "[email protected]",
//        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
}

Fails with this error.

{
  "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."
}
  • Is it correct to use multiple scopes with comma separated values?
  • Or did I misconfigured something?

I am using Xcode 11, Swift 5.x, and IBM Swift-JWT library.


Solution

  • Scopes are concatenated and separated by a space , and not a comma ,.

    ].joined(separator: " "),