如何使用 JWT 为 Google firebase 生成身份验证令牌?

2024-02-25

所以我正在努力对 Firebase REST API 进行身份验证。 https://firebase.google.com/docs/database/rest/auth我正在使用蒸气框架 https://vapor.codes对于服务器端 swift,我安装了智威汤逊包 https://github.com/vapor/jwt.

我正在尝试使用中的数据serviceAccountKey.json文件和 JWT 来生成身份验证令牌。

这是我尝试过的代码:

let payload = try JSON(node: [
        "iat": Date().timeIntervalSince1970,
        "exp": Date().timeIntervalSince1970 + 3600,
        "iss": "client_email from serviceAccountKey.json",
        "aud": "https://accounts.google.com/o/oauth2/token",
        "scope": [
            "https://www.googleapis.com/auth/firebase.database",
            "https://www.googleapis.com/auth/userinfo.email"
        ]
    ])
    let privateKey = "copied from serviceAccountKey.json"

    let signer = try HS256(bytes: privateKey.bytes)

    let jwt = try JWT(payload: payload, signer: signer)
    let token = try jwt.createToken()
    print(token)

serviceAccountKey.json

{
  "type": "service_account",
  "project_id": "",
  "private_key_id": "",
  "private_key": "",
  "client_email": "",
  "client_id": "",
  "auth_uri": "https://accounts.google.com/o/oauth2/auth",
  "token_uri": "https://accounts.google.com/o/oauth2/token",
  "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
  "client_x509_cert_url": ""
}

此时我使用的是Xcode 8.3.3。 Package.swift 包含:

let package = Package(
name: "StripePayment",
dependencies: [
    .Package(url: "https://github.com/vapor/vapor.git", majorVersion: 1, minor: 5),
    .Package(url:"https://github.com/vapor/jwt.git", majorVersion: 0,minor: 8),
     .Package(url: "https://github.com/SwiftyJSON/SwiftyJSON.git", versions: Version(1, 0, 0)..<Version(3, .max, .max))

],
exclude: [
    "Config",
    "Database",
    "Localization",
    "Public",
    "Resources",
    "Tests",
]
)

如果您生成服务帐户凭据,您需要记住以下内容,取自https://cloud.google.com/storage/docs/authentication:您可以在云平台控制台中通过为服务帐号创建OAuth Client ID来创建私钥。您可以获取 JSON 和 PKCS12 格式的私钥:

如果您使用的是 JSON 密钥,则需要应用程序默认凭据 https://cloud.google.com/storage/docs/authentication#libauth在 Google Cloud Platform 之外的生产环境中。JSON 密钥无法转换为其他格式。许多不同的编程语言和库都支持 PKCS12 (.p12)。如果需要,您可以使用 OpenSSL 将密钥转换为其他格式(请参阅将私钥转换为其他格式 https://cloud.google.com/storage/docs/authentication)。但是,PKCS12 密钥无法转换为 JSON 格式。

Note: You do NOT需要在 console.cloud.google.com 生成一个服务帐户。只需按照下面列出的步骤 1...6 进行操作即可。

  1. Go to https://console.firebase.google.com https://console.firebase.google.com,单击您的项目,在“概述”旁边单击滚轮“设置”,单击“服务帐户”,滚动到页面底部,然后单击“生成新私钥”。

  2. 使用 OpenSSL 将 p.12(又名 pkcs12)文件转换为 .pem(又名 pkcs1)

    cat /path/to/xxxx-privatekey.p12 | openssl pkcs12 -nodes -nocerts -passin pass:notasecret | openssl rsa > /path/to/secret.pem

  3. 去github并搜索VaporJWT https://github.com/siemensikkema/vapor-jwt并将其导入到 Xcode 中。它将帮助您创建签名的 JSON Web 令牌。

  4. 在此 github 页面上,您将了解如何提取私钥以供 RSA 使用。

  5. 将 .pem 转换为 der
    openssl rsa -in /path/to/secret.pem -outform der -out /path/to/private.der

  6. 将 .der 转换为 .base64
    openssl base64 -in /path/to/private.der -out /path/to/Desktop/private.txt
    在 private.txt 中,您拥有以 base64 编码的私钥,您最终可以使用它来签署您的 JWT。然后您可以使用签名的 JWT 调用 Google API。

``

 import Vapor
 import VaporJWT

 let drop = Droplet()
 var tokenID:String!

 //set current date
 let dateNow = Date()

 // assign to expDate the validity period of the token returned by OAuth server (3600 seconds)
 var expDate = String(Int(dateNow.timeIntervalSince1970 + (60 * 60)))

// assign to iatDate the time when the call was made to request an access token
 var iatDate = String(Int(dateNow.timeIntervalSince1970))

// the header of the JSON Web Token (first part of the JWT)
 let headerJWT = ["alg":"RS256","typ":"JWT"]

 // the claim set of the JSON Web Token
 let jwtClaimSet =
   ["iss":"[email protected] /cdn-cgi/l/email-protection",
     "scope":"https://www.googleapis.com/auth/firebase.database",
     "aud":"https://www.googleapis.com/oauth2/v4/token",
     "exp": expDate,
     "iat": iatDate]


 //Using VaporJWT construct a JSON Web Token and sign it with RS256 algorithm
 //The only signing algorithm supported by the Google OAuth 2.0 Authorization     
 //Server is RSA using SHA-256 hashing algorithm.

  let jwt = try JWT(headers: Node(node: headerJWT), payload: Node(node:jwtClaimSet), encoding: Base64URLEncoding(), signer: RS256(encodedKey: "copy paste here what you have in private.txt as explained at point 7 above "))

 // create the JSON Web Token
  let JWTtoken = try jwt.createToken()
 let grant_type = "urn:ietf:params:oauth:grant-type:jwt-bearer" // this value must not be changed
   let unreserved = "*-._"
   let allowed = NSMutableCharacterSet.alphanumeric()
    allowed.addCharacters(in: unreserved)

// percent or URL encode grant_type
 let grant_URLEncoded = grant_type.addingPercentEncoding(withAllowedCharacters: allowed as CharacterSet)

 // create a string made of grant_type and assertion. NOTE!!! only grant_type's value is URL encoded.
 //JSON Web Token value does not need to be URL encoded
   var fullString = "grant_type=\(grant_URLEncoded!)&assertion=\(JWTtoken)"


  //pass fullString in the body parameter
   drop.get("call") { request in


    let response =  try drop.client.post("https://www.googleapis.com/oauth2/v4/token", headers: ["Content-Type": "application/x-www-form-urlencoded"], query: [:],body: fullString)

   let serverResp = response.headers
   let serverBody = response.body.bytes
      let serverJson = try JSON(bytes: serverBody!)
        print(serverJson)

     return "Success"
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何使用 JWT 为 Google firebase 生成身份验证令牌? 的相关文章

随机推荐