1 import { TypeList, Table } from "docs-ui"
2
3 export const metadata = {
4 title: `${pageNumber} Asymmetric Encryption`,
5 }
6
7 # {metadata.title}
8
9 In this chapter, you'll learn how to configure asymmetric encryption in Medusa using public/private key pairs instead of a shared secret.
10
11 ## What is Asymmetric Encryption?
12
13 By default, Medusa uses symmetric JWT authentication, where the same secret signs and verifies tokens. With asymmetric encryption, you use a private key to sign tokens and a public key to verify them.
14
15 This approach provides better security, supports key rotation, and enables distributed systems where multiple services can verify tokens without needing access to the signing key.
16
17 ### When to Use Asymmetric Encryption
18
19 Asymmetric encryption is useful in several scenarios:
20
21 <Table>
22 <Table.Header>
23 <Table.Row>
24 <Table.HeaderCell>
25 Scenario
26 </Table.HeaderCell>
27 <Table.HeaderCell>
28 Description
29 </Table.HeaderCell>
30 <Table.HeaderCell>
31 Benefits
32 </Table.HeaderCell>
33 </Table.Row>
34 </Table.Header>
35 <Table.Body>
36 <Table.Row>
37 <Table.Cell>
38 Multi-Instance Deployments
39 </Table.Cell>
40 <Table.Cell>
41 Running multiple Medusa instances behind a load balancer.
42 </Table.Cell>
43 <Table.Cell>
44 Centralized signing, reduced risk if an instance is compromised.
45 </Table.Cell>
46 </Table.Row>
47 <Table.Row>
48 <Table.Cell>
49 Microservices Architecture
50 </Table.Cell>
51 <Table.Cell>
52 Medusa as part of a larger microservices ecosystem.
53 </Table.Cell>
54 <Table.Cell>
55 Independent token verification across services.
56 </Table.Cell>
57 </Table.Row>
58 <Table.Row>
59 <Table.Cell>
60 JWKS Support
61 </Table.Cell>
62 <Table.Cell>
63 Dynamic key rotation using JSON Web Key Sets.
64 </Table.Cell>
65 <Table.Cell>
66 Seamless key rotation without service disruption.
67 </Table.Cell>
68 </Table.Row>
69 </Table.Body>
70 </Table>
71
72 ---
73
74 ## How to Configure Asymmetric Encryption
75
76 ### Step 1: Install Dependencies
77
78 First, you need to install `jsonwebtoken` to handle JWT token creation and verification.
79
80 Run the following command in your Medusa application:
81
82 ```bash npm2yarn
83 npm install jsonwebtoken
84 ```
85
86 ### Step 2: Set Asymmetric JWT Configuration
87
88 To configure asymmetric encryption, you need to set up both signing and verification options in your `medusa-config.ts` file.
89
90 In `medusa-config.ts`, create a helper function to load the JWT configuration, and use it in the exported configuration:
91
92 ```ts title="medusa-config.ts"
93 // other imports...
94 import jwt from "jsonwebtoken"
95
96 export const getJwtConfig = () => {
97 return {
98 jwtSecret: process.env.JWT_SECRET_KEY,
99 jwtPublicKey: process.env.JWT_PUBLIC_KEY,
100 jwtExpiresIn: process.env.JWT_EXPIRES_IN || "1d",
101 jwtOptions: {
102 algorithm: (process.env.JWT_ALGORITHM || "RS256") as jwt.Algorithm,
103 audience: process.env.JWT_AUDIENCE
104 ? process.env.JWT_AUDIENCE.split(",")
105 : undefined,
106 issuer: process.env.JWT_ISSUER,
107 keyid: process.env.JWT_KEYID,
108 },
109 jwtVerifyOptions: {
110 algorithms: [(process.env.JWT_ALGORITHM || "RS256") as jwt.Algorithm],
111 audience: process.env.JWT_AUDIENCE
112 ? process.env.JWT_AUDIENCE.split(",")
113 : undefined,
114 issuer: process.env.JWT_ISSUER,
115 },
116 }
117 }
118
119 const jwtConfig = getJwtConfig()
120
121 module.exports = defineConfig({
122 projectConfig: {
123 http: {
124 // ...
125 jwtSecret: jwtConfig.jwtSecret,
126 jwtPublicKey: jwtConfig.jwtPublicKey,
127 jwtExpiresIn: jwtConfig.jwtExpiresIn,
128 jwtOptions: jwtConfig.jwtOptions,
129 jwtVerifyOptions: jwtConfig.jwtVerifyOptions,
130 },
131 // ...
132 },
133 modules: [
134 {
135 resolve: "@medusajs/medusa/user",
136 options: {
137 jwt_secret: {
138 key: jwtConfig.jwtSecret,
139 },
140 jwt_public_key: jwtConfig.jwtPublicKey,
141 jwt_options: jwtConfig.jwtOptions,
142 },
143 },
144 ],
145 })
146 ```
147
148 You set the JWT configurations in the following options:
149
150 1. [http options](../page.mdx#http): You set the global JWT options for Medusa's HTTP layer, which are used to sign and verify JWT authentication tokens.
151 - Refer to the [Medusa Configuration chapter](../page.mdx#http) for more details on these options and their default values.
152 2. [User Module options](!resources!/commerce-modules/user/module-options): You set the JWT options specific to the User Module, which are used to sign and verify invite tokens.
153
154 ### Step 3: Generate Key Pair
155
156 Next, generate an RSA key pair (private and public keys) for signing and verifying tokens. You can use OpenSSL to generate the keys:
157
158 ```bash
159 # Generate private key
160 openssl genrsa -out private-key.pem 2048
161
162 # Extract public key
163 openssl rsa -in private-key.pem -pubout -out public-key.pem
164 ```
165
166 Make sure not to commit your private key to Git or any public repository. Add it to your `.gitignore` file to prevent accidental commits:
167
168 ```title=".gitignore"
169 # Asymmetric encryption keys (DO NOT COMMIT)
170 private-key.pem
171 *.pem
172 ```
173
174 ### Step 4: Set Environment Variables
175
176 Finally, set the following environment variables using the generated keys:
177
178 ```bash
179 # JWT Configuration
180 JWT_SECRET_KEY="-----BEGIN RSA PRIVATE KEY-----
181 MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQC...
182 -----END RSA PRIVATE KEY-----"
183
184 JWT_PUBLIC_KEY="-----BEGIN PUBLIC KEY-----
185 MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAvTtLGDIK...
186 -----END PUBLIC KEY-----"
187
188 JWT_ALGORITHM=RS256
189 JWT_EXPIRES_IN=1d
190 JWT_ISSUER=medusa
191 JWT_AUDIENCE=medusa-api
192 JWT_KEYID=medusa-key-1
193 ```
194
195 Where:
196
197 - `JWT_SECRET_KEY`: Your RSA private key for signing tokens.
198 - `JWT_PUBLIC_KEY`: Your RSA public key for verifying tokens.
199 - `JWT_ALGORITHM`: The [signing algorithm](https://www.npmjs.com/package/jsonwebtoken#algorithms-supported).
200 - `JWT_EXPIRES_IN`: The token expiration time.
201 - `JWT_ISSUER`: (Optional) The issuer claim for tokens.
202 - `JWT_AUDIENCE`: (Optional) The audience claim for tokens.
203 - `JWT_KEYID`: (Optional) The key ID for JWKS support.
204
205 <Note title="Tip">
206
207 For multiline keys in `.env` files, wrap the key with double quotes and use `\n` for newlines.
208
209 </Note>
210
211 ---
212
213 ## Using JWKS (JSON Web Key Set)
214
215 JWKS (JSON Web Key Set) is a set of public keys used to verify JWT tokens. By exposing a JWKS endpoint, you allow clients to dynamically fetch your public keys for token verification, enabling key rotation without requiring clients to update their configurations.
216
217 This section explains how to set up JWKS support in Medusa and verify tokens using JWKS.
218
219 ### Step 1: Install Required Packages
220
221 First, install the packages for handling JWKS and JWT verification. Run the following command in your Medusa application:
222
223 ```bash npm2yarn
224 npm install jwks-rsa jsonwebtoken
225 npm install @types/jsonwebtoken@8.5.9 --save-dev
226 ```
227
228 You install the following packages:
229
230 1. `jwks-rsa`: A library to create a JWKS client that can fetch and cache public keys.
231 2. `jsonwebtoken`: A library to handle JWT token creation and verification.
232 3. `@types/jsonwebtoken`: TypeScript types for the `jsonwebtoken` package. Make sure to install version `8.5.9` for compatibility.
233
234 ### Step 2: Expose JWKS Endpoint
235
236 To allow clients to fetch the JWKS, expose it in an [API route](../../../fundamentals/api-routes/page.mdx).
237
238 In the API route, return the JWKS content containing your public keys. You can set the JWKS content using an environment variable or by manually converting your public key to JWK format.
239
240 #### Option 1: Environment Variable
241
242 The first option is to set the JWKS content using an environment variable. Convert your public key to JWK format using online tools or libraries like [node-jose](https://www.npmjs.com/package/node-jose).
243
244 For example, add the following environment variable:
245
246 ```bash
247 JWKS_CONTENT='{"keys":[{"kty":"RSA","use":"sig","kid":"medusa-key-1","n":"vTtLGDIK...","e":"AQAB"}]}'
248 ```
249
250 Then, create the API route at `src/api/.well-known/jwks.json/route.ts` with the following content:
251
252 ```ts title="src/api/.well-known/jwks.json/route.ts"
253 import type {
254 MedusaRequest,
255 MedusaResponse,
256 } from "@medusajs/framework/http"
257
258 export const GET = async (
259 req: MedusaRequest,
260 res: MedusaResponse
261 ) => {
262 if (!process.env.JWKS_CONTENT) {
263 return res.status(500).json({ error: "JWKS_CONTENT not configured" })
264 }
265
266 res.status(200).json(JSON.parse(process.env.JWKS_CONTENT))
267 }
268 ```
269
270 This exposes your public key at `/.well-known/jwks.json`, which clients can fetch to verify tokens.
271
272 #### Option 2: Manual JWK Conversion
273
274 If you prefer not to use an environment variable, manually convert your public key to JWK format using the JWT configurations you set in `medusa-config.ts`.
275
276 For example, create the API route at `src/api/.well-known/jwks.json/route.ts` with the following content:
277
278 ```ts title="src/api/.well-known/jwks.json/route.ts"
279 import type {
280 MedusaRequest,
281 MedusaResponse,
282 } from "@medusajs/framework/http"
283 import crypto from "crypto"
284 import {
285 ContainerRegistrationKeys,
286 } from "@medusajs/framework/utils"
287
288 export const GET = async (
289 req: MedusaRequest,
290 res: MedusaResponse
291 ) => {
292 const configModule = req.scope.resolve(
293 ContainerRegistrationKeys.CONFIG_MODULE
294 )
295 const { projectConfig } = configModule
296
297 // If JWKS_CONTENT is set, use it
298 if (process.env.JWKS_CONTENT) {
299 return res.status(200).json(JSON.parse(process.env.JWKS_CONTENT))
300 }
301
302 // Otherwise, generate from public key
303 const publicKey = projectConfig.http.jwtPublicKey
304 if (!publicKey) {
305 return res.status(500).json({ error: "No public key configured" })
306 }
307
308 try {
309 // Convert PEM to JWK
310 const jwk = crypto.createPublicKey(publicKey).export({ format: "jwk" })
311
312 const jwks = {
313 keys: [{
314 ...jwk,
315 use: "sig",
316 kid: projectConfig.http.jwtOptions?.keyid || "medusa-key-1",
317 alg: projectConfig.http.jwtOptions?.algorithm || "RS256",
318 }],
319 }
320
321 res.status(200).json(jwks)
322 } catch (error: any) {
323 return res.status(500).json({
324 error: "Failed to generate JWKS",
325 message: error.message,
326 })
327 }
328 }
329 ```
330
331 In the above example:
332
333 1. Check if the `JWKS_CONTENT` environment variable is set and return it if available.
334 2. If not, retrieve the public key from the Medusa configuration and convert it to JWK format using Node's `crypto` module.
335 3. Construct the JWKS response and return it.
336
337 The public key will be available at `/.well-known/jwks.json` for clients to fetch.
338
339 ### Step 3: Verify Tokens Using JWKS
340
341 Finally, verify JWT tokens from incoming requests using the JWKS API route.
342
343 Create a [middleware](../../../fundamentals/api-routes/middlewares/page.mdx) function at `src/api/middlewares/jwks-auth.ts` that uses the `jwks-rsa` package to fetch the public key and verify the token:
344
345 ```ts title="src/api/middlewares/jwks-auth.ts"
346 import {
347 MedusaRequest,
348 MedusaNextFunction,
349 MedusaResponse,
350 } from "@medusajs/framework/http"
351 import jwt from "jsonwebtoken"
352 import { JwksClient } from "jwks-rsa"
353 import { MedusaError } from "@medusajs/framework/utils"
354
355 const MEDUSA_BACKEND_URL = process.env.MEDUSA_BACKEND_URL || "http://localhost:9000"
356
357 // Create JWKS client with caching
358 const jwksClient = new JwksClient({
359 // This is the API route where your JWKS is exposed
360 jwksUri: `${MEDUSA_BACKEND_URL}/.well-known/jwks.json`,
361 cache: true,
362 rateLimit: true,
363 jwksRequestsPerMinute: 5,
364 cacheMaxAge: 60 * 60 * 1000, // 1 hour in ms
365 })
366
367 // Helper to get signing key
368 async function getKey(header: any) {
369 try {
370 const key = await jwksClient.getSigningKey(header.kid)
371
372 return key.getPublicKey()
373 } catch (err: any) {
374 throw new MedusaError(
375 MedusaError.Types.UNEXPECTED_STATE,
376 `Failed to get signing key: ${err.message}`
377 )
378 }
379 }
380
381 // Function that validates JWT token
382 export async function isValidJWTToken(token: string): Promise<boolean> {
383 if (!token) {
384 return false
385 }
386
387 try {
388 // Decode the token to get the header
389 const decoded = jwt.decode(token, { complete: true }) as {
390 header: { kid: string }
391 payload: {
392 actor_id: string
393 }
394 } | null
395
396 if (
397 !decoded ||
398 !decoded.header ||
399 !decoded.header.kid ||
400 !decoded.payload.actor_id
401 ) {
402 return false
403 }
404
405 const publicKey = await getKey(decoded.header)
406
407 return new Promise((resolve) => {
408 jwt.verify(
409 token,
410 publicKey,
411 {
412 ignoreExpiration: false,
413 ignoreNotBefore: false,
414 },
415 (err) => {
416 if (err) {
417 console.error("Error verifying JWT token:", err)
418 resolve(false)
419 }
420
421 resolve(true)
422 }
423 )
424 })
425 } catch (err: any) {
426 console.error("Error validating JWT token:", err)
427 return false
428 }
429 }
430
431 // Authentication middleware
432 export const jwtAuthMiddleware = async (
433 req: MedusaRequest,
434 res: MedusaResponse,
435 next: MedusaNextFunction
436 ) => {
437 const authHeader = req.headers.authorization
438 const jwtToken = authHeader?.split(" ")[1]
439
440 // If we should check login and the JWT token is invalid, return 401
441 if (!jwtToken || !(await isValidJWTToken(jwtToken))) {
442 const error = new Error(
443 "Invalid auth token provided"
444 )
445
446 return next(error)
447 }
448
449 return next()
450 }
451 ```
452
453 The `jwtAuthMiddleware` function extracts the JWT token from the `Authorization` header, fetches the appropriate public key from the JWKS endpoint, and verifies the token.
454
455 Apply this middleware to your protected API routes to ensure that only requests with valid JWT tokens are allowed.
456
457 For example, apply the middleware in `src/api/middlewares.ts`:
458
459 ```ts title="src/api/middlewares.ts"
460 import { defineMiddlewares } from "@medusajs/framework/http"
461 import { jwtAuthMiddleware } from "./middlewares/jwks-auth"
462
463 export default defineMiddlewares({
464 routes: [
465 {
466 matcher: "/custom-protected-route*",
467 middlewares: [jwtAuthMiddleware],
468 },
469 ],
470 })
471 ```
472
473 ### Test JWKS Verification
474
475 To test the JWKS verification, start the Medusa application:
476
477 ```bash npm2yarn
478 npm run dev
479 ```
480
481 Next, obtain a valid JWT token by authenticating a user. For example, to authenticate an admin user, send a `POST` request to `/auth/user/emailpass`:
482
483 ```bash
484 curl -X POST http://localhost:9000/auth/user/emailpass \
485 -H "Content-Type: application/json" \
486 -d '{
487 "email": "admin@medusa-test.com",
488 "password": "supersecret"
489 }'
490 ```
491
492 Make sure to replace the email and password with valid credentials for your Medusa application.
493
494 The response will include a `token` field, which is your JWT token.
495
496 Finally, make a request to your protected route using the obtained JWT token:
497
498 ```bash
499 curl http://localhost:9000/custom-protected-route \
500 -H "Authorization: Bearer YOUR_JWT_TOKEN"
501 ```
502
503 If the token is valid, the middleware will successfully verify it using the public key fetched from the JWKS endpoint, and you'll receive a successful response. If the token is invalid or expired, you'll receive an error.