How to decrypt JWE via RSA private key in next js?

We have a JWE token that we want to decrypt using a given RSA private key. If the token is valid, we will grant access to the website; otherwise, the user will be redirected to https://example.com. I have used the node-jose and jose libraries, but I am unsure how to implement this in Next.js.

Here is my middelware.js:

import cookie from 'cookie';
import { NextResponse } from 'next/server';
import jose from 'node-jose';
import { Buffer } from 'buffer';
// Your private key in PEM format

const privateKey = `-----BEGIN RSA PRIVATE KEY-----
// key here
-----END RSA PRIVATE KEY-----`;


export async function middleware(req) {
 const token = 'token here'; // Sample token
  if (!token) {
    console.log('No token found, redirecting...');
    return NextResponse.redirect('https://www.example.com');
  }
  try {
    // Create a keystore and add the private key
    const keystore = jose.JWK.createKeyStore();
    await keystore.add(privateKey, 'pem');
    console.log('Key added to keystore:', keystore);
    // Define the allowed algorithms for decryption
    const opts = {
      algorithms: ['RSA-OAEP', 'A256GCM']
    };
    // Decrypt the JWE token
    const decryptedToken = await jose.JWE.createDecrypt(keystore, opts).decrypt(token);
    // Decode and parse the payload
    const decodedPayload = JSON.parse(decryptedToken.plaintext.toString());
    console.log('Decoded payload:', decodedPayload);
    // Check token expiry
    if (decodedPayload.exp < Math.floor(Date.now() / 1000)) {
      console.log('Token expired, redirecting...');
      return NextResponse.redirect('https://www.example.com');
    }
    console.log('Token is valid, continuing request...');
    return NextResponse.next();
  } catch (err) {
    console.error('Token decryption failed:', err);
    return NextResponse.redirect('https://www.example.com');
  }

Here’s a snippet using a different module.

You’ll need to encode your private key as PKCS#8 instead of PKCS#1, or just use JWK format and importJWK.

import * as jose from 'jose';

// key needs to be in PKCS#8 format, not PKCS#1
const privateKeyPem = `-----BEGIN PRIVATE KEY-----
// key here
-----END PRIVATE KEY-----`;

const alg = 'RSA-OAEP'
const enc = 'A256GCM'

const privateKey = await jose.importPKCS8(privateKeyPem, alg)

export async function middleware(req) {
 const token = 'token here'; // Sample token
  if (!token) {
    console.log('No token found, redirecting...');
    return NextResponse.redirect('https://www.example.com');
  }
  try {
    await jose.jwtDecrypt(token, privateKey, {
      keyManagementAlgorithms: [alg],
      contentEncryptionAlgorithms: [enc]
    })
    console.log('Token is valid and not expired, continuing request...');
    return NextResponse.next();
  } catch (err) {
    if (err.code === 'ERR_JWT_EXPIRED') {
      console.log('Token is expired');
    }
    console.error('Token decryption failed:', err);
    return NextResponse.redirect('https://www.example.com');
  }
}

It is worth noting that if you issue these tokens yourself for yourself to consume then you’re using the wrong cipher suite. With the one you’ve chosen anyone (presumably given the encryption is done with a PUBLIC key) can make their own tokens for your API to accept. If you issue these tokens yourself for yourself to consume then alg: dir and enc: A256CBC-HS512 would be a far more appropriate suite to use and it uses a 64 byte symmetric secret as a key.

5

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật