|
1
|
--- |
|
2
|
tags: |
|
3
|
- auth |
|
4
|
- user |
|
5
|
- name: server |
|
6
|
label: Custom Admin Authentication |
|
7
|
products: |
|
8
|
- auth |
|
9
|
- user |
|
10
|
--- |
|
11
|
|
|
12
|
export const metadata = { |
|
13
|
title: `How to Add Custom Authentication in Medusa Admin`, |
|
14
|
} |
|
15
|
|
|
16
|
# {metadata.title} |
|
17
|
|
|
18
|
In this guide, you'll learn how to add custom authentication provider to the Medusa Admin. |
|
19
|
|
|
20
|
<Note> |
|
21
|
|
|
22
|
Authenticating into the Medusa Admin with third-party providers is supported from [Medusa v2.12.0](https://github.com/medusajs/medusa/releases/tag/v2.12.0). |
|
23
|
|
|
24
|
</Note> |
|
25
|
|
|
26
|
## Overview |
|
27
|
|
|
28
|
By default, the Medusa Admin allows users to authenticate using their email and password. Medusa uses the [Emailpass Authentication Provider](../../../../commerce-modules/auth/auth-providers/emailpass/page.mdx) to handle this authentication method. |
|
29
|
|
|
30
|
You can also integrate a custom or third-party authentication provider to allow users registered with that provider to log in to the Medusa Admin. This delegates the authentication process to the third-party provider, which is useful if your organization uses a centralized authentication system. |
|
31
|
|
|
32
|
<Note type="warning"> |
|
33
|
|
|
34
|
Ensure the third-party authentication provider allows **only** your organization's users to log in to the Medusa Admin. For example, integrating a social login provider like Google or Facebook without restrictions will allow any user with an account on those platforms to access your Medusa Admin. |
|
35
|
|
|
36
|
</Note> |
|
37
|
|
|
38
|
### Summary of Custom Medusa Admin Authentication |
|
39
|
|
|
40
|
To authenticate admin users through a third-party provider, you need to: |
|
41
|
|
|
42
|
1. Create a [custom Authentication Module Provider](/references/auth/provider) that integrates the third-party provider. For example, you can create a provider that integrates with Okta. |
|
43
|
2. Change the authentication type in the Medusa Admin dashboard to use JWT authentication. |
|
44
|
3. Add an API route with a workflow that handles creating the admin user after they authenticate through the third-party provider. |
|
45
|
4. Add a widget on the login page that provides the option to log in through the third-party provider. |
|
46
|
|
|
47
|
 |
|
48
|
|
|
49
|
--- |
|
50
|
|
|
51
|
## Step 1: Create a Custom Authentication Module Provider |
|
52
|
|
|
53
|
The first step is to create a custom Authentication Module Provider that integrates with the third-party authentication provider you want to use. |
|
54
|
|
|
55
|
For example, if your organization uses Okta for authentication, you can create an Okta Authentication Provider that uses the Okta SDK to authenticate users. |
|
56
|
|
|
57
|
Refer to the [Create Custom Authentication Module Provider](/references/auth/provider) guide to learn how to create a custom Authentication Module Provider. |
|
58
|
|
|
59
|
### Enable Custom Authentication Provider for Admin Users |
|
60
|
|
|
61
|
By default, registered Authentication Module Providers can be used for all [actor types](../../../../commerce-modules/auth/auth-identity-and-actor-types/page.mdx). This means both admin users and customers can authenticate through the provider. |
|
62
|
|
|
63
|
It's recommended to restrict the custom authentication provider to admin users only. To do this, set the `http.authMethodsPerActor` configuration in `medusa-config.ts` to enable the custom authentication provider only for the `user` actor type: |
|
64
|
|
|
65
|
```ts title="medusa-config.ts" |
|
66
|
module.exports = defineConfig({ |
|
67
|
projectConfig: { |
|
68
|
http: { |
|
69
|
// ... |
|
70
|
authMethodsPerActor: { |
|
71
|
user: ["emailpass", "custom"], |
|
72
|
customer: ["emailpass"], |
|
73
|
}, |
|
74
|
}, |
|
75
|
// ... |
|
76
|
}, |
|
77
|
}) |
|
78
|
``` |
|
79
|
|
|
80
|
Where `emailpass` is the identifier of the Emailpass Authentication Provider, and `custom` is the identifier of your custom Authentication Module Provider. |
|
81
|
|
|
82
|
Refer to the [Authentication Module Providers](../../../../commerce-modules/auth/auth-providers/page.mdx#configure-allowed-auth-providers-of-actor-types) guide to learn more about configuring allowed authentication providers for actor types. |
|
83
|
|
|
84
|
--- |
|
85
|
|
|
86
|
## Step 2: Change Authentication Type in Medusa Admin |
|
87
|
|
|
88
|
Next, you need to change the authentication type in the Medusa Admin dashboard to use JWT authentication. |
|
89
|
|
|
90
|
To do this, set the `ADMIN_AUTH_TYPE` environment variable to `jwt` in your Medusa application's environment variables: |
|
91
|
|
|
92
|
```bash |
|
93
|
ADMIN_AUTH_TYPE=jwt |
|
94
|
``` |
|
95
|
|
|
96
|
Make sure to also create a JS SDK instance in your Medusa Admin customizations with the `auth.type` option set to `jwt`. For example, create the file `src/lib/sdk.ts` with the following content: |
|
97
|
|
|
98
|
```ts title="src/lib/sdk.ts" |
|
99
|
import Medusa from "@medusajs/js-sdk" |
|
100
|
|
|
101
|
export const sdk = new Medusa({ |
|
102
|
baseUrl: import.meta.env.VITE_BACKEND_URL || "/", |
|
103
|
debug: import.meta.env.DEV, |
|
104
|
auth: { |
|
105
|
type: "jwt", |
|
106
|
}, |
|
107
|
}) |
|
108
|
``` |
|
109
|
|
|
110
|
Refer to the [JS SDK Authentication guide](../../../../js-sdk/auth/overview/page.mdx) to learn more about configuring authentication in the Medusa JS SDK. |
|
111
|
|
|
112
|
--- |
|
113
|
|
|
114
|
## Step 3: Create User API Route |
|
115
|
|
|
116
|
Next, you need to create an [API route](!docs!/learn/fundamentals/api-routes) with a [workflow](!docs!/learn/fundamentals/workflows) that handles creating the admin user after they authenticate through the third-party provider. |
|
117
|
|
|
118
|
You will protect this API route so that only users authenticated through the custom Authentication Module Provider can access it. This prevents users from creating admin users through other authentication methods, such as email and password. |
|
119
|
|
|
120
|
### Create User Workflow |
|
121
|
|
|
122
|
First, you need to create the workflow that creates a user and associates it with the authenticated identity. |
|
123
|
|
|
124
|
Create the file `src/workflows/create-user.ts` with the following content: |
|
125
|
|
|
126
|
```ts title="src/workflows/create-user.ts" |
|
127
|
import { createWorkflow, transform, WorkflowResponse } from "@medusajs/framework/workflows-sdk" |
|
128
|
import { createUsersWorkflow, setAuthAppMetadataStep } from "@medusajs/medusa/core-flows" |
|
129
|
|
|
130
|
type WorkflowInput = { |
|
131
|
email: string |
|
132
|
auth_identity_id: string |
|
133
|
} |
|
134
|
|
|
135
|
export const createUserWorkflow = createWorkflow( |
|
136
|
"create-user", |
|
137
|
(input: WorkflowInput) => { |
|
138
|
const users = createUsersWorkflow.runAsStep({ |
|
139
|
input: { |
|
140
|
users: [ |
|
141
|
{ |
|
142
|
email: input.email, |
|
143
|
}, |
|
144
|
], |
|
145
|
}, |
|
146
|
}) |
|
147
|
|
|
148
|
const authUserInput = transform({ input, users }, ({ input, users }) => { |
|
149
|
const createdUser = users[0] |
|
150
|
|
|
151
|
return { |
|
152
|
authIdentityId: input.auth_identity_id, |
|
153
|
actorType: "user", |
|
154
|
value: createdUser.id, |
|
155
|
} |
|
156
|
}) |
|
157
|
|
|
158
|
setAuthAppMetadataStep(authUserInput) |
|
159
|
|
|
160
|
return new WorkflowResponse({ |
|
161
|
user: users[0], |
|
162
|
}) |
|
163
|
} |
|
164
|
) |
|
165
|
``` |
|
166
|
|
|
167
|
The workflow receives an object with the following properties: |
|
168
|
|
|
169
|
- `email`: The email of the user being authenticated. You can modify this based on your third-party provider's identification method. |
|
170
|
- `auth_identity_id`: The ID of the auth identity created by the custom Authentication Module Provider. Refer to the [Auth Identities](../../../../commerce-modules/auth/auth-identity-and-actor-types/page.mdx) guide to learn more. |
|
171
|
|
|
172
|
In the workflow, you: |
|
173
|
|
|
174
|
1. Create a user with the provided email using `createUsersWorkflow`. |
|
175
|
2. Associate the created user with the authenticated identity using `setAuthAppMetadataStep`. |
|
176
|
|
|
177
|
### Create User API Route |
|
178
|
|
|
179
|
Next, you need to create the API route that calls the workflow to create the user. |
|
180
|
|
|
181
|
Create the file `src/api/custom-auth/admin/users/route.ts` with the following content: |
|
182
|
|
|
183
|
<Note> |
|
184
|
|
|
185
|
As of [Medusa v2.13.0](https://github.com/medusajs/medusa/releases/tag/v2.13.0), Zod should be imported from `@medusajs/framework/zod`. |
|
186
|
|
|
187
|
</Note> |
|
188
|
|
|
189
|
```ts title="src/api/custom-auth/admin/users/route.ts" |
|
190
|
import { AuthenticatedMedusaRequest, MedusaResponse } from "@medusajs/framework" |
|
191
|
import { z } from "@medusajs/framework/zod" |
|
192
|
import { createUserWorkflow } from "../../../../workflows/create-user" |
|
193
|
|
|
194
|
export const CreateUserSchema = z.object({ |
|
195
|
email: z.string(), |
|
196
|
}) |
|
197
|
|
|
198
|
type CreateUserBody = z.infer<typeof CreateUserSchema> |
|
199
|
|
|
200
|
export const POST = async (req: AuthenticatedMedusaRequest<CreateUserBody>, res: MedusaResponse) => { |
|
201
|
const user = await createUserWorkflow(req.scope) |
|
202
|
.run({ |
|
203
|
input: { |
|
204
|
email: req.body.email, |
|
205
|
auth_identity_id: req.auth_context!.auth_identity_id!, |
|
206
|
}, |
|
207
|
}) |
|
208
|
|
|
209
|
return res.status(200).json({ user }) |
|
210
|
} |
|
211
|
``` |
|
212
|
|
|
213
|
You expose a `POST` API route at `/custom-auth/admin/users` that receives the user's email in the request body. It executes `createUserWorkflow` to create the user and returns the created user in the response. |
|
214
|
|
|
215
|
### Apply Authentication Middleware |
|
216
|
|
|
217
|
Finally, you need to apply the authentication [middleware](!docs!/learn/fundamentals/api-routes/middlewares) to the API route to ensure that only authenticated users can access it. |
|
218
|
|
|
219
|
To do this, create the file `src/api/middlewares.ts` with the following content: |
|
220
|
|
|
221
|
```ts title="src/api/middlewares.ts" |
|
222
|
import { authenticate, defineMiddlewares } from "@medusajs/framework/http" |
|
223
|
|
|
224
|
export default defineMiddlewares({ |
|
225
|
routes: [ |
|
226
|
{ |
|
227
|
matcher: "/custom-auth/admin/users", |
|
228
|
methods: ["POST"], |
|
229
|
middlewares: [ |
|
230
|
authenticate("user", "bearer", { |
|
231
|
allowUnregistered: true, |
|
232
|
}), |
|
233
|
// TODO add custom validation middleware |
|
234
|
], |
|
235
|
}, |
|
236
|
], |
|
237
|
}) |
|
238
|
``` |
|
239
|
|
|
240
|
This middleware applies the `authenticate` middleware to the `/custom-auth/admin/users` `POST` route, allowing only authenticated users to access it. By enabling the `allowUnregistered` option, users who are authenticated through the third-party provider but don't yet have an associated Medusa user can still access the route to create their user. |
|
241
|
|
|
242
|
Refer to the [Protected Routes](!docs!/learn/fundamentals/api-routes/protected-routes) guide to learn more about protecting API routes with the `authentication` middleware. |
|
243
|
|
|
244
|
### Create Custom Validation Middleware |
|
245
|
|
|
246
|
Finally, you should create a custom validation middleware that ensures only users authenticated through the custom Authentication Module Provider can access the API route. If you don't add this middleware, users authenticated through other methods, such as email and password, can also access the route and create accounts. |
|
247
|
|
|
248
|
To create the custom validation middleware, create thefile `src/api/middlewares/validate-custom-auth-provider.ts` with the following content: |
|
249
|
|
|
250
|
```ts title="src/api/middlewares/validate-custom-auth-provider.ts" |
|
251
|
import { |
|
252
|
AuthenticatedMedusaRequest, |
|
253
|
MedusaResponse, |
|
254
|
MedusaNextFunction, |
|
255
|
} from "@medusajs/framework/http" |
|
256
|
import { |
|
257
|
MedusaError, |
|
258
|
ContainerRegistrationKeys, |
|
259
|
} from "@medusajs/framework/utils" |
|
260
|
|
|
261
|
export default async function validateCustomAuthProvider( |
|
262
|
req: AuthenticatedMedusaRequest, |
|
263
|
res: MedusaResponse, |
|
264
|
next: MedusaNextFunction |
|
265
|
) { |
|
266
|
if (req.auth_context.actor_id) { |
|
267
|
throw new MedusaError( |
|
268
|
MedusaError.Types.INVALID_DATA, |
|
269
|
"User already exists" |
|
270
|
) |
|
271
|
} |
|
272
|
|
|
273
|
const query = req.scope.resolve( |
|
274
|
ContainerRegistrationKeys.QUERY |
|
275
|
) |
|
276
|
const { data: [authIdentity] } = await query.graph({ |
|
277
|
entity: "auth_identity", |
|
278
|
fields: [ |
|
279
|
"provider_identities.provider", |
|
280
|
], |
|
281
|
filters: { |
|
282
|
id: req.auth_context!.auth_identity_id!, |
|
283
|
}, |
|
284
|
}, { |
|
285
|
throwIfKeyNotFound: true, |
|
286
|
}) |
|
287
|
|
|
288
|
const isCustomAuthProvider = authIdentity.provider_identities.some((identity) => identity?.provider === "custom") |
|
289
|
|
|
290
|
if (!isCustomAuthProvider) { |
|
291
|
throw new MedusaError( |
|
292
|
MedusaError.Types.UNAUTHORIZED, |
|
293
|
"Invalid provider" |
|
294
|
) |
|
295
|
} |
|
296
|
|
|
297
|
next() |
|
298
|
} |
|
299
|
``` |
|
300
|
|
|
301
|
You create a middleware function that checks if: |
|
302
|
|
|
303
|
- The user already has an associated Medusa user. If so, you throw an error since the user shouldn't access the route. |
|
304
|
- The user's auth identity was authenticated by the custom Authentication Module Provider. You use [Query](!docs!/learn/fundamentals/query) to retrieve the user's auth identity with its provider identities, then check whether the custom provider is one of the providers. If not, you throw an unauthorized error. |
|
305
|
|
|
306
|
If both checks pass, you call the `next` function to proceed to the next middleware or route handler. |
|
307
|
|
|
308
|
Next, import this middleware at the top of the file `src/api/middlewares.ts`: |
|
309
|
|
|
310
|
```ts title="src/api/middlewares.ts" |
|
311
|
import validateCustomAuthProvider from "./middlewares/validate-custom-auth-provider" |
|
312
|
``` |
|
313
|
|
|
314
|
Then, replace the `// TODO add custom validation middleware` comment with the new middleware: |
|
315
|
|
|
316
|
```ts title="src/api/middlewares.ts" |
|
317
|
export default defineMiddlewares({ |
|
318
|
routes: [ |
|
319
|
{ |
|
320
|
matcher: "/custom-auth/admin/users", |
|
321
|
methods: ["POST"], |
|
322
|
middlewares: [ |
|
323
|
// ... |
|
324
|
validateCustomAuthProvider, |
|
325
|
], |
|
326
|
}, |
|
327
|
], |
|
328
|
}) |
|
329
|
``` |
|
330
|
|
|
331
|
Only users authenticated through the custom Authentication Module Provider can now access the `/custom-auth/admin/users` API route to create their admin user. |
|
332
|
|
|
333
|
--- |
|
334
|
|
|
335
|
## Step 4: Add a Widget on the Login Page |
|
336
|
|
|
337
|
Finally, you need to add a [widget](!docs!/learn/fundamentals/admin/widgets) to the Medusa Admin login page that provides the option to log in through the third-party provider. |
|
338
|
|
|
339
|
The widget should display a button that authenticates or redirects the user to the third-party provider. The widget should also handle the redirection back to the Medusa Admin after successful authentication. |
|
340
|
|
|
341
|
For example, the widget may look like this: |
|
342
|
|
|
343
|
```tsx title="src/admin/widgets/custom-login.tsx" |
|
344
|
import { defineWidgetConfig } from "@medusajs/admin-sdk" |
|
345
|
import { Button, toast } from "@medusajs/ui" |
|
346
|
import { decodeToken } from "react-jwt" |
|
347
|
import { useSearchParams, useNavigate } from "react-router-dom" |
|
348
|
import { useMutation } from "@tanstack/react-query" |
|
349
|
import { sdk } from "../lib/sdk" |
|
350
|
import { useEffect } from "react" |
|
351
|
|
|
352
|
// Replace with the identifier of your custom authentication provider |
|
353
|
const CUSTOM_AUTH_PROVIDER = "custom" |
|
354
|
|
|
355
|
const CustomLogin = () => { |
|
356
|
// The third-party provider redirects back with query parameters |
|
357
|
// used to validate the authentication |
|
358
|
const [searchParams] = useSearchParams() |
|
359
|
const navigate = useNavigate() |
|
360
|
const { mutateAsync, isPending } = useMutation({ |
|
361
|
mutationFn: async () => { |
|
362
|
if (isPending) { |
|
363
|
return |
|
364
|
} |
|
365
|
return await validateCallback() |
|
366
|
}, |
|
367
|
onError: (error) => { |
|
368
|
console.error("Custom authentication error:", error) |
|
369
|
}, |
|
370
|
}) |
|
371
|
|
|
372
|
const sendCallback = async () => { |
|
373
|
try { |
|
374
|
return await sdk.auth.callback( |
|
375
|
"user", |
|
376
|
CUSTOM_AUTH_PROVIDER, |
|
377
|
Object.fromEntries(searchParams) |
|
378
|
) |
|
379
|
} catch (error) { |
|
380
|
toast.error("Authentication failed") |
|
381
|
throw error |
|
382
|
} |
|
383
|
} |
|
384
|
|
|
385
|
// Validate the authentication callback |
|
386
|
const validateCallback = async () => { |
|
387
|
const token = await sendCallback() |
|
388
|
|
|
389
|
const decodedToken = decodeToken(token) as { actor_id: string, user_metadata: Record<string, unknown> } |
|
390
|
|
|
391
|
const userExists = decodedToken.actor_id !== "" |
|
392
|
|
|
393
|
if (!userExists) { |
|
394
|
// Create user |
|
395
|
await sdk.client.fetch("/custom-auth/admin/users", { |
|
396
|
method: "POST", |
|
397
|
body: { |
|
398
|
email: decodedToken.user_metadata?.email as string, |
|
399
|
}, |
|
400
|
}) |
|
401
|
|
|
402
|
const newToken = await sdk.auth.refresh() |
|
403
|
|
|
404
|
if (!newToken) { |
|
405
|
toast.error("Authentication failed") |
|
406
|
return |
|
407
|
} |
|
408
|
} |
|
409
|
|
|
410
|
// User is authenticated |
|
411
|
navigate("/orders") |
|
412
|
} |
|
413
|
|
|
414
|
// Handle custom login button click |
|
415
|
const customLogin = async () => { |
|
416
|
const result = await sdk.auth.login("user", CUSTOM_AUTH_PROVIDER, {}) |
|
417
|
|
|
418
|
if (typeof result === "object" && result.location) { |
|
419
|
// Redirect to custom provider for authentication |
|
420
|
window.location.href = result.location |
|
421
|
return |
|
422
|
} |
|
423
|
|
|
424
|
if (typeof result !== "string") { |
|
425
|
// Result failed, show an error |
|
426
|
toast.error("Authentication failed") |
|
427
|
return |
|
428
|
} |
|
429
|
|
|
430
|
navigate("/app") |
|
431
|
} |
|
432
|
|
|
433
|
// Handle the redirection back from the third-party provider |
|
434
|
useEffect(() => { |
|
435
|
// Check for provider-specific query parameters |
|
436
|
if (searchParams.get("code")) { |
|
437
|
mutateAsync() |
|
438
|
} |
|
439
|
}, [searchParams, mutateAsync]) |
|
440
|
|
|
441
|
return ( |
|
442
|
<> |
|
443
|
<hr className="bg-ui-border-base my-4" /> |
|
444
|
<Button |
|
445
|
variant="secondary" |
|
446
|
onClick={customLogin} |
|
447
|
className="w-full" |
|
448
|
> |
|
449
|
Login with Custom Provider |
|
450
|
</Button> |
|
451
|
</> |
|
452
|
) |
|
453
|
} |
|
454
|
|
|
455
|
export const config = defineWidgetConfig({ |
|
456
|
zone: "login.after", |
|
457
|
}) |
|
458
|
|
|
459
|
export default CustomLogin |
|
460
|
``` |
|
461
|
|
|
462
|
You inject the widget into the `login.after` zone. This displays it below the default email and password login form. |
|
463
|
|
|
464
|
<Note> |
|
465
|
|
|
466
|
You can't remove the default email and password login form from the Medusa Admin. You can only add additional login options through widgets. |
|
467
|
|
|
468
|
</Note> |
|
469
|
|
|
470
|
In the widget, you: |
|
471
|
|
|
472
|
1. Display a button that initiates login through the third-party provider using the `sdk.auth.login` method. |
|
473
|
- If the login method returns a `location` property, redirect the user to that location to authenticate through the third-party provider. |
|
474
|
- Otherwise, if the login method returns a token, the user is authenticated and you navigate to the Orders page of the admin dashboard. |
|
475
|
2. Add a `useEffect` hook that checks for provider-specific query parameters in the URL, such as `code`, to handle the redirection back from the third-party provider after successful authentication. |
|
476
|
3. Upon redirection back, you: |
|
477
|
- Call the `sdk.auth.callback` method to validate the authentication with the third-party provider. |
|
478
|
- If the user doesn't exist in Medusa, call the [custom API route you created](#step-3-create-user-api-route) to create the user, then refresh the authentication token. |
|
479
|
- Finally, if authentication is successful, navigate to the Orders page of the admin dashboard. |
|
480
|
|
|
481
|
--- |
|
482
|
|
|
483
|
## Test Custom Authentication in Medusa Admin |
|
484
|
|
|
485
|
To test the custom authentication in the Medusa Admin, run the following command to start your Medusa application: |
|
486
|
|
|
487
|
```bash npm2yarn |
|
488
|
npm run dev |
|
489
|
``` |
|
490
|
|
|
491
|
Then, open the Medusa Admin at `http://localhost:9000/app`, which will redirect you to the login page. |
|
492
|
|
|
493
|
On the login page, you should see the option to log in through the third-party provider you integrated. Click the button to log in through the provider and follow the authentication flow. |
|
494
|
|
|
495
|
If authentication is successful, you'll have access to the Medusa Admin dashboard. Otherwise, you can troubleshoot the issue by checking your Medusa application's logs or the browser's console for errors. |