我正在使用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、
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_type和assertion参数作为POST请求参数传递。现在我得到了"error_description": Node.Node.string("SSL is required to perform this operation.")]))
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: [:])发布于 2016-11-19 20:04:19
您似乎没有在代码中正确设置grant_type:
urlString.append("?grant_type=")在您的例子中,可能是grant_type=authorization_code或grant_type=jwt-bearer
看来你把grant_type放错地方了。
更新
另外,我认为grant_type和断言参数不是作为请求头传递的,而是作为post请求参数传递的。
更新
我不太确定你是否使用了正确的方式来设置POST (body)参数。在这文档中,示例是如何使用post prams创建请求,如下所示:
try drop.client.request(.other(method: "POST"), "http://some-domain", headers: ["My": "Header"], query: ["key": "value"], body: [])https://stackoverflow.com/questions/40696026
复制相似问题