【发布时间】:2021-01-05 22:00:57
【问题描述】:
我正在尝试设置 Google OAuth 身份验证,以便我可以获取帐户服务的访问令牌,并且可以通过 REST API 使用其他服务,例如 Cloud Storage。 问题是我在发出访问令牌请求时收到 400 错误,并且消息是通用的,所以我不知道什么不起作用。 我正在使用 Typescript、Node 和一些包(例如 jsonwebtokens 或 jwt-simple)来签署 JWT。
如果我遗漏了什么,有什么想法吗?
import moment from 'moment';
import jwt from 'jwt-simple';
import jsonwebtoken from 'jsonwebtoken'; // try wuth this one for signing the JWT too but same result
import axios from 'axios';
import base64Url from 'base64url';
export const authentication = function (): void {
const nowInUnix = moment().unix();
const secret = 'MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQCc9HWEZ2VtoIt5...........';
//this's supposed to be my private key so I removed the beginning and end from it 'cause in the file from where i get it was like this: "private_key": "-----BEGIN PRIVATE KEY-----MY_KEY-----END PRIVATE KEY-----\n"
let header = { "alg": "RS256", "typ": "JWT" };
const headerEncoded = base64Url.encode(JSON.stringify(header));
let claims = {
"iss": "service-account@my-project.iam.gserviceaccount.com",
"scope": "https://www.googleapis.com/auth/devstorage.full_control",
"aud": "https://oauth2.googleapis.com/token",
"exp": nowInUnix + 2000,
"iat": nowInUnix
};
const claimsEncoded = base64Url.encode(JSON.stringify(claims));
// console.log(claimsEncoded);
const stringToEncrypt = headerEncoded + '.' + claimsEncoded;
// console.log(stringToEncrypt);
const signature = jwt.encode(stringToEncrypt, secret);
// console.log(signature);
const fullToken = headerEncoded + '.' + claimsEncoded + '.' + signature;
console.log(fullToken);
// Something else i don't know if how to pass the params, I assumed it's like query params but I also tried sending the in the body request and same result.
axios.post(`https://oauth2.googleapis.com/token?grant_type=urn%3Aietf%3Aparams%3Aoauth%3Agrant-type%3Ajwt-bearer&assertion=${fullToken}`)
.then(res => console.log('todo ok'))
.catch(e => console.log(e));
}
这是我得到的错误: BAD_REQUEST:400 screenshot of the error i see
我阅读的 Google 文档:https://developers.google.com/identity/protocols/oauth2/service-account https://cloud.google.com/storage/docs/uploading-objects#rest-upload-objects
【问题讨论】:
-
1) 您正在生成错误的签名类型 (HS256)。使用 RS256
jwt.encode(payload, secret, 'RS512')。 2) 函数jwt.encode返回整个令牌(标头、有效负载和签名),而不仅仅是签名。 3)不要剥离私钥。 4) 一旦你有签名的 JWT,你必须交换一个访问令牌。阅读本文了解如何操作:jhanley.com/… -
非常感谢您的帮助!我根据您的评论更改了代码,它终于奏效了。我使用 jsonwebtoken 包对 RS512 进行编码。我只将
claimsobject 传递给了签名方法并包含了所有的私钥字符串,现在它工作得很好。再次感谢!
标签: node.js typescript google-cloud-platform google-cloud-storage google-oauth