使用带有 RS256 加密的 express-jwt 在应用程序路由上解码 JWT 令牌会引发未授权错误

问题描述

我正在使用 Keycloak 进行身份验证,并使用它的中间件将令牌附加到我的请求中。我试图编写一个使用该令牌检索用户数据的 api 路由,但出现以下错误:

UnauthorizedError: error:0909006C:PEM routines:get_name:no start line

目前我正在访问“/protected/”路由上的用户数据

app.get('/protected',jwt({
  secret: Buffer.from(process.env.TOKEN_SECRET as string),algorithms: ['RS256'],requestProperty: 'auth',getToken: (req: any) => {
    const token = req?.kauth?.grant?.access_token;
    if (token) {
      console.log(token.token.toString())
      return token.token.toString();
    } 
    return null;
  }
}),(req: any,res: any) => {
  return res.json(req.auth)
});

我正在从 keycloak 控制台获取我的公钥 - 但我仍然收到该错误。

** 编辑 **

在秘密中添加第一行和最后一行后:

`-----BEGIN PUBLIC KEY-----\r\n${Buffer.from(process.env.TOKEN_SECRET as string)}\r\n-----END PUBLIC KEY-----`

我现在收到一个新错误:

UnauthorizedError: No authorization token was found

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)