首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >快速Vapor unsupported_grant_type无效签名/ OAuth访问令牌

快速Vapor unsupported_grant_type无效签名/ OAuth访问令牌
EN

Stack Overflow用户
提问于 2016-11-19 17:46:14
回答 2查看 914关注 0票数 1

我正在使用Vapor和SWIFT 3运行Xcode 8.1。

我向google发送了一个请求,以获得一个auth令牌,这样我就可以调用FireBaseDB API,但是我得到了错误:unsupported_ grant_type _type/无效的grant_type。

developers.google.com上,它说我必须在URL中编码以下内容:https://www.googleapis.com/oauth2/v4/token + grant_type +断言,并将编码的URL传递到POST请求的正文中。我把它当作一根线传递。

我注意到从我的服务帐户下载的JSON文件中的私钥包含一些字符,比如/n、

代码语言:javascript
运行
复制
    let dateNow = Date()
      var expDate = String(Int(dateNow.timeIntervalSince1970 + (60 * 60)))
        var iatDate = String(Int(dateNow.timeIntervalSince1970))


 let headerJWT = ["alg":"HS256","typ":"JWT"]
    let jwtClaimSet =
    ["iss":"firebase-adminsdk-c7i48@fir-10c2e.iam.gserviceaccount.com",
     "scope":"https://www.googleapis.com/auth/firebase.database",
      "aud":"https://www.googleapis.com/oauth2/v4/token",
       "exp": expDate,
         "iat": iatDate]

      //create and sign JSON Web Token
   let jwt = try JWT(headers: Node(node: headerJWT),
              payload: Node(node: jwtClaimSet),
               signer: HS256(key:"-----BEGIN PRIVATE KEY-----\nMIIEvAWvQ== \n-----END PRIVATE KEY-----\n"))

    // Store JSON Web Token
      let JWTtoken = try jwt.createToken()

func createUrlWithString() -> NSURL {
    var urlString = "https://www.googleapis.com/oauth2/v4/token"
     urlString.append("?grant_type=")
      urlString.append("urn:ietf:params:oauth:grant-type:jwt-bearer")
       urlString.append("&assertion=")
        urlString.append(JWTtoken)
  return NSURL(string: urlString)!
 }

        // make the body input for our POST
      let bodyURL =  createUrlWithString().absoluteURL

     drop.get("any") { request in
        let response =  
 try drop.client.request(.other(method:"Post"),
           "https://www.googleapis.com/oauth2/v4/token", 
             headers: ["Content-Type": "application/x-www-form-urlencoded"], 
                 query: [:], 
                  body: String(describing: bodyURL) )


     let serverResp = response.headers
        let serverBody = response.body.bytes
          let serverJson = try JSON(bytes: serverBody!)
             print(serverJson)
    return "POST Request went through"
}

更新

根据Karol的建议,我将grant_typeassertion参数作为POST请求参数传递。现在我得到了"error_description": Node.Node.string("SSL is required to perform this operation.")]))

代码语言:javascript
运行
复制
func createUrlWithString() -> NSURL {
 var urlString = "https://www.googleapis.com/oauth2/v4/token"
  urlString.append("?grant_type=")
    urlString.append("urn:ietf:params:oauth:grant-type:jwt-bearer")
     urlString.append("&assertion=")
      urlString.append(JWTtoken)
  return NSURL(string: urlString)!
}

  let response =  try drop.client.request(.other(method:"Post"), 
   String(describing: bodyURL),
      headers: ["Content-Type": "application/x-www-form-urlencoded"], 
         query: [:])
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2016-11-22 21:35:14

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

如果在Google平台之外的生产环境中使用应用程序默认凭据,则需要使用JSON键。JSON键不能转换成其他格式,许多不同的编程语言和库都支持 PKCS12 (.p12)。如果需要,可以使用OpenSSL (请参阅将私钥转换为其他格式。)将密钥转换为其他格式。但是,PKCS12键不能转换为JSON格式。

  1. 创建服务帐户,然后下载.p12文件。
  2. 使用pkcs12将p.12 (a.k.a pkcs1)文件转换为.pem (a.k.a pkcs1)

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

  1. 转到github并搜索VaporJWT并在Xcode中导入它。它将帮助您创建一个签名的JSON令牌。
  2. 在这个github页面上,您将了解如何提取用于RSA的私钥。
  3. //将.pem转换为der openssl rsa -in /path/to/secret.pem -outform der -out /path/to/private.der
  4. //将.der转换为.base64 openssl base64 -in /path/to/private.der -out /path/to/Desktop/private.txt 在private.txt中,私钥是用base64编码的,最终可以用来为您签名JWT。然后,您可以使用签名的JWT调用Google。

代码语言:javascript
运行
复制
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 returnd 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":"firebase-adminsdk-c7i38@fir-30c9e.iam.gserviceaccount.com",
     "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"
}
票数 1
EN

Stack Overflow用户

发布于 2016-11-19 20:04:19

您似乎没有在代码中正确设置grant_type

代码语言:javascript
运行
复制
urlString.append("?grant_type=")

在您的例子中,可能是grant_type=authorization_codegrant_type=jwt-bearer

看来你把grant_type放错地方了。

更新

另外,我认为grant_type和断言参数不是作为请求头传递的,而是作为post请求参数传递的。

更新

我不太确定你是否使用了正确的方式来设置POST (body)参数。在文档中,示例是如何使用post prams创建请求,如下所示:

代码语言:javascript
运行
复制
try drop.client.request(.other(method: "POST"), "http://some-domain", headers: ["My": "Header"], query: ["key": "value"], body: [])
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/40696026

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档