next.js 对www.example.com使用jose而不是jsonwebtokenClerk.dev

j2qf4p5b  于 2022-11-23  发布在  其他
关注(0)|答案(1)|浏览(99)

我尝试在Next.js(v12.3.2)上验证中间件中的JWT标记,但得到jsonwebtoken错误(以下文档:https://clerk.dev/docs/request-authentication/validate-session-tokens),因为它需要节点环境。
我尝试使用jose代替Clerk.devCLERK_JWT_KEY,但我一直收到[错误:Key info does not have required parameters] error.以下是我的代码,以供参考:

export const decodeAndVerifyToken = async (
  getToken: ServerGetToken
): Promise<JWTPayload | undefined> => {
  // initialize a variable for the token
  let token: string | null;

  try {
    // get the token using metadata template, which should return
    // a 'publicMetadata' object containing an 'isAdmin' value
    token = await getToken({ template: "metadata" });
  } catch (err) {
    // if we had an error getting the token, return undefined
    return undefined;
  }

  // if no token is found, then short-circuit to undefined
  if (!token) {
    return undefined;
  }

  // split the jwt key to 64-bit lines
  const splitPem = process.env.CLERK_JWT_KEY?.match(/.{1,64}/g) ?? [];

  // combine into a public key format
  const publicKey =
    "-----BEGIN PUBLIC KEY-----\n" +
    splitPem.join("\n") +
    "\n-----END PUBLIC KEY-----";

  //

  const test = await importSPKI(publicKey, "ES256").catch((err) =>
    console.log(err)
  );
};

我也尝试过直接调用const decoded = await jwtVerify(token, publicKey);,但这也会产生错误。
有人知道怎么称呼吗?

5kgi1eie

5kgi1eie1#

根据clerk.dev中的示例密钥,这些是您要导入的RSA密钥。该密钥是not a valid key for ES256,您将其传递给importSPKI
我怀疑算法将是RS256,但要确保检查令牌的头部进行确认。
看看这些文档,它们确实有一个JWKs端点,所以这对您来说可能要容易得多。

import * as jose from 'jose'

const JWKS = jose.createRemoteJWKSet(new URL('https://<YOUR_FRONTEND_API>/.well-known/jwks.json')) 

const { payload, protectedHeader } = await jose.jwtVerify(token, JWKS)

相关问题