Raw
1 ---
2 sidebar_label: "Integrate Okta"
3 tags:
4 - server
5 - tutorial
6 - auth
7 products:
8 - auth
9 ---
10
11 import { Card, Prerequisites, Details, WorkflowDiagram, H3 } from "docs-ui"
12 import { Github } from "@medusajs/icons"
13
14 export const metadata = {
15 title: `Authenticate Admin Users with Okta`,
16 }
17
18 # {metadata.title}
19
20 In this tutorial, you'll learn how to allow admin users to authenticate with Okta.
21
22 When you install a Medusa application, you get a fully-fledged commerce platform with a Framework for customization. Medusa also facilitates integrating third-party services that enrich your application with features specific to your unique business use case.
23
24 [Okta](https://www.okta.com/) is an enterprise-grade identity management service that provides secure authentication. By integrating Okta with your Medusa application, you allow users in your Okta organization to authenticate and access the Medusa Admin without needing to create separate credentials.
25
26 You can follow this tutorial whether you're new to Medusa or an advanced Medusa developer.
27
28 <Card
29 title="Full Code"
30 text="Find the full code of the guide in this repository."
31 href="https://github.com/medusajs/examples/tree/main/okta-integration"
32 icon={Github}
33 />
34
35 ---
36
37 ## Okta Authentication Flow Summary
38
39 Before you implement the Okta integration, this section provides a high-level overview of how the Okta authentication flow works in Medusa.
40
41 ![Diagram of the authentication flow between the Medusa Admin, Medusa server, and Okta](https://res.cloudinary.com/dza7lstvk/image/upload/v1764663019/Medusa%20Resources/okta-auth-overview_ngbx80.jpg)
42
43 The authentication flow consists of the following steps:
44
45 1. An admin user clicks the "Login with Okta" button on the Medusa Admin login page. This action triggers a request to the Medusa server to initiate the authentication process.
46 2. The Medusa server generates an authorization URL with the necessary parameters.
47 3. Medusa Admin redirects the user to the Okta authorization URL.
48 4. The user authenticates with Okta using their Okta credentials.
49 5. After successful authentication, Okta redirects the user back to the Medusa Admin with an authorization code.
50 6. The Medusa Admin validates the callback by sending a request to the Medusa server with the authorization code.
51 7. The Medusa server exchanges the authorization code for tokens and retrieves the user's information from Okta.
52 8. The Medusa server creates or updates the user's auth identity in Medusa and returns the authentication response to the Medusa Admin.
53 9. If this is a new user, the Medusa Admin sends a request to create a new admin user in Medusa.
54 10. The Medusa Admin refreshes the user's token and logs in the user.
55
56 <Note>
57
58 Refer to the [Auth Route Flows](../../../commerce-modules/auth/authentication-route/page.mdx) guide to learn more about the authentication flows in Medusa.
59
60 </Note>
61
62 Medusa's [Auth Module](../../../commerce-modules/auth/page.mdx) provides the interface to authenticate users. It delegates the actual authentication logic to the underlying Auth Module Provider, which in this case is Okta.
63
64 So, to support the above flow, you'll create:
65
66 1. An Okta Auth Module Provider that implements the logic to authenticate users with Okta and validate the callback.
67 2. An admin user creation flow in the Medusa Admin that creates a new admin user in Medusa after successful authentication with Okta.
68 3. An admin widget that adds the "Login with Okta" button to the Medusa Admin login page and handles the authentication flow from the frontend.
69
70 ---
71
72 ## Step 1: Install a Medusa Application
73
74 <Prerequisites items={[
75 {
76 text: "Node.js v20.19.0+ or v22.12.0+",
77 link: "https://nodejs.org/en/download"
78 },
79 {
80 text: "Git CLI tool",
81 link: "https://git-scm.com/downloads"
82 },
83 {
84 text: "PostgreSQL",
85 link: "https://www.postgresql.org/download/"
86 }
87 ]} />
88
89 Start by installing the Medusa application on your machine with the following command:
90
91 ```bash
92 npx create-medusa-app@latest
93 ```
94
95 First, you'll be asked for the project's name. Then, when prompted about installing the [Next.js Starter Storefront](../../../nextjs-starter/page.mdx), choose "Yes."
96
97 Afterwards, the installation process will start, which will install the Medusa application as a monorepository in a directory with your project's name. The backend is installed in the `apps/backend` directory, and the Next.js Starter Storefront is installed in the `apps/storefront` directory.
98
99 Once the installation finishes successfully, the Medusa Admin dashboard will open with a form to create a new user. Enter the user's credentials and submit the form. Afterwards, you can log in with the new user and explore the dashboard.
100
101 <Note title="Ran into Errors?">
102
103 Check out the [troubleshooting guides](../../../troubleshooting/create-medusa-app-errors/page.mdx) for help.
104
105 </Note>
106
107 <Note>
108
109 In this guide, all file paths of backend customizations are relative to the `apps/backend` directory of your Medusa project.
110
111 </Note>
112
113 ---
114
115 ## Step 2: Create Okta Auth Module Provider
116
117 In this step, you'll integrate Okta as an Auth Module Provider. Later, you'll allow admin users to authenticate with Okta.
118
119 <Note>
120
121 Learn more about modules in the [Modules](!docs!/learn/fundamentals/modules) documentation.
122
123 </Note>
124
125 ### a. Create Module Directory
126
127 A module is created under the `src/modules` directory of your Medusa application. So, create the directory `src/modules/okta`.
128
129 ### b. Create Service
130
131 A module has a service that contains its logic. For Auth Module Providers, the service implements the logic to authenticate users.
132
133 To create the service for the Okta Auth Module Provider, create the file `src/modules/okta/service.ts` with the following content:
134
135 export const serviceHighlights = [
136 ["10", "Options", "The options required to configure the Okta Auth Module Provider."],
137 ["17", "AbstractAuthModuleProvider", "Auth Module Provider services must extend this class."],
138 ["18", "DISPLAY_NAME", "The display name of the Okta Auth Module Provider."],
139 ["19", "identifier", "A unique identifier used to register the Okta Auth Module Provider in Medusa."],
140 ]
141
142 ```ts title="src/modules/okta/service.ts" highlights={serviceHighlights}
143 import { AbstractAuthModuleProvider } from "@medusajs/framework/utils"
144 import {
145 Logger,
146 } from "@medusajs/framework/types"
147
148 type InjectedDependencies = {
149 logger: Logger
150 }
151
152 type Options = {
153 oktaDomain: string
154 clientId: string
155 clientSecret: string
156 redirectUri: string
157 }
158
159 class OktaAuthProviderService extends AbstractAuthModuleProvider {
160 static DISPLAY_NAME = "Okta"
161 static identifier = "okta"
162
163 // Scopes requested from Okta during authentication
164 private static readonly SCOPES = ["openid", "profile", "email"]
165
166 protected logger_: Logger
167 protected options_: Options
168
169 constructor(
170 { logger }: InjectedDependencies,
171 options: Options
172 ) {
173 // @ts-ignore
174 super(...arguments)
175
176 this.logger_ = logger
177 this.options_ = options
178 }
179
180 // TODO add methods
181 }
182
183 export default OktaAuthProviderService
184 ```
185
186 An Auth Module Provider's service must extend the `AbstractAuthModuleProvider` class. You'll implement its abstract methods in a bit.
187
188 #### Static Properties
189
190 The service must also define the following static properties:
191
192 1. `DISPLAY_NAME`: The display name of the Auth Module Provider.
193 2. `identifier`: The unique identifier of the Auth Module Provider. This identifier is used to form the ID of the Auth Module Provider when registering it in Medusa.
194
195 #### Constructor
196
197 The constructor receives the following parameters:
198
199 1. Dependencies resolved from the [module's container](!docs!/learn/fundamentals/modules/container) that contains Framework resources available to the module.
200 2. Options passed to the Auth Module Provider. You expect the following options:
201 - `oktaDomain`: The Okta domain of your organization.
202 - `clientId`: The Client ID of your Okta application.
203 - `clientSecret`: The Client Secret of your Okta application.
204 - `redirectUri`: The Redirect URI of your Okta application.
205
206 ### c. Implement Service Methods
207
208 In this section, you'll implement the methods required by the `AbstractAuthModuleProvider` class. You can refer to the [How to Create an Auth Module Provider](/references/auth/provider) guide for more details about these methods.
209
210 #### validateOptions
211
212 The [validateOptions](/references/auth/provider#validateOptions) method ensures that the module received the required options. Otherwise, it throws an error.
213
214 Add the `validateOptions` method to the `OktaAuthProviderService` class:
215
216 ```ts title="src/modules/okta/service.ts"
217 import { MedusaError } from "@medusajs/framework/utils"
218
219 class OktaAuthProviderService extends AbstractAuthModuleProvider {
220 // ...
221 static validateOptions(options: Record<any, any>): void | never {
222 if (!options.oktaDomain) {
223 throw new MedusaError(
224 MedusaError.Types.INVALID_DATA,
225 "Okta auth provider requires oktaDomain option"
226 )
227 }
228
229 if (!options.clientId) {
230 throw new MedusaError(
231 MedusaError.Types.INVALID_DATA,
232 "Okta auth provider requires clientId option"
233 )
234 }
235
236 if (!options.clientSecret) {
237 throw new MedusaError(
238 MedusaError.Types.INVALID_DATA,
239 "Okta auth provider requires clientSecret option"
240 )
241 }
242
243 if (!options.redirectUri) {
244 throw new MedusaError(
245 MedusaError.Types.INVALID_DATA,
246 "Okta auth provider requires redirectUri option"
247 )
248 }
249 }
250 }
251 ```
252
253 The method receives the options passed to the module as a parameter.
254
255 It throws an error if any of the options are missing.
256
257 #### generateState
258
259 The `generateState` method is not required by the `AbstractAuthModuleProvider` class, but it's necessary to generate a unique state parameter that Okta requires during authentication.
260
261 Add the `generateState` method to the `OktaAuthProviderService` class:
262
263 ```ts title="src/modules/okta/service.ts"
264 class OktaAuthProviderService extends AbstractAuthModuleProvider {
265 // ...
266 private generateState(): string {
267 return (
268 Math.random().toString(36).substring(2, 15) +
269 Math.random().toString(36).substring(2, 15)
270 )
271 }
272 }
273 ```
274
275 In the method, you generate a random string that will be used as the state parameter during authentication. You'll use this method in other methods to generate the state parameter.
276
277 #### authenticate
278
279 The [authenticate](/references/auth/provider#authenticate) method is called when a user tries to authenticate with the Okta Auth Module Provider. It returns the URL to redirect the user to Okta for authentication.
280
281 Add the `authenticate` method to the `OktaAuthProviderService` class:
282
283 ```ts title="src/modules/okta/service.ts"
284 import {
285 AuthIdentityProviderService,
286 AuthenticationInput,
287 AuthenticationResponse,
288 } from "@medusajs/framework/types"
289
290 class OktaAuthProviderService extends AbstractAuthModuleProvider {
291 // ...
292 async authenticate(
293 data: AuthenticationInput,
294 authIdentityProviderService: AuthIdentityProviderService
295 ): Promise<AuthenticationResponse> {
296 const { body } = data
297
298 // If callback_url is provided, use it;
299 // otherwise use the default redirectUri
300 const callbackUrl = body?.callback_url || this.options_.redirectUri
301
302 // Generate state parameter for CSRF protection
303 const state = this.generateState()
304
305 await authIdentityProviderService.setState(state, {
306 callback_url: callbackUrl,
307 })
308
309 const params = new URLSearchParams({
310 client_id: this.options_.clientId,
311 response_type: "code",
312 scope: OktaAuthProviderService.SCOPES.join(" "),
313 redirect_uri: callbackUrl,
314 state: state,
315 })
316
317 const authUrl = `${this.options_.oktaDomain}/oauth2/v1/authorize?${
318 params.toString()
319 }`
320
321 // Return the authorization URL for the frontend to redirect to
322 return {
323 success: true,
324 location: authUrl,
325 }
326 }
327 }
328 ```
329
330 The method receives the following parameters:
331
332 1. `data`: The input data for the authentication request, which includes the request body, headers, and other useful information.
333 2. `authIdentityProviderService`: The service to manage [auth identities](../../../commerce-modules/auth/auth-identity-and-actor-types/page.mdx).
334
335 <Note>
336
337 Refer to the [Auth Module Provider guide](/references/auth/provider#authenticate) for a detailed breakdown of the parameters.
338
339 </Note>
340
341 In the method, you:
342
343 1. Extract the `callback_url` from the input data. If it's not provided, you use the `redirectUri` option passed to the module.
344 2. Generate a state query parameter using the `generateState` method.
345 3. Store the state parameter along with the callback URL in the cache using the `setState` method of the `authIdentityProviderService`. This is useful for validating the state parameter later during the callback.
346 4. Create a URL with the required parameters to redirect the user to Okta for authentication.
347 5. Return the authorization URL in the response.
348
349 #### validateCallback
350
351 The [validateCallback](/references/auth/provider#validateCallback) method is called when Okta redirects the user back to your application after authentication. It validates that the user authenticated successfully, creates the user's [auth identity](../../../commerce-modules/auth/auth-identity-and-actor-types/page.mdx), and returns the authentication response.
352
353 Add the `validateCallback` method to the `OktaAuthProviderService` class:
354
355 ```ts title="src/modules/okta/service.ts"
356 class OktaAuthProviderService extends AbstractAuthModuleProvider {
357 // ...
358 async validateCallback(
359 data: AuthenticationInput,
360 authIdentityProviderService: AuthIdentityProviderService
361 ): Promise<AuthenticationResponse> {
362 const { query } = data
363
364 const code = query?.code as string
365 const stateKey = query?.state as string
366
367 if (!code) {
368 return {
369 success: false,
370 error: "Authorization code is missing",
371 }
372 }
373
374 const state = await authIdentityProviderService.getState(stateKey)
375
376 if (!state) {
377 return {
378 success: false,
379 error: "No state provided, or session expired",
380 }
381 }
382
383 const callbackUrl = state.callback_url as string
384
385 try {
386 // Exchange the authorization code for tokens
387 const tokenUrl = `${this.options_.oktaDomain}/oauth2/v1/token`
388 const params = new URLSearchParams({
389 grant_type: "authorization_code",
390 code: code,
391 redirect_uri: callbackUrl,
392 client_id: this.options_.clientId,
393 client_secret: this.options_.clientSecret,
394 })
395
396 const tokenResponse = await fetch(tokenUrl, {
397 method: "POST",
398 headers: {
399 "Content-Type": "application/x-www-form-urlencoded",
400 Accept: "application/json",
401 },
402 body: params.toString(),
403 })
404
405 if (!tokenResponse.ok) {
406 const errorText = await tokenResponse.text()
407 throw new MedusaError(
408 MedusaError.Types.INVALID_DATA,
409 `Failed to exchange code for tokens: ${errorText}`
410 )
411 }
412
413 const tokenData = await tokenResponse.json()
414 const accessToken = tokenData.access_token as string
415 const refreshToken = tokenData.refresh_token as string | undefined
416 const idToken = tokenData.id_token as string | undefined
417 const expiresIn = tokenData.expires_in as number
418
419 // Get user info from Okta using the access token
420 const userInfoUrl = `${this.options_.oktaDomain}/oauth2/v1/userinfo`
421 const userInfoResponse = await fetch(userInfoUrl, {
422 method: "GET",
423 headers: {
424 Authorization: `Bearer ${accessToken}`,
425 Accept: "application/json",
426 },
427 })
428
429 if (!userInfoResponse.ok) {
430 const errorText = await userInfoResponse.text()
431 throw new MedusaError(
432 MedusaError.Types.INVALID_DATA,
433 `Failed to get user info: ${errorText}`
434 )
435 }
436
437 const userInfo = await userInfoResponse.json()
438
439 // Extract user identifier (email or sub)
440 const entityId = userInfo.email || userInfo.sub
441
442 if (!entityId) {
443 return {
444 success: false,
445 error: "Unable to retrieve user identifier from Okta",
446 }
447 }
448
449 // TODO create or update auth identity
450 } catch (error) {
451 this.logger_.error("Okta authentication error:", error)
452 return {
453 success: false,
454 error: error.message || "Failed to authenticate with Okta",
455 }
456 }
457 }
458 }
459 ```
460
461 The method receives the following parameters:
462
463 1. `data`: The input data for the authentication request, which includes the request body, headers, and other useful information.
464 2. `authIdentityProviderService`: The service to manage [auth identities](../../../commerce-modules/auth/auth-identity-and-actor-types/page.mdx).
465
466 <Note>
467
468 Refer to the [Auth Module Provider guide](/references/auth/provider#validateCallback) for a detailed breakdown of the parameters.
469
470 </Note>
471
472 In the method, so far, you:
473
474 1. Extract the authorization code and state parameter from the input data.
475 2. Retrieve the stored state using the `getState` method of the `authIdentityProviderService`. If the state is not found, return an error response.
476 3. Extract the `callback_url` from the retrieved state.
477 4. Exchange the authorization code for tokens by making a `POST` request to the Okta token endpoint.
478 5. If the token exchange is successful, you retrieve the token details from the response, including the access token, refresh token, ID token, and expiration time.
479 6. Use the access token to fetch the user's information from Okta.
480
481 Next, you'll create or update the user's auth identity in Medusa.
482
483 Replace the `// TODO create or update auth identity` comment with the following:
484
485 ```ts title="src/modules/okta/service.ts"
486 let authIdentity
487 try {
488 // Try to retrieve by entity_id
489 authIdentity = await authIdentityProviderService.retrieve({
490 entity_id: entityId,
491 })
492
493 // Update existing auth identity with latest user metadata
494 authIdentity = await authIdentityProviderService.update(entityId, {
495 user_metadata: {
496 email: userInfo.email,
497 name: userInfo.name,
498 given_name: userInfo.given_name,
499 family_name: userInfo.family_name,
500 picture: userInfo.picture,
501 updated_at: new Date().toISOString(),
502 },
503 provider_metadata: {
504 okta_sub: userInfo.sub,
505 access_token: accessToken,
506 refresh_token: refreshToken,
507 id_token: idToken,
508 expires_at: Date.now() + expiresIn * 1000,
509 },
510 })
511 } catch (error) {
512 if (error.type === MedusaError.Types.NOT_FOUND) {
513 // Auth identity doesn't exist, create it
514 authIdentity = await authIdentityProviderService.create({
515 entity_id: entityId,
516 provider_metadata: {
517 okta_sub: userInfo.sub,
518 access_token: accessToken,
519 refresh_token: refreshToken,
520 id_token: idToken,
521 expires_at: Date.now() + expiresIn * 1000,
522 },
523 user_metadata: {
524 email: userInfo.email,
525 name: userInfo.name,
526 given_name: userInfo.given_name,
527 family_name: userInfo.family_name,
528 picture: userInfo.picture,
529 },
530 })
531 } else {
532 // Re-throw if it's not a NOT_FOUND error
533 throw error
534 }
535 }
536
537 return {
538 success: true,
539 authIdentity,
540 }
541 ```
542
543 In this part of the method, you:
544
545 1. Try to retrieve the user's auth identity using the `entity_id`.
546 - If the user already has an auth identity, it means the user was previously authenticated. You update the existing auth identity with the latest user metadata and provider metadata.
547 - Otherwise, you create a new auth identity with the user metadata and provider metadata.
548 2. Return a successful response with the auth identity.
549
550 ### d. Export Module Definition
551
552 You've now finished implementing the necessary methods for the Okta Auth Module Provider.
553
554 The final piece to a module is its definition, which you export in an `index.ts` file at the module's root directory. This definition tells Medusa the module's details, including its service.
555
556 To create the module's definition, create the file `src/modules/okta/index.ts` with the following content:
557
558 ```ts title="src/modules/okta/index.ts"
559 import OktaAuthProviderService from "./service"
560 import { ModuleProvider, Modules } from "@medusajs/framework/utils"
561
562 export default ModuleProvider(Modules.AUTH, {
563 services: [OktaAuthProviderService],
564 })
565 ```
566
567 You use `ModuleProvider` from the Modules SDK to create the module provider's definition. It accepts two parameters:
568
569 1. The name of the module that this provider belongs to, which is `Modules.AUTH` in this case.
570 2. An object with a required property `services` indicating the Module Provider's services.
571
572 ### e. Add Module Provider to Medusa's Configurations
573
574 Once you finish building the module, add it to Medusa's configurations to start using it.
575
576 In `medusa-config.ts`, add a `modules` property to the configurations:
577
578 ```ts title="medusa-config.ts"
579 import {
580 Modules,
581 ContainerRegistrationKeys,
582 } from "@medusajs/framework/utils"
583
584 module.exports = defineConfig({
585 // ...
586 modules: [
587 // ...
588 {
589 resolve: "@medusajs/medusa/auth",
590 dependencies: [
591 Modules.CACHE,
592 ContainerRegistrationKeys.LOGGER,
593 ],
594 options: {
595 providers: [
596 // Default email/password provider
597 {
598 resolve: "@medusajs/medusa/auth-emailpass",
599 id: "emailpass",
600 },
601 // other providers...
602 // Okta auth provider
603 {
604 resolve: "./src/modules/okta",
605 id: "okta",
606 options: {
607 oktaDomain: process.env.OKTA_DOMAIN!,
608 clientId: process.env.OKTA_CLIENT_ID!,
609 clientSecret: process.env.OKTA_CLIENT_SECRET!,
610 redirectUri: process.env.OKTA_REDIRECT_URI!,
611 },
612 },
613 ],
614 },
615 },
616 ],
617 })
618 ```
619
620 To pass a Module Provider to the Auth Module, you add the `modules` property to the Medusa configuration and pass the Auth Module in its value.
621
622 The Auth Module accepts a `providers` option, which is an array of Auth Module Providers to register.
623
624 To register the Okta Auth Module Provider, you add an object to the `providers` array with the following properties:
625
626 - `resolve`: The NPM package or path to the module provider. In this case, it's the path to the `src/modules/okta` directory.
627 - `id`: The ID of the module provider. The Auth Module Provider is then registered with the ID `au_{identifier}_{id}`, where:
628 - `{identifier}`: The identifier static property defined in the Module Provider's service, which is `okta` in this case.
629 - `{id}`: The ID set in this configuration, which is also `okta` in this case.
630 - `options`: The options to pass to the module provider. These are the options you defined in the `Options` type of the module provider's service.
631
632 ### f. Set Up Environment Variables
633
634 Next, you'll set up the environment variables whose values you passed to the Okta Auth Module Provider.
635
636 <Prerequisites
637 items={[
638 {
639 text: "Okta Account. You can create a free developer account as well.",
640 link: "https://developer.okta.com/signup/"
641 }
642 ]}
643 />
644
645 #### Create Okta Application
646
647 To authenticate users with Okta, you need to create an Okta application in your Okta organization.
648
649 To create an Okta application:
650
651 1. [Log in to your Okta organization](https://developer.okta.com/login/).
652 2. Go to Applications -> Applications.
653 3. Click on "Create App Integration."
654 4. In the pop up, select "OIDC - OpenID Connect" as the Sign-in method and "Web Application" as the Application type. Click "Next."
655 5. In the creation form, enter the following details:
656 - **App integration name**: A name for your application. For example, "Medusa".
657 - **Sign-in redirect URIs**: The redirect URI where Okta will redirect users after authentication. For example, set it to `http://localhost:9000/app/login`. You can replace the localhost URL with your Medusa Admin's URL if it's different.
658 - **Sign-out redirect URIs**: The redirect URI where Okta will redirect users after signing out. For example, set it to `http://localhost:9000/app/login`.
659 - **Controlled access**: Optionally, choose "Allow everyone in your organization to access" to allow all users in your Okta organization to authenticate. You can alternatively restrict access to specific groups.
660 6. Click "Save" to create the application.
661
662 ![Okta application creation form](https://res.cloudinary.com/dza7lstvk/image/upload/v1764672257/Medusa%20Resources/CleanShot_2025-12-02_at_12.44.00_2x_nygahc.png)
663
664 After creating the application, you'll be redirected to the application's settings page. Copy the client ID and client secret from this page, as you'll need them for the environment variables.
665
666 ![Okta application settings page](https://res.cloudinary.com/dza7lstvk/image/upload/v1764672504/Medusa%20Resources/CleanShot_2025-12-02_at_12.48.03_2x_imaqs4.png)
667
668 #### Set Environment Variables
669
670 Next, set the following environment variables in your Medusa application's `.env` file:
671
672 ```shell title=".env"
673 OKTA_DOMAIN=https://integrator...
674 OKTA_CLIENT_ID=your_okta_client_id
675 OKTA_CLIENT_SECRET=your_okta_client_secret
676 OKTA_REDIRECT_URI=http://localhost:9000/app/login
677 ```
678
679 Where:
680
681 - `OKTA_DOMAIN`: The Okta domain of your organization. You can find it by going to Security -> API -> Authorization Servers in your Okta dashboard. It's the URL before `/oauth2/default`.
682
683 ![Okta domain in Authorization Servers page](https://res.cloudinary.com/dza7lstvk/image/upload/v1764672662/Medusa%20Resources/CleanShot_2025-12-02_at_12.50.40_2x_exdpgj.png)
684
685 - `OKTA_CLIENT_ID`: The Client ID of your Okta application.
686 - `OKTA_CLIENT_SECRET`: The Client Secret of your Okta application.
687 - `OKTA_REDIRECT_URI`: The URL where Okta will redirect users after authentication. It's the same URL you set in the application's Sign-in redirect URIs.
688
689 The Okta integration is now ready. You'll test it out once you set up the authentication flow in the Medusa Admin.
690
691 ---
692
693 ## Step 3: Create Admin User API Route
694
695 In this step, you'll create an API route that creates an admin user for a newly authenticated Okta user. This also requires creating a workflow that the API route executes to create the user.
696
697 <Note title="Important" type="warning">
698
699 This API route is secured by Okta authentication since only authenticated users in your Okta organization can access it. However, for other authentication providers, proceed with caution if the authentication provider allows public sign-ups, such as social login with Google. In those scenarios, anyone with a Google account could create an admin user in your Medusa application.
700
701 </Note>
702
703 ### a. Create User Workflow
704
705 A [workflow](!docs!/learn/fundamentals/workflows) is a series of actions, called steps, that complete a task with rollback and retry mechanisms. In Medusa, you build commerce features in workflows, then execute them in other customizations, such as subscribers, scheduled jobs, and API routes.
706
707 The workflow to create a user has the following steps:
708
709 <WorkflowDiagram
710 workflow={{
711 name: "createUserWorkflow",
712 steps: [
713 {
714 type: "workflow",
715 name: "createUsersWorkflow",
716 description: "Create an admin user in Medusa.",
717 link: "/references/medusa-workflows/createUsersWorkflow",
718 depth: 1
719 },
720 {
721 type: "step",
722 name: "setAuthAppMetadataStep",
723 description: "Associate the auth identity with the newly created user.",
724 link: "/references/medusa-workflows/steps/setAuthAppMetadataStep",
725 depth: 2
726 }
727 ]
728 }}
729 />
730
731 Medusa provides the workflow and step out-of-the-box, so you can create the workflow.
732
733 Create the file `src/workflows/create-user.ts` with the following content:
734
735 ```ts title="src/workflows/create-user.ts"
736 import { createWorkflow, transform, WorkflowResponse } from "@medusajs/framework/workflows-sdk"
737 import { createUsersWorkflow, setAuthAppMetadataStep } from "@medusajs/medusa/core-flows"
738
739 type WorkflowInput = {
740 email: string
741 auth_identity_id: string
742 first_name?: string
743 last_name?: string
744 }
745
746 export const createUserWorkflow = createWorkflow(
747 "create-user",
748 (input: WorkflowInput) => {
749 const users = createUsersWorkflow.runAsStep({
750 input: {
751 users: [
752 {
753 email: input.email,
754 first_name: input.first_name,
755 last_name: input.last_name,
756 },
757 ],
758 },
759 })
760
761 const authUserInput = transform({ input, users }, ({ input, users }) => {
762 const createdUser = users[0]
763
764 return {
765 authIdentityId: input.auth_identity_id,
766 actorType: "user",
767 value: createdUser.id,
768 }
769 })
770
771 setAuthAppMetadataStep(authUserInput)
772
773 return new WorkflowResponse({
774 user: users[0],
775 })
776 }
777 )
778 ```
779
780 You create a workflow using `createWorkflow` from the Workflows SDK. It accepts the workflow's unique name as a first parameter.
781
782 `createWorkflow` accepts as a second parameter a constructor function, which is the user's details with the ID of the auth identity that Okta created during authentication.
783
784 In the workflow's constructor function, you:
785
786 1. Create the user using the [createUsersWorkflow](/references/medusa-workflows/createUsersWorkflow).
787 2. Prepare the input for the `setAuthAppMetadataStep` step using [transform](!docs!//learn/fundamentals/workflows/variable-manipulation). You update the auth identity to associate it with the created user.
788 3. Associate the created user with the auth identity (created by Okta) using the [setAuthAppMetadataStep](/references/medusa-workflows/steps/setAuthAppMetadataStep).
789
790 Finally, you return an instance of `WorkflowResponse` with the created user.
791
792 <Note>
793
794 A workflow has some constraints that require you to define and manipulate variables using `transform`. Refer to the [Data Manipulation](!docs!/learn/fundamentals/workflows/variable-manipulation) guide to learn more.
795
796 </Note>
797
798 ### b. Create Admin User API Route
799
800 Next, you'll create the API route that executes the `createUserWorkflow` to create an admin user for a newly authenticated Okta user.
801
802 An API route is created in a `route.ts` file under a sub-directory of the `src/api` directory. The path of the API route is the file's path relative to `src/api`.
803
804 So, create the file `src/api/okta/users/route.ts` with the following content:
805
806 <Note>
807
808 As of [Medusa v2.13.0](https://github.com/medusajs/medusa/releases/tag/v2.13.0), Zod should be imported from `@medusajs/framework/zod`.
809
810 </Note>
811
812 ```ts title="src/api/okta/users/route.ts"
813 import { AuthenticatedMedusaRequest, MedusaResponse } from "@medusajs/framework"
814 import { z } from "@medusajs/framework/zod"
815 import { createUserWorkflow } from "../../../workflows/create-user"
816
817 export const CreateUserSchema = z.object({
818 email: z.string(),
819 first_name: z.string().optional(),
820 last_name: z.string().optional(),
821 })
822
823 type CreateUserBody = z.infer<typeof CreateUserSchema>
824
825 export const POST = async (
826 req: AuthenticatedMedusaRequest<CreateUserBody>,
827 res: MedusaResponse
828 ) => {
829 const user = await createUserWorkflow(req.scope)
830 .run({
831 input: {
832 email: req.validatedBody.email,
833 auth_identity_id: req.auth_context!.auth_identity_id!,
834 first_name: req.validatedBody.first_name,
835 last_name: req.validatedBody.last_name,
836 },
837 })
838
839 return res.status(200).json({ user })
840 }
841 ```
842
843 You export a [Zod](https://zod.dev/) schema that you'll use to validate incoming requests to the API route.
844
845 You also export a `POST` handler function which exposes a `POST` API route at `/okta/users`.
846
847 In the API route, you execute the `createUserWorkflow` by invoking it, passing it the [Medusa container](!docs!/learn/fundamentals/medusa-container), then calling its `run` method with the workflow's input.
848
849 Finally, you return the created user in the response.
850
851 ### c. Apply Authentication and Validation Middlewares
852
853 Next, you'll apply middlewares to the API route to ensure that only authenticated users can access it and that the incoming requests are valid.
854
855 To apply middlewares to an API route, create the file `src/api/middlewares.ts` with the following content:
856
857 ```ts title="src/api/middlewares.ts"
858 import { authenticate, defineMiddlewares, validateAndTransformBody } from "@medusajs/framework/http"
859 import { CreateUserSchema } from "./okta/users/route"
860
861 export default defineMiddlewares({
862 routes: [
863 {
864 matcher: "/okta/users",
865 methods: ["POST"],
866 middlewares: [
867 authenticate("user", "bearer", {
868 allowUnregistered: true,
869 }),
870 validateAndTransformBody(CreateUserSchema),
871 // TODO add Okta validation middleware
872 ],
873 },
874 ],
875 })
876 ```
877
878 You use `defineMiddlewares` to apply middlewares to API routes. You apply two middlewares to the `/okta/users` route:
879
880 1. [authenticate](!docs!/learn/fundamentals/api-routes/protected-routes): This middleware ensures only admin users with an authentication token can access the route. You set the `allowUnregistered` option to `true` to allow users who don't have an associated Medusa user yet (new Okta users) to access the route.
881 2. [validateAndTransformBody](!docs!/learn/fundamentals/api-routes/validation): This middleware validates and transforms the request body using the `CreateUserSchema` schema you defined earlier.
882
883 You'll add another middleware to validate that the user was authenticated with Okta in the next section.
884
885 ### d. Add Okta Validation Middleware
886
887 To ensure that only authenticated Okta users can access the user creation API route, you'll add a [middleware](!docs!/learn/fundamentals/api-routes/middlewares) that validates that the user was authenticated with Okta.
888
889 To create the middleware, create the file `src/api/middlewares/validate-okta-provider.ts` with the following content:
890
891 ```ts title="src/api/middlewares/validate-okta-provider.ts"
892 import {
893 AuthenticatedMedusaRequest,
894 MedusaResponse,
895 MedusaNextFunction,
896 } from "@medusajs/framework/http"
897 import {
898 MedusaError,
899 ContainerRegistrationKeys,
900 } from "@medusajs/framework/utils"
901
902 export default async function validateOktaProvider(
903 req: AuthenticatedMedusaRequest,
904 res: MedusaResponse,
905 next: MedusaNextFunction
906 ) {
907 if (req.auth_context.actor_id) {
908 throw new MedusaError(
909 MedusaError.Types.INVALID_DATA,
910 "User already exists"
911 )
912 }
913
914 const query = req.scope.resolve(
915 ContainerRegistrationKeys.QUERY
916 )
917 const { data: [authIdentity] } = await query.graph({
918 entity: "auth_identity",
919 fields: [
920 "provider_identities.provider",
921 ],
922 filters: {
923 id: req.auth_context!.auth_identity_id!,
924 },
925 }, {
926 throwIfKeyNotFound: true,
927 })
928
929 const isOkta = authIdentity.provider_identities.some((identity) => identity?.provider === "okta")
930
931 if (!isOkta) {
932 throw new MedusaError(
933 MedusaError.Types.UNAUTHORIZED,
934 "Invalid provider"
935 )
936 }
937
938 next()
939 }
940 ```
941
942 You create a middleware function that checks if:
943
944 - The user already has an associated Medusa user. If so, you throw an error since the user shouldn't access the route.
945 - The user's auth identity was authenticated by Okta. You use [Query](!docs!/learn/fundamentals/query) to retrieve the user's auth identity with its provider identities, then check whether Okta is one of the providers. If not, you throw an unauthorized error.
946
947 If both checks pass, you call the `next` function to proceed to the next middleware or route handler.
948
949 Finally, in `src/api/middlewares.ts`, add the following import at the top of the file:
950
951 ```ts title="src/api/middlewares.ts"
952 import validateOktaProvider from "./middlewares/validate-okta-provider"
953 ```
954
955 Then, replace the `// TODO add Okta validation middleware` comment with the new middleware:
956
957 ```ts title="src/api/middlewares.ts" highlights={[["8"]]}
958 export default defineMiddlewares({
959 routes: [
960 {
961 matcher: "/okta/users",
962 methods: ["POST"],
963 middlewares: [
964 // ...
965 validateOktaProvider,
966 ],
967 },
968 ],
969 })
970 ```
971
972 The `validateOktaProvider` middleware will now run before the API route handler, ensuring only authenticated Okta users can create an admin user.
973
974 You'll test out this API route after you implement the Okta authentication flow in the Medusa Admin.
975
976 ---
977
978 ## Step 4: Add Login with Okta in Medusa Admin
979
980 In this step, you'll customize the Medusa Admin login form to add a "Login with Okta" button that initiates the Okta authentication flow.
981
982 The Medusa Admin is customizable, allowing you to either inject custom components into existing pages or create new pages.
983
984 You'll inject a custom component into the existing login page to add the "Login with Okta" button.
985
986 <Note>
987
988 While you can inject custom components into the login page, you can't remove the existing email/password login form. Therefore, both login methods will be available on the login page.
989
990 </Note>
991
992 ### a. Set Admin Authentication Type
993
994 By default, the Medusa Admin uses session-based authentication. However, to support third-party authentication providers like Okta, you need to switch to token-based authentication.
995
996 To set the admin authentication type, add the following environment variable to your Medusa application's `.env` file:
997
998 ```shell title=".env"
999 ADMIN_AUTH_TYPE=jwt
1000 ```
1001
1002 This sets the admin authentication type to JWT (JSON Web Token), which supports third-party authentication providers.
1003
1004 ### b. Configure JS SDK
1005
1006 Next, you'll configure Medusa's [JS SDK](../../../js-sdk/page.mdx). It allows you to send requests to the Medusa server from any client application, including your Medusa Admin customizations.
1007
1008 The JS SDK is installed by default in your Medusa application. To configure it, create the file `src/admin/lib/sdk.ts` with the following content:
1009
1010 ```ts title="src/admin/lib/sdk.ts"
1011 import Medusa from "@medusajs/js-sdk"
1012
1013 export const sdk = new Medusa({
1014 baseUrl: import.meta.env.VITE_BACKEND_URL || "/",
1015 debug: import.meta.env.DEV,
1016 auth: {
1017 type: "jwt",
1018 },
1019 })
1020 ```
1021
1022 You create an instance of the JS SDK using the `Medusa` class from the JS SDK. You pass it an object having the following properties:
1023
1024 - `baseUrl`: The base URL of the Medusa server.
1025 - `debug`: A boolean indicating whether to log debug information into the console.
1026 - `auth`: An object specifying the authentication type. When using the JS SDK for admin customizations, you use the `jwt` authentication type.
1027
1028 ### c. Add Okta Icon Component
1029
1030 Next, you'll create a React component that renders the Okta logo. You'll use this component in the "Login with Okta" button.
1031
1032 Create the file `src/admin/components/okta-icon.tsx` with the following content:
1033
1034 ```tsx title="src/admin/components/okta-icon.tsx"
1035 export default function OktaIcon() {
1036 return (
1037 <svg
1038 width="15"
1039 height="15"
1040 viewBox="0 0 15 15"
1041 fill="none"
1042 xmlns="http://www.w3.org/2000/svg"
1043 >
1044 <g clipPath="url(#clip0_16091_86347)">
1045 <path
1046 fillRule="evenodd"
1047 clipRule="evenodd"
1048 d="M8.23809 0.0952381L7.92857 3.90476C7.78571 3.88095 7.64286 3.88095 7.47619 3.88095C7.28571 3.88095 7.09524 3.90476 6.92857 3.92857L6.7619 2.09524C6.7619 2.04762 6.80952 1.97619 6.85714 1.97619H7.16667L7.02381 0.119048C7.02381 0.0714286 7.07143 0 7.11905 0H8.14286C8.21429 0 8.2619 0.047619 8.23809 0.0952381ZM5.66667 0.285714C5.64286 0.238095 5.59524 0.190476 5.54762 0.214286L4.59524 0.571429C4.52381 0.595238 4.5 0.666667 4.52381 0.714286L5.30952 2.40476L5.02381 2.52381C4.97619 2.54762 4.95238 2.59524 4.97619 2.66667L5.7619 4.33333C6.04762 4.16667 6.35714 4.04762 6.69048 3.97619L5.66667 0.285714ZM3.33333 1.35714L5.54762 4.47619C5.2619 4.66667 5.02381 4.88095 4.80952 5.11905L3.45238 3.80952C3.40476 3.7619 3.40476 3.69048 3.45238 3.66667L3.69048 3.47619L2.38095 2.14286C2.33333 2.09524 2.33333 2.02381 2.38095 2L3.16667 1.35714C3.21429 1.28571 3.28571 1.30952 3.33333 1.35714ZM1.47619 3.14286C1.42857 3.11905 1.35714 3.11905 1.33333 3.16667L0.833333 4.04762C0.809524 4.09524 0.833333 4.16667 0.880952 4.19048L2.57143 5L2.40476 5.2619C2.38095 5.30952 2.40476 5.38095 2.45238 5.40476L4.14286 6.16667C4.2619 5.85714 4.42857 5.57143 4.61905 5.30952L1.47619 3.14286ZM0.214286 5.54762C0.214286 5.5 0.285714 5.45238 0.333333 5.47619L4.02381 6.42857C3.92857 6.7381 3.88095 7.07143 3.85714 7.40476L2 7.2619C1.95238 7.2619 1.90476 7.21429 1.90476 7.14286L1.95238 6.83333L0.142857 6.66667C0.0952381 6.66667 0.047619 6.61905 0.047619 6.54762L0.214286 5.54762ZM0.0952381 8.04762C0.0238095 8.04762 0 8.09524 0 8.16667L0.190476 9.16667C0.190476 9.21429 0.261905 9.2619 0.309524 9.2381L2.11905 8.7619L2.16667 9.07143C2.16667 9.11905 2.2381 9.16667 2.28571 9.14286L4.07143 8.64286C3.97619 8.33333 3.90476 8 3.88095 7.66667L0.0952381 8.04762ZM0.690476 10.6905C0.666667 10.6429 0.690476 10.5714 0.738095 10.5476L4.19048 8.90476C4.30952 9.21429 4.5 9.5 4.71429 9.7619L3.21429 10.8333C3.16667 10.8571 3.09524 10.8571 3.07143 10.8095L2.85714 10.5476L1.30952 11.619C1.2619 11.6429 1.19048 11.6429 1.16667 11.5952L0.690476 10.6905ZM4.85714 9.97619L2.16667 12.6905C2.11905 12.7381 2.11905 12.8095 2.16667 12.8333L2.95238 13.4762C3 13.5238 3.07143 13.5 3.09524 13.4524L4.19048 11.9286L4.42857 12.1429C4.47619 12.1905 4.54762 12.1667 4.57143 12.119L5.61905 10.5952C5.33333 10.4286 5.07143 10.2143 4.85714 9.97619ZM4.33333 14.3095C4.28571 14.2857 4.2619 14.2381 4.28571 14.1667L5.85714 10.7143C6.14286 10.8571 6.47619 10.9762 6.78571 11.0476L6.30952 12.8333C6.28571 12.881 6.2381 12.9286 6.19048 12.9048L5.90476 12.7857L5.40476 14.5952C5.38095 14.6429 5.33333 14.6905 5.28571 14.6667L4.33333 14.3095ZM7.04762 11.0952L6.7381 14.9048C6.7381 14.9524 6.78571 15.0238 6.83333 15.0238H7.85714C7.90476 15.0238 7.95238 14.9762 7.95238 14.9048L7.80952 13.0476H8.11905C8.16667 13.0476 8.21429 13 8.21429 12.9286L8.04762 11.0952C7.85714 11.119 7.69048 11.1429 7.5 11.1429C7.35714 11.119 7.19048 11.119 7.04762 11.0952ZM10.7381 0.809524C10.7619 0.761905 10.7381 0.690476 10.6905 0.666667L9.7381 0.309524C9.69048 0.285714 9.61905 0.333333 9.61905 0.380952L9.11905 2.19048L8.83333 2.07143C8.78571 2.04762 8.71429 2.09524 8.71429 2.14286L8.23809 3.92857C8.57143 4 8.88095 4.11905 9.16667 4.2619L10.7381 0.809524ZM12.8333 2.30952L10.1429 5.02381C9.92857 4.78571 9.66667 4.57143 9.38095 4.40476L10.4286 2.88095C10.4524 2.83333 10.5238 2.83333 10.5714 2.85714L10.8095 3.07143L11.9048 1.54762C11.9286 1.5 12 1.5 12.0476 1.52381L12.8333 2.16667C12.8571 2.21429 12.8571 2.28571 12.8333 2.30952ZM14.2619 4.45238C14.3095 4.42857 14.3333 4.35714 14.3095 4.30952L13.8095 3.42857C13.7857 3.38095 13.7143 3.35714 13.6667 3.40476L12.119 4.47619L11.9524 4.21429C11.9286 4.16667 11.8571 4.14286 11.8095 4.19048L10.3095 5.2381C10.5238 5.5 10.6905 5.78571 10.8333 6.09524L14.2619 4.45238ZM14.8095 5.83333L14.9762 6.83333C14.9762 6.88095 14.9524 6.95238 14.881 6.95238L11.0952 7.30952C11.0714 6.97619 11 6.64286 10.9048 6.33333L12.6905 5.83333C12.7381 5.80952 12.8095 5.85714 12.8095 5.90476L12.8571 6.21429L14.6667 5.7381C14.7381 5.7381 14.7857 5.78571 14.8095 5.83333ZM14.6429 9.52381C14.6905 9.54762 14.7619 9.5 14.7619 9.45238L14.9286 8.45238C14.9286 8.40476 14.9048 8.33333 14.8333 8.33333L12.9762 8.16667L13.0238 7.85714C13.0238 7.80952 13 7.7381 12.9286 7.7381L11.0714 7.59524C11.0714 7.92857 11 8.2619 10.9048 8.57143L14.6429 9.52381ZM13.6667 11.8095C13.6429 11.8571 13.5714 11.881 13.5238 11.8333L10.381 9.66667C10.5714 9.40476 10.7381 9.11905 10.8571 8.80952L12.5476 9.57143C12.5952 9.59524 12.619 9.66667 12.5952 9.71429L12.4286 10L14.119 10.8095C14.1667 10.8333 14.1905 10.9048 14.1667 10.9524L13.6667 11.8095ZM9.45238 10.5238L11.6667 13.6429C11.6905 13.6905 11.7619 13.6905 11.8095 13.6667L12.5952 13.0238C12.6429 12.9762 12.6429 12.9286 12.5952 12.881L11.2857 11.5476L11.5238 11.3571C11.5714 11.3095 11.5714 11.2619 11.5238 11.2143L10.2143 9.90476C10 10.1429 9.7381 10.3571 9.45238 10.5238ZM9.45238 14.7619C9.40476 14.7857 9.33333 14.7381 9.33333 14.6905L8.33333 11.0238C8.66667 10.9524 8.97619 10.8333 9.26191 10.6667L10.0476 12.3333C10.0714 12.381 10.0476 12.4524 10 12.4762L9.71429 12.5952L10.5 14.2857C10.5238 14.3333 10.5 14.4048 10.4524 14.4286L9.45238 14.7619Z"
1049 fill="currentColor"
1050 />
1051 </g>
1052 <defs>
1053 <clipPath id="clip0_16091_86347">
1054 <rect width="15" height="15" fill="white"/>
1055 </clipPath>
1056 </defs>
1057 </svg>
1058 )
1059 }
1060 ```
1061
1062 ### d. Create Login with Okta Widget
1063
1064 A [widget](!docs!/learn/fundamentals/admin/widgets) is a React component that you can inject into predefined zones in the Medusa Admin.
1065
1066 You'll create a widget that renders the "Login with Okta" button on the login page.
1067
1068 To create the widget, create the file `src/admin/widgets/okta-login.tsx` with the following content:
1069
1070 ```tsx title="src/admin/widgets/okta-login.tsx"
1071 import { defineWidgetConfig } from "@medusajs/admin-sdk"
1072 import { Button, toast } from "@medusajs/ui"
1073 import { decodeToken } from "react-jwt"
1074 import { useSearchParams, useNavigate } from "react-router-dom"
1075 import { useMutation } from "@tanstack/react-query"
1076 import { sdk } from "../lib/sdk"
1077 import { useEffect, useMemo } from "react"
1078 import OktaIcon from "../components/okta-icon"
1079
1080 const OKTA_AUTH_PROVIDER = "okta"
1081
1082 const LoginWithOkta = () => {
1083 const [searchParams] = useSearchParams()
1084 const navigate = useNavigate()
1085
1086 // TODO define auth functions
1087 }
1088
1089 export const config = defineWidgetConfig({
1090 zone: "login.after",
1091 })
1092
1093 export default LoginWithOkta
1094 ```
1095
1096 A widget file must export:
1097
1098 1. A React component as the default export. This component renders the widget's UI.
1099 2. A widget configuration object created using `defineWidgetConfig`. This configuration specifies the zone where the widget will be injected, which is `login.after` in this case.
1100
1101 So far, in the component, you:
1102
1103 1. Retrieve the URL search parameters. You'll use this to get the authorization code returned by Okta after authentication.
1104 2. Get the `navigate` function which is necessary for navigation after successful login.
1105
1106 #### Initiate Okta Authentication
1107
1108 Next, you'll start adding the functions necessary for the authentication flow. The first function is the button click handler that initiates the Okta authentication flow.
1109
1110 Replace the `// TODO define auth functions` comment with the following:
1111
1112 ```tsx title="src/admin/widgets/okta-login.tsx"
1113 const oktaLogin = async () => {
1114 const result = await sdk.auth.login("user", OKTA_AUTH_PROVIDER, {})
1115
1116 if (typeof result === "object" && result.location) {
1117 // Redirect to okta for authentication
1118 window.location.href = result.location
1119 return
1120 }
1121
1122 if (typeof result !== "string") {
1123 // Result failed, show an error
1124 toast.error("Authentication failed")
1125 return
1126 }
1127
1128 // User is authenticated
1129 navigate("/orders")
1130 }
1131
1132 // TODO send callback function
1133 ```
1134
1135 The `oktaLogin` function uses the JS SDK's `auth.login` method to initiate the Okta authentication flow. This method sends a request to Medusa's `/auth/user/okta` API route, which executes the `authenticate` method of the Okta Auth Module Provider's service.
1136
1137 If the result contains a `location` property, the user is redirected to that location, which is the Okta authentication page.
1138
1139 If the result is not a string (the authentication token), you show an error toast notification.
1140
1141 Otherwise, the user is authenticated and navigated to the orders page.
1142
1143 #### Handle Okta Callback in Server
1144
1145 Next, you'll add a function that validates the Okta authentication callback in the Medusa server.
1146
1147 Replace the `// TODO send callback function` comment with the following:
1148
1149 ```tsx title="src/admin/widgets/okta-login.tsx"
1150 const sendCallback = async () => {
1151 try {
1152 return await sdk.auth.callback(
1153 "user",
1154 OKTA_AUTH_PROVIDER,
1155 Object.fromEntries(searchParams)
1156 )
1157 } catch (error) {
1158 toast.error("Authentication failed")
1159 throw error
1160 }
1161 }
1162
1163 // TODO validate callback
1164 ```
1165
1166 The `sendCallback` function uses the JS SDK's `auth.callback` method to send the query parameters returned by Okta to Medusa's `/auth/user/okta/callback` API route.
1167
1168 This API route executes the `validateCallback` method of the Okta Auth Module Provider's service to validate the authentication.
1169
1170 #### Validate Callback and Create User
1171
1172 Next, you'll add a function that validates the callback and creates an admin user if the Okta user is new.
1173
1174 Replace the `// TODO validate callback` comment with the following:
1175
1176 ```tsx title="src/admin/widgets/okta-login.tsx"
1177 const validateCallback = async () => {
1178 const token = await sendCallback()
1179
1180 const decodedToken = decodeToken(token) as { actor_id: string, user_metadata: Record<string, unknown> }
1181
1182 const userExists = decodedToken.actor_id !== ""
1183
1184 if (!userExists) {
1185 // Create user
1186 await sdk.client.fetch("/okta/users", {
1187 method: "POST",
1188 body: {
1189 email: decodedToken.user_metadata?.email as string,
1190 first_name: decodedToken.user_metadata?.given_name as string,
1191 last_name: decodedToken.user_metadata?.family_name as string,
1192 },
1193 })
1194
1195 const newToken = await sdk.auth.refresh()
1196
1197 if (!newToken) {
1198 toast.error("Authentication failed")
1199 return
1200 }
1201 }
1202
1203 // User is authenticated
1204 navigate("/orders")
1205 }
1206
1207 const { mutateAsync, isPending } = useMutation({
1208 mutationFn: async () => {
1209 if (isPending) {
1210 return
1211 }
1212 return await validateCallback()
1213 },
1214 onError: (error) => {
1215 console.error("Custom authentication error:", error)
1216 },
1217 })
1218
1219 // TODO useEffect to trigger callback validation
1220 ```
1221
1222 In the `validateCallback` function, you:
1223
1224 1. Call the `sendCallback` function to validate the Okta authentication in the Medusa server.
1225 2. Decode the returned authentication token to access the user's details.
1226 3. If the `actor_id` in the decoded token is an empty string, it means the user is new. So, you:
1227 - Send a `POST` request to the `/okta/users` API route you created earlier to create an admin user for the new Okta user.
1228 - Refresh the authentication token using the JS SDK's `auth.refresh` method to get a token associated with the newly created user.
1229 4. Finally, the user is authenticated, and you navigate them to the orders page.
1230
1231 You also add a mutation using [Tanstack Query](https://tanstack.com/query/latest) to handle the asynchronous operation of validating the callback.
1232
1233 #### Trigger Callback Validation
1234
1235 Next, you'll trigger the callback validation when the search parameters contain an authorization code from Okta.
1236
1237 Replace the `// TODO useEffect to trigger callback validation` comment with the following:
1238
1239 ```tsx title="src/admin/widgets/okta-login.tsx"
1240 useEffect(() => {
1241 // Check for provider-specific query parameters
1242 if (searchParams.get("code")) {
1243 mutateAsync()
1244 }
1245 }, [searchParams, mutateAsync])
1246
1247 // TODO return statement
1248 ```
1249
1250 The `useEffect` hook runs whenever the search parameters change. If the `code` parameter is present, it calls the `mutateAsync` function to validate the callback.
1251
1252 #### Render Login with Okta Button
1253
1254 Finally, you'll render the "Login with Okta" button in the widget component. You'll also show a loading pop-up when the authentication is in progress.
1255
1256 Replace the `// TODO return statement` comment with the following:
1257
1258 ```tsx title="src/admin/widgets/okta-login.tsx"
1259 const showLoading = useMemo(() => {
1260 return isPending || !!searchParams.get("code")
1261 }, [isPending, searchParams])
1262
1263 return (
1264 <>
1265 {showLoading && (
1266 <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50 backdrop-blur-sm">
1267 <div className="flex flex-col items-center gap-4 rounded-lg bg-ui-bg-base p-8 shadow-lg">
1268 <div className="h-8 w-8 animate-spin rounded-full border-4 border-ui-border-base border-t-ui-fg-interactive" />
1269 <p className="text-ui-fg-subtle text-sm">Please wait...</p>
1270 </div>
1271 </div>
1272 )}
1273 <hr className="bg-ui-border-base my-4" />
1274 <Button
1275 variant="secondary"
1276 onClick={oktaLogin}
1277 className="w-full"
1278 isLoading={showLoading}
1279 >
1280 <OktaIcon />
1281 Login with Okta
1282 </Button>
1283 </>
1284 )
1285 ```
1286
1287 You define a memoized value `showLoading` that determines whether to show the loading pop-up.
1288
1289 Then, you render a loading pop-up if `showLoading` is `true`, and a "Login with Okta" button. The button displays the `OktaIcon` component and triggers the `oktaLogin` function when clicked.
1290
1291 ---
1292
1293 ## Test Okta Authentication Flow
1294
1295 You can now test out the Okta integration and authentication flow you implemented.
1296
1297 First, run the following command to start the Medusa server:
1298
1299 ```bash npm2yarn
1300 npm run dev
1301 ```
1302
1303 Then, open the Medusa Admin in your browser at `http://localhost:9000/app`. You'll see a "Login with Okta" button on the login page.
1304
1305 ![Medusa Admin login page with a "Login with Okta" button](https://res.cloudinary.com/dza7lstvk/image/upload/v1764676152/Medusa%20Resources/CleanShot_2025-12-02_at_13.48.58_2x_qjpsbk.png)
1306
1307 Click the button to initiate the Okta authentication flow. If you're already logged in to Okta, you'll be redirected back to the Medusa Admin immediately where you'll be logged in. If not, you'll be prompted to log in to Okta first, then redirected back to the Medusa Admin.
1308
1309 Once the authentication is successful, you can access the Medusa Admin dashboard as an authenticated user.
1310
1311 ---
1312
1313 ## Next Steps
1314
1315 You've now set up Okta as an authentication provider for admin users in your Medusa application. This allows your Okta organization's users to log in to the Medusa Admin using their Okta credentials without needing to manage separate credentials for Medusa.
1316
1317 You can also manage user access and permissions in Okta. For example, if you deny a user's access to the Medusa application in Okta, that user will no longer be able to log in to the Medusa Admin.
1318
1319 ### Learn More about Medusa
1320
1321 If you're new to Medusa, check out the [main documentation](!docs!/learn), where you'll get a more in-depth understanding of all the concepts you've used in this guide and more.
1322
1323 To learn more about the commerce features that Medusa provides, check out Medusa's [Commerce Modules](../../../commerce-modules/page.mdx).
1324
1325 ### Troubleshooting
1326
1327 If you encounter issues during your development, check out the [troubleshooting guides](../../../troubleshooting/page.mdx).
1328
1329 ### Getting Help
1330
1331 If you encounter issues not covered in the troubleshooting guides:
1332
1333 1. Visit the [Medusa GitHub repository](https://github.com/medusajs/medusa) to report issues or ask questions.
1334 2. Join the [Medusa Discord community](https://discord.gg/medusajs) for real-time support from community members.