I am running Xcode 8.1 with Vapor and SWIFT 3.
I am posting a request to to google server to get an auth token, so I can call FireBaseDB API, but I get error: unsupported_grant_type/Invalid grant_type.
On developers.google.com it says that I have to encode in a URL the following: https://www.googleapis.com/oauth2/v4/token + grant_type + assertion, and pass the encoded URL in the body of the POST request. I pass it as a string.
I have noticed that the private key from the JSON file downloaded from my service account contains characters such as /n , ----,==, should I delete them before posting the key?
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"
}
Update
As per Karol Gasienica suggestion, I am passing grant_type
and assertion
parameters as POST request parameters. Now I get "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: [:])