MongoDB Stitch JWT 自定义身份验证:需要有效的 UID(介于 1 到 128 个字符之间)



如何在节点.js中为 mongodb Atlas Cloud Stitch 设置所需的有效 UID(1 到 128 个字符之间(?我正在使用jasonwebtoken包来签署 Stitch 凭据的令牌:

Nodejs:

var token = jwt.sign(payload, Buffer.from(key), options);
credential = new CustomCredential(token);
stitchclient.auth.loginWithCredential(credential)
.then(authedUser => console.log(`logged in with custom auth as user ${authedUser.id}`))
.catch( err => console.error(`failed to log in with custom auth: ${err}`))

我可以发送,通过签名,但 Stitch 返回:

无法使用自定义身份验证登录:拼接服务错误:自定义无效 身份验证令牌:需要有效的 UID(介于 1 到 128 个字符之间(

泰为你的时间!

有关以下内容的文档: https://docs.mongodb.com/stitch/authentication/custom-token/#usage

更具体地说,例如,如果您从 Realm 函数生成令牌,您将从上下文中获取用户 ID:

exports = function(userMail) {
const jwt = require('jsonwebtoken')
const KEY_JWT = 'MY_SECRET_KEY'
const token = jwt.sign({
email: userMail, 
sub: context.user.id,
aud: "<application_id>"
},
KEY_JWT,
{
expiresIn: "1h"
}
)
return token
}

已解决:

在有效负载上预先设置:

"aud": "your api stitch id",
"sub": "your user custom api key"
var header = {
alg: "HS256",
typ: "JWT"
}
var payload = {
"aud": "your api stitch id",
"sub": "your user custom api key",
name : "name",
pass : "pass",
} 
var options = {
expiresIn : (60 * 60 * 24).toString(), // ONE DAY TO EXPIRATION
algorithm: 'HS256'
} 

后:

var token = jwt.sign(payload, Buffer.from("your user custom api key"), options);
credential = new CustomCredential(token);
stitchclient.auth.loginWithCredential(credential)
.then(authedUser => console.log(`logged in with custom auth as user ${authedUser.id}`))
.catch( err => console.error(`failed to log in with custom auth: ${err}`))

最新更新