【问题标题】:Migrating from Auth0.js to Auth0-spa.js - Jwt malformed从 Auth0.js 迁移到 Auth0-spa.js - Jwt 格式错误
【发布时间】:2020-01-30 13:21:01
【问题描述】:

我正在尝试将我的应用从 auth0 迁移到 auth0-spa.js。我已经让它几乎可以工作了,而且这个新库的代码肯定更简单,所以我想继续使用它,但我还需要一个有效的 jwt 令牌作为后端。

我在我的节点服务器上使用以下中间件 (express-jwt)

export const jwtCheckMiddleware = jwt({
    secret: '....',
    getToken: function (req) {
       if (req.headers.authorization && req.headers.authorization.split(' ')[0] === 'Bearer') {
           return req.headers.authorization.split(' ')[1];
       }
    },
    issuer: `https://${environment.auth.auth0Domain}/`,
    algorithm: 'RS256'
});

以前我会从 auth0 传递 idToken 并且它有效。现在我通过await auth0.getTokenSilently() 获得了一个令牌,但是将它传递给中间件会给我“jwt malformed”。

如何从 auth0-spa.js 获取有效的 JWT 令牌?另外,我将如何确保我传递给中间件的令牌永不过期?

【问题讨论】:

  • 当我认为您的意思是访问令牌时,您提到了 ID 令牌。你能打印 getTokenSilently() 函数的结果并在网站 jwt.io 上验证它吗?

标签: auth0


【解决方案1】:

好的,所以我可以通过向 Auth0 注册自定义 API,然后将 API 标识符作为受众传递,让 auth-spa.js 给我一个 jwt 令牌。

更多信息在这里:https://auth0.com/docs/getting-started/set-up-api

const auth0 = createAuth0Client({
  audience: environment.auth.audience,  <-----API identifier of custom API in Auth0
  client_id: environment.auth.clientId,
  domain: environment.auth.clientDomain
});

添加观众后,getTokenSilently() 给了我一个 JWT 令牌,我将它传递给节点。然后我必须在我的 jwt 中间件中添加观众:

export const jwtCheckMiddleware = jwt({
    secret: jwks.expressJwtSecret({
        cache: true,
        rateLimit: true,
        jwksRequestsPerMinute: 5,
        jwksUri: `https://${environment.auth.auth0Domain}/.well-known/jwks.json`
    }),
    audience: environment.auth.auth0ApiAudience,  <!--- API identifier
    issuer: `https://${environment.auth.auth0Domain}/`,
    algorithms: ['RS256']
});

【讨论】:

    猜你喜欢
    • 2022-08-17
    • 1970-01-01
    • 1970-01-01
    • 2018-03-13
    • 2021-04-16
    • 2021-09-11
    • 2020-11-07
    • 2017-01-23
    • 2018-12-16
    相关资源
    最近更新 更多