|
| 1 | +--- |
| 2 | +tags: |
| 3 | + - order |
| 4 | + - auth |
| 5 | + - name: how to |
| 6 | + label: Restrict Order Retrieval |
| 7 | + - server |
| 8 | +products: |
| 9 | + - order |
| 10 | + - auth |
| 11 | +--- |
| 12 | + |
| 13 | +export const metadata = { |
| 14 | + title: `Restrict Order Retrieval`, |
| 15 | +} |
| 16 | + |
| 17 | +# {metadata.title} |
| 18 | + |
| 19 | +In this guide, you'll learn how Medusa handles access to the [Get an Order API route](!api!/store/orders/get-an-order), and how to restrict access to it in your Medusa application. |
| 20 | + |
| 21 | +## How Medusa Handles Order Retrieval |
| 22 | + |
| 23 | +The `GET /store/orders/:id` API route doesn't require customer authentication. Any request that includes a valid [publishable API key](../../../storefront-development/publishable-api-keys/page.mdx) and a correct order ID receives the order's details. |
| 24 | + |
| 25 | +Medusa applies this behavior intentionally. Guest customers place orders without an account, so they have no session or token to authenticate with. After they complete the cart, the storefront redirects them to an order confirmation page that retrieves the order by its ID. Requiring authentication would break that page. |
| 26 | + |
| 27 | +The order's ID acts as the credential in this flow. Medusa generates order IDs randomly, so guessing an ID requires brute forcing a value from an address space large enough to make the attempt impractical. |
| 28 | + |
| 29 | +<Note> |
| 30 | + |
| 31 | +The [List Orders API route](!api!/store/orders/list-orders), which lists a customer's orders, does require customer authentication. Only the retrieval route accepts unauthenticated requests. |
| 32 | + |
| 33 | +</Note> |
| 34 | + |
| 35 | +--- |
| 36 | + |
| 37 | +## Restrict Access to the Route |
| 38 | + |
| 39 | +If your store doesn't allow guest checkout, you may want stricter access rules. You can add access rules with [middlewares](!docs!/learn/fundamentals/api-routes/middlewares). Middlewares that you apply to an existing API route run in addition to the route's original middlewares, so you don't have to replicate the route. |
| 40 | + |
| 41 | +For example, add the [authenticate middleware](!docs!/learn/fundamentals/api-routes/protected-routes#protect-custom-api-routes) to the route: |
| 42 | + |
| 43 | +```ts title="src/api/middlewares.ts" |
| 44 | +import { |
| 45 | + defineMiddlewares, |
| 46 | + authenticate, |
| 47 | +} from "@medusajs/framework/http" |
| 48 | + |
| 49 | +export default defineMiddlewares({ |
| 50 | + routes: [ |
| 51 | + { |
| 52 | + matcher: "/store/orders/:id", |
| 53 | + method: ["GET"], |
| 54 | + middlewares: [ |
| 55 | + authenticate("customer", ["session", "bearer"]), |
| 56 | + ], |
| 57 | + }, |
| 58 | + ], |
| 59 | +}) |
| 60 | +``` |
| 61 | + |
| 62 | +A request without an authenticated customer now receives a `401` error, while a logged-in customer still retrieves the order. |
| 63 | + |
| 64 | +<Note> |
| 65 | + |
| 66 | +This middleware only checks that a customer is authenticated. It doesn't check that the customer owns the order, so any logged-in customer can retrieve any order. Refer to the [next section](#restrict-the-route-to-the-orders-customer) to also check ownership. |
| 67 | + |
| 68 | +</Note> |
| 69 | + |
| 70 | +### Restrict the Route to the Order's Customer |
| 71 | + |
| 72 | +To allow only the customer that placed the order to retrieve it, add a custom middleware that compares the authenticated customer's ID to the order's `customer_id`. |
| 73 | + |
| 74 | +Create the file `src/api/middlewares/ensure-order-owner.ts` with the following content: |
| 75 | + |
| 76 | +export const ownerHighlights = [ |
| 77 | + ["12", "AuthenticatedMedusaRequest", "Access the authenticated customer's details."], |
| 78 | + ["20", "query", "Retrieve the order's customer."], |
| 79 | + ["28", "actor_id", "The ID of the authenticated customer."], |
| 80 | +] |
| 81 | + |
| 82 | +```ts title="src/api/middlewares/ensure-order-owner.ts" highlights={ownerHighlights} |
| 83 | +import { |
| 84 | + AuthenticatedMedusaRequest, |
| 85 | + MedusaNextFunction, |
| 86 | + MedusaResponse, |
| 87 | +} from "@medusajs/framework/http" |
| 88 | +import { |
| 89 | + ContainerRegistrationKeys, |
| 90 | + MedusaError, |
| 91 | +} from "@medusajs/framework/utils" |
| 92 | + |
| 93 | +export async function ensureOrderOwner( |
| 94 | + req: AuthenticatedMedusaRequest, |
| 95 | + res: MedusaResponse, |
| 96 | + next: MedusaNextFunction |
| 97 | +) { |
| 98 | + const query = req.scope.resolve( |
| 99 | + ContainerRegistrationKeys.QUERY |
| 100 | + ) |
| 101 | + |
| 102 | + const { data: [order] } = await query.graph({ |
| 103 | + entity: "order", |
| 104 | + fields: ["id", "customer_id"], |
| 105 | + filters: { |
| 106 | + id: req.params.id, |
| 107 | + }, |
| 108 | + }) |
| 109 | + |
| 110 | + if (order?.customer_id !== req.auth_context.actor_id) { |
| 111 | + return next( |
| 112 | + new MedusaError( |
| 113 | + MedusaError.Types.UNAUTHORIZED, |
| 114 | + "You're not allowed to retrieve this order." |
| 115 | + ) |
| 116 | + ) |
| 117 | + } |
| 118 | + |
| 119 | + next() |
| 120 | +} |
| 121 | +``` |
| 122 | + |
| 123 | +The middleware retrieves the order's `customer_id` with [Query](!docs!/learn/fundamentals/module-links/query). The `auth_context.actor_id` property holds the ID of the customer that the `authenticate` middleware authenticated. If the two IDs don't match, the middleware rejects the request with a `401` error. |
| 124 | + |
| 125 | +Then, apply the middleware after the `authenticate` middleware: |
| 126 | + |
| 127 | +```ts title="src/api/middlewares.ts" highlights={[["16", "ensureOrderOwner", "Run the ownership check after authentication."]]} |
| 128 | +import { |
| 129 | + defineMiddlewares, |
| 130 | + authenticate, |
| 131 | +} from "@medusajs/framework/http" |
| 132 | +import { |
| 133 | + ensureOrderOwner, |
| 134 | +} from "./middlewares/ensure-order-owner" |
| 135 | + |
| 136 | +export default defineMiddlewares({ |
| 137 | + routes: [ |
| 138 | + { |
| 139 | + matcher: "/store/orders/:id", |
| 140 | + method: ["GET"], |
| 141 | + middlewares: [ |
| 142 | + authenticate("customer", ["session", "bearer"]), |
| 143 | + ensureOrderOwner, |
| 144 | + ], |
| 145 | + }, |
| 146 | + ], |
| 147 | +}) |
| 148 | +``` |
| 149 | + |
| 150 | +The order of the middlewares matters. The `authenticate` middleware must run first, since `ensureOrderOwner` reads the customer that it authenticated. |
| 151 | + |
| 152 | +Now, only the customer that placed the order can retrieve it. Other logged-in customers receive a `401` error. |
0 commit comments