awinogrodzki / next-firebase-auth-edge

Next.js Firebase Authentication for Edge and Node.js runtimes. Compatible with latest Next.js features.
https://next-firebase-auth-edge-docs.vercel.app/
MIT License
468 stars 42 forks source link

TypeError: Key for the RS256 algorithm must be of type CryptoKey. #242

Closed Abulkalam-Asif closed 6 days ago

Abulkalam-Asif commented 3 weeks ago

I am trying to implement persistent login. I am getting an issue with cookieSignatureKeys: TypeError: Key for the RS256 algorithm must be of type CryptoKey. Received an instance of Uint8Array I have tried generating keys using like 10 different methods but every time, I get this issue.

// middleware.ts
import { NextResponse, type NextRequest } from "next/server";
import {
  authMiddleware,
  redirectToHome,
  redirectToLogin
} from "next-firebase-auth-edge";

const PUBLIC_PATHS = ["/login"];

export async function middleware(request: NextRequest) {
  return authMiddleware(request, {
    loginPath: "/api/auth/login",
    logoutPath: "/api/auth/logout",
    apiKey: process.env.FIREBASE_API_KEY as string,
    cookieName: "AuthToken",
    cookieSignatureKeys: ["key"], // "key" just as a placeholder
    cookieSerializeOptions: {
      path: "/",
      httpOnly: true,
      secure: process.env.NODE_ENV === "production",
      sameSite: "lax" as const,
      maxAge: 60 * 60 * 24
    },
    serviceAccount: {
      projectId: process.env.FIREBASE_PROJECT_ID as string,
      clientEmail: process.env.FIREBASE_CLIENT_EMAIL as string,
      privateKey: process.env.FIREBASE_PRIVATE_KEY as string
    },
    enableMultipleCookies: true,
    handleValidToken: async ({ token, decodedToken }, headers) => {
      console.log(token, decodedToken);
      if (PUBLIC_PATHS.includes(request.nextUrl.pathname)) {
        return redirectToHome(request);
      }
      return NextResponse.next({
        request: {
          headers
        }
      });
    },
    handleInvalidToken: async reason => {
      console.info("Missing or malformed credentials", { reason });

      return redirectToLogin(request, {
        path: "/login",
        publicPaths: PUBLIC_PATHS
      });
    },
    handleError: async error => {
      console.error("Unhandled authentication error", { error });

      return redirectToLogin(request, {
        path: "/login",
        publicPaths: PUBLIC_PATHS
      });
    }
  });
}

export const config = {
  matcher: [
    "/api/auth/login",
    "/api/auth/logout",
    "/((?!_next|favicon.ico|api|.*\\.).*)"
  ]
};
awinogrodzki commented 3 weeks ago

Hey @Abulkalam-Asif,

Could you share the output of npx next info command?

What version of next-firebase-auth-edge are you using?

Abulkalam-Asif commented 3 weeks ago

Hey @Abulkalam-Asif,

Could you share the output of npx next info command?

What version of next-firebase-auth-edge are you using?

Output of npx next info:

Operating System:
  Platform: win32
  Arch: x64
  Version: Windows 10 Pro
  Available memory (MB): 12163
  Available CPU cores: 8
Binaries:
  Node: 20.15.0
  npm: N/A
  Yarn: N/A
  pnpm: N/A
Relevant Packages:
  next: 14.2.6 // Latest available version is detected (14.2.6).
  eslint-config-next: 14.2.6
  react: 18.3.1
  react-dom: 18.3.1
  typescript: 5.5.4
Next.js Config:
  output: N/A

Version:

"next-firebase-auth-edge": "^1.7.0-canary.2",
awinogrodzki commented 2 weeks ago

@Abulkalam-Asif thanks for the info!

Could you also share a stack trace of the error?

Abulkalam-Asif commented 2 weeks ago

@Abulkalam-Asif thanks for the info!

Could you also share a stack trace of the error?

I am sorry, I forgot to reply. Here is the stack trace

Error [TypeError]: Key for the RS256 algorithm must be of type CryptoKey. Received an instance of Uint8Array
    at asymmetricTypeCheck (webpack-internal:///(middleware)/./node_modules/next-firebase-auth-edge/node_modules/jose/dist/browser/lib/check_key_type.js:22:15)
    at checkKeyType (webpack-internal:///(middleware)/./node_modules/next-firebase-auth-edge/node_modules/jose/dist/browser/lib/check_key_type.js:49:9)
    at flattenedVerify (webpack-internal:///(middleware)/./node_modules/next-firebase-auth-edge/node_modules/jose/dist/browser/jws/flattened/verify.js:88:71)
    at compactVerify (webpack-internal:///(middleware)/./node_modules/next-firebase-auth-edge/node_modules/jose/dist/browser/jws/compact/verify.js:22:97)
    at jwtVerify (webpack-internal:///(middleware)/./node_modules/next-firebase-auth-edge/node_modules/jose/dist/browser/jwt/verify.js:12:97)
    at verifyCustomJWT (webpack-internal:///(middleware)/./node_modules/next-firebase-auth-edge/lib/auth/custom-token/index.js:26:33)
    at RotatingCredential.verify (webpack-internal:///(middleware)/./node_modules/next-firebase-auth-edge/lib/auth/rotating-credential.js:19:73)
    at parseTokens (webpack-internal:///(middleware)/./node_modules/next-firebase-auth-edge/lib/auth/cookies/sign.js:59:41)
    at getRequestCookiesTokens (webpack-internal:///(middleware)/./node_modules/next-firebase-auth-edge/lib/next/tokens.js:34:35)
    at authMiddleware (webpack-internal:///(middleware)/./node_modules/next-firebase-auth-edge/lib/next/middleware.js:96:73)
awinogrodzki commented 1 week ago

Thanks @Abulkalam-Asif for the stack trace.

I am not able to reproduce the issue on my end (macOS ARM, Ubuntu ARM, Amazon Linux ARM), but I think it may be connected to https://github.com/panva/jose/discussions/427

I have released a fix

Could you try next-firebase-auth-edge@1.7.0-canary.12 and let me know if it fixes the issue?

hassanzadeh commented 21 minutes ago

Hey guys, I"m having the exact same issue, tried to install the canary version and same result, any update on this?