HarmonyOS 鸿蒙Next在node环境中如何生成鉴权令牌?
HarmonyOS 鸿蒙Next在node环境中如何生成鉴权令牌?
我们元服务中需要接入服务通知,
需要Authorization 这个令牌
我们按照文档将需要的东西配置完成后 需要生成JWT
但是文档中的示例代码 是java的 ,我们打算在云服务的node环境中配置
找了一些文档照着java的写老是生成不了鉴权令牌.
我想问下有没有大佬做过这块的内容给个源码或者关键代码看看
//使用jsonwebtoken 框架
var jwt = require(‘jsonwebtoken’);
var token = jwt.sign(payload, base64key, {header, algorithm: ‘RS256’ })
会报
secretOrPrivateKey must be an asymmetric key when using PS256
2 回复
Node.js 中使用JWT(JSON Web Tokens)身份验证和授权,参考:
https://juejin.cn/post/6976957058625044517?from=search-suggest
https://blog.csdn.net/qq_63358859/article/details/142706887
https://apifox.com/apiskills/how-to-use-jwt-in-nodejs/
示例demo:
注意:需要在-----BEGIN PRIVATE KEY-----结尾有'\n',-----END PRIVATE KEY-----开头有'\n'
let myHandler = async function (event, context, callback, logger) {
logger.info(event);
var jwt = require('jsonwebtoken');
// 注意需要在-----BEGIN PRIVATE KEY-----结尾有'\n',-----END PRIVATE KEY-----开头有'\n'
const base64key = "-----BEGIN PRIVATE KEY-----\nMIIJRAXXXXXsBTJ\n-----END PRIVATE KEY-----"
const iss = "123456789";
// 实际开发时请从服务账号密钥文件中读取key_id
const kid = "xxxxx";
const aud = "https://oauth-login.cloud.huawei.com/oauth2/v3/token";
<span class="hljs-keyword">const</span> iat = <span class="hljs-built_in">Math</span>.floor(<span class="hljs-built_in">Date</span>.now() / <span class="hljs-number">1000</span>);
<span class="hljs-keyword">const</span> exp = iat + <span class="hljs-number">3600</span>;
<span class="hljs-keyword">const</span> header = {
<span class="hljs-string">'kid'</span>: kid,
<span class="hljs-string">'alg'</span>: <span class="hljs-string">'PS256'</span>,
<span class="hljs-string">'typ'</span>: <span class="hljs-string">'JWT'</span>
};
<span class="hljs-keyword">const</span> payload = {
<span class="hljs-string">'iss'</span>: iss,
<span class="hljs-string">'iat'</span>: iat,
<span class="hljs-string">'exp'</span>: exp,
<span class="hljs-string">'aud'</span>: aud
};
jwt.sign(payload, base64key, {header: header, algorithm: <span class="hljs-string">'RS256'</span> }, <span class="hljs-function"><span class="hljs-keyword">function</span><span class="hljs-params">(err, token)</span> {</span>
callback({
code: <span class="hljs-number">0</span>,
desc: <span class="hljs-string">''</span> + token
});
});
};
export { myHandler };