1 {"slug":"/references/auth/provider","title":"How to Create an Auth Module Provider","frontmatter":{"slug":"/references/auth/provider","tags":["auth","server","how to"],"sidebar_label":"Create Auth Provider","keywords":["auth","provider","integration"]},"toc":[{"title":"Implementation Example","id":"implementation-example","level":2},{"title":"1. Create Module Provider Directory","id":"1-create-module-provider-directory","level":2},{"title":"2. Create the Auth Module Provider's Service","id":"2-create-the-auth-module-provider-s-service","level":2},{"title":"constructor","id":"constructor","level":3},{"title":"Example","id":"example","level":4},{"title":"DISPLAY_NAME","id":"display-name","level":3},{"title":"Example","id":"example-1","level":4},{"title":"identifier","id":"identifier","level":3},{"title":"Example","id":"example-2","level":4},{"title":"authenticate","id":"authenticate","level":3},{"title":"Example","id":"example-3","level":4},{"title":"Parameters","id":"authenticate-parameters","level":4},{"title":"Returns","id":"authenticate-returns","level":4},{"title":"register","id":"register","level":3},{"title":"Example","id":"example-4","level":4},{"title":"Parameters","id":"register-parameters","level":4},{"title":"Returns","id":"register-returns","level":4},{"title":"update","id":"update","level":3},{"title":"Example","id":"example-5","level":4},{"title":"Parameters","id":"update-parameters","level":4},{"title":"Returns","id":"update-returns","level":4},{"title":"validateCallback","id":"validatecallback","level":3},{"title":"Example","id":"example-6","level":4},{"title":"Parameters","id":"validatecallback-parameters","level":4},{"title":"Returns","id":"validatecallback-returns","level":4},{"title":"validateOptions","id":"validateoptions","level":3},{"title":"Example","id":"example-7","level":4},{"title":"Parameters","id":"validateoptions-parameters","level":4},{"title":"3. Create Module Provider Definition File","id":"3-create-module-provider-definition-file","level":2},{"title":"4. Use Module Provider","id":"4-use-module-provider","level":2},{"title":"5. Test it Out","id":"5-test-it-out","level":2}],"blocks":[{"kind":"markdown","html":"In this document, you’ll learn how to create an Auth Module Provider and the methods you must implement in its main service."},{"kind":"markdown","html":"---"},{"kind":"heading","level":2,"text":"Implementation Example","id":"implementation-example"},{"kind":"markdown","html":"As you implement your Auth Module Provider, it can be useful to refer to an existing provider and how it's implemeted.\n\nIf you need to refer to an existing implementation as an example, check the [Google Auth Module Provider in the Medusa repository](https://github.com/medusajs/medusa/tree/develop/packages/modules/providers/auth-google).\n\n---"},{"kind":"heading","level":2,"text":"1. Create Module Provider Directory","id":"1-create-module-provider-directory"},{"kind":"markdown","html":"Start by creating a new directory for your module provider.\n\nIf you're creating the module provider in a Medusa application, create it under the `src/modules` directory. For example, `src/modules/my-auth`.\n\nIf you're creating the module provider in a plugin, create it under the `src/providers` directory. For example, `src/providers/my-auth`."},{"kind":"note","variant":"note","html":"The rest of this guide always uses the `src/modules/my-auth` directory as an example."},{"kind":"markdown","html":"---"},{"kind":"heading","level":2,"text":"2. Create the Auth Module Provider's Service","id":"2-create-the-auth-module-provider-s-service"},{"kind":"markdown","html":"Create the file `src/modules/my-auth/service.ts` that holds the module provider's main service. It must extend the `AbstractAuthModuleProvider` class imported from `@medusajs/framework/utils`:\n\n```ts title=\"src/modules/my-auth/service.ts\"\nimport { AbstractAuthModuleProvider } from \"@medusajs/framework/utils\"\n\nclass MyAuthProviderService extends AbstractAuthModuleProvider {\n // TODO implement methods\n}\n\nexport default MyAuthProviderService\n```"},{"kind":"heading","level":3,"text":"constructor","id":"constructor"},{"kind":"markdown","html":"The constructor allows you to access resources from the module's container using the first parameter,\nand the module's options using the second parameter.\n\nIf you're creating a client or establishing a connection with a third-party service, do it in the constructor."},{"kind":"heading","level":4,"text":"Example","id":"example"},{"kind":"markdown","html":"```ts\nimport { AbstractAuthModuleProvider } from \"@medusajs/framework/utils\"\nimport { Logger } from \"@medusajs/framework/types\"\n\ntype InjectedDependencies = {\n logger: Logger\n}\n\ntype Options = {\n apiKey: string\n}\n\nclass MyAuthProviderService extends AbstractAuthModuleProvider {\n static identifier = \"my-auth\"\n protected logger_: Logger\n protected options_: Options\n // assuming you're initializing a client\n protected client\n\n constructor (\n { logger }: InjectedDependencies,\n options: Options\n ) {\n super(...arguments)\n\n this.logger_ = logger\n this.options_ = options\n\n // assuming you're initializing a client\n this.client = new Client(options)\n }\n\n // ...\n}\n\nexport default MyAuthProviderService\n```"},{"kind":"heading","level":3,"text":"DISPLAY_NAME","id":"display-name"},{"kind":"markdown","html":"This property indicates the name used when displaying the provider on a frontend application."},{"kind":"heading","level":4,"text":"Example","id":"example-1"},{"kind":"markdown","html":"```ts\nclass MyAuthProviderService extends AbstractAuthModuleProvider {\n static DISPLAY_NAME = \"My Auth\"\n // ...\n}\n```"},{"kind":"heading","level":3,"text":"identifier","id":"identifier"},{"kind":"markdown","html":"Every auth provider must have an `identifier` static property. The provider's ID\nwill be stored as `au_{identifier}_{id}`, where `{id}` is the provider's `id` \nproperty in the `medusa-config.ts`."},{"kind":"heading","level":4,"text":"Example","id":"example-2"},{"kind":"markdown","html":"```ts\nclass MyAuthProviderService extends AbstractAuthModuleProvider {\n static identifier = \"my-auth\"\n // ...\n}\n```"},{"kind":"heading","level":3,"text":"authenticate","id":"authenticate"},{"kind":"markdown","html":"This method authenticates the user.\n\nThe authentication happens either by directly authenticating or returning a redirect URL to continue\nthe authentication with a third party provider.\n\nRelated Read: [Learn about the different authentication flows in Medusa](https://docs.medusajs.com/resources/commerce-modules/auth/authentication-route)."},{"kind":"heading","level":4,"text":"Example","id":"example-3"},{"kind":"markdown","html":"For example, if your authentication provider doesn't require validating a callback:\n\n```ts\nimport {\n AuthIdentityProviderService,\n AuthenticationInput,\n AuthenticationResponse\n} from \"@medusajs/framework/types\"\n// ...\n\nclass MyAuthProviderService extends AbstractAuthModuleProvider {\n // ...\n async authenticate(\n data: AuthenticationInput,\n authIdentityProviderService: AuthIdentityProviderService\n ): Promise<AuthenticationResponse> {\n const isAuthenticated = false\n // TODO perform custom logic to authenticate the user\n // for example, verifying a password\n\n if (!isAuthenticated) {\n // if the authentication didn't succeed, return\n // an object of the following format\n return {\n success: false,\n error: \"Incorrect credentials\"\n }\n }\n\n // authentication is successful, retrieve the identity\n const authIdentity = await authIdentityProviderService.retrieve({\n entity_id: data.body.email, // email or some ID\n })\n\n return {\n success: true,\n authIdentity\n }\n }\n}\n```\n\nIf your authentication provider requires validating callback:\n\n```ts\nimport {\n AuthIdentityProviderService,\n AuthenticationInput,\n AuthenticationResponse\n} from \"@medusajs/framework/types\"\n// ...\n\nclass MyAuthProviderService extends AbstractAuthModuleProvider {\n // ...\n async authenticate(\n data: AuthenticationInput,\n authIdentityProviderService: AuthIdentityProviderService\n ): Promise<AuthenticationResponse> {\n const isAuthenticated = false\n // TODO perform custom logic to authenticate the user\n // ...\n\n if (!isAuthenticated) {\n // if the authentication didn't succeed, return\n // an object of the following format\n return {\n success: false,\n error: \"Incorrect credentials\"\n }\n }\n\n // optional, useful for third-party providers that require a redirect URL\n // to continue the authentication flow\n // const stateKey = crypto.randomBytes(32).toString(\"hex\")\n // const state = {\n // callback_url: body?.callback_url ?? this.config_.callbackUrl,\n // }\n \n // verify this later in the `validateCallback` method\n // await authIdentityService.setState(stateKey, state)\n\n return {\n success: true,\n location: \"some-url.com\"\n }\n }\n}\n```"},{"kind":"heading","level":4,"text":"Parameters","id":"authenticate-parameters"},{"kind":"typeList","sectionTitle":"authenticate","types":[{"name":"data","type":"[AuthenticationInput](/references/types/interfaces/types.AuthenticationInput)","description":"The details of the authentication request.","optional":false,"defaultValue":"","expandable":false,"children":[{"name":"url","type":"`string`","description":"URL of the incoming authentication request.","optional":true,"defaultValue":"","expandable":false,"children":[]},{"name":"headers","type":"`Record<string, string>`","description":"Headers of incoming authentication request.","optional":true,"defaultValue":"","expandable":false,"children":[]},{"name":"query","type":"`Record<string, string>`","description":"Query params of the incoming authentication request.","optional":true,"defaultValue":"","expandable":false,"children":[]},{"name":"body","type":"`Record<string, string>`","description":"Body of the incoming authentication request.\n\nOne of the arguments that is suggested to be treated in a standard manner is a `callback_url` field.\nThe field specifies where the user is redirected to after a successful authentication in the case of Oauth auhentication.\nIf not passed, the provider will fallback to the callback\\_url provided in the provider options.","optional":true,"defaultValue":"","expandable":false,"children":[]},{"name":"protocol","type":"`string`","description":"Protocol of the incoming authentication request (For example, `https`).","optional":true,"defaultValue":"","expandable":false,"children":[]}]},{"name":"authIdentityProviderService","type":"[AuthIdentityProviderService](/references/types/interfaces/types.AuthIdentityProviderService)","description":"The service used to retrieve or\ncreate an auth identity. It has two methods: `create` to create an auth identity,\nand `retrieve` to retrieve an auth identity. When you authenticate the user, you can create an auth identity\nusing this service.","optional":false,"defaultValue":"","expandable":false,"children":[{"name":"retrieve","type":"(`selector`: ``{ entity_id: string }``) => Promise&#60;[AuthIdentityDTO](/references/auth/interfaces/auth.AuthIdentityDTO)&#62;","description":"","optional":false,"defaultValue":"","expandable":false,"children":[]},{"name":"create","type":"(`data`: ``{ entity_id: string ; provider_metadata?: Record&#60;string, unknown&#62; ; user_metadata?: Record&#60;string, unknown&#62; }``) => Promise&#60;[AuthIdentityDTO](/references/auth/interfaces/auth.AuthIdentityDTO)&#62;","description":"","optional":false,"defaultValue":"","expandable":false,"children":[]},{"name":"update","type":"(`entity_id`: `string`, `data`: ``{ provider_metadata?: Record&#60;string, unknown&#62; ; user_metadata?: Record&#60;string, unknown&#62; }``) => Promise&#60;[AuthIdentityDTO](/references/auth/interfaces/auth.AuthIdentityDTO)&#62;","description":"","optional":false,"defaultValue":"","expandable":false,"children":[]},{"name":"setState","type":"(`key`: `string`, `value`: `Record<string, unknown>`, `ttlSeconds?`: `number`) => Promise&#60;void&#62;","description":"","optional":false,"defaultValue":"","expandable":false,"children":[]},{"name":"getState","type":"(`key`: `string`) => Promise&#60;null \\| Record&#60;string, unknown&#62;&#62;","description":"","optional":false,"defaultValue":"","expandable":false,"children":[]}]}]},{"kind":"heading","level":4,"text":"Returns","id":"authenticate-returns"},{"kind":"typeList","sectionTitle":"authenticate","types":[{"name":"Promise","type":"Promise&#60;[AuthenticationResponse](/references/types/interfaces/types.AuthenticationResponse)&#62;","optional":false,"defaultValue":"","description":"The authentication response.","expandable":false,"children":[{"name":"success","type":"`boolean`","description":"Whether the authentication was successful.","optional":false,"defaultValue":"","expandable":false,"children":[]},{"name":"authIdentity","type":"[AuthIdentityDTO](/references/auth/interfaces/auth.AuthIdentityDTO)","description":"The authenticated user's details.","optional":true,"defaultValue":"","expandable":false,"children":[{"name":"id","type":"`string`","description":"The ID of the auth identity.","optional":false,"defaultValue":"","expandable":false,"children":[]},{"name":"provider_identities","type":"[ProviderIdentityDTO](/references/auth/interfaces/auth.ProviderIdentityDTO)[]","description":"The list of provider identities linked to the auth identity.","optional":true,"defaultValue":"","expandable":false,"children":[]},{"name":"app_metadata","type":"`Record<string, unknown>`","description":"Holds information related to the actor IDs tied to the auth identity.","optional":true,"defaultValue":"","expandable":false,"children":[]}]},{"name":"mfaChallenge","type":"[AuthMfaChallengeDTO](/references/auth/types/auth.AuthMfaChallengeDTO)","description":"The multi-factor authentication (MFA) challenge to complete before issuing a token.","optional":true,"defaultValue":"","expandable":false,"children":[{"name":"id","type":"`string`","description":"The multi-factor authentication (MFA) challenge's ID.","optional":false,"defaultValue":"","expandable":false,"children":[]},{"name":"auth_identity_id","type":"`string`","description":"The ID of the authentication identity being challenged.","optional":true,"defaultValue":"","expandable":false,"children":[]},{"name":"auth_identity","type":"[AuthIdentityDTO](/references/auth/interfaces/auth.AuthIdentityDTO)","description":"The authentication identity being challenged.","optional":true,"defaultValue":"","expandable":true,"children":[]},{"name":"auth_provider","type":"`string` \\| `null`","description":"The authentication provider handling the challenge.","optional":true,"defaultValue":"","expandable":false,"children":[]},{"name":"methods","type":"[AuthMfaChallengeMethod](/references/auth/types/auth.AuthMfaChallengeMethod)[]","description":"Available methods for completing this challenge.","optional":false,"defaultValue":"","expandable":false,"children":[]},{"name":"expires_at","type":"`Date`","description":"When the challenge expires.","optional":false,"defaultValue":"","expandable":false,"children":[]},{"name":"attempts","type":"`number`","description":"Number of verification attempts made.","optional":false,"defaultValue":"","expandable":false,"children":[]},{"name":"max_attempts","type":"`number`","description":"Maximum verification attempts allowed.","optional":false,"defaultValue":"","expandable":false,"children":[]},{"name":"completed_at","type":"`Date` \\| `null`","description":"When the challenge was completed.","optional":true,"defaultValue":"","expandable":false,"children":[]},{"name":"metadata","type":"`Record<string, unknown>` \\| `null`","description":"Additional metadata for the challenge.","optional":true,"defaultValue":"","expandable":false,"children":[]}]},{"name":"error","type":"`string`","description":"If an error occurs during the authentication process,\nwhether within the Auth Module or a third-party provider,\nthe error message is set in this field.","optional":true,"defaultValue":"","expandable":false,"children":[]},{"name":"location","type":"`string`","description":"The URL to redirect to for further authentication action\nwith a third-party provider. This takes precedence before\nthe `success` field.\n\nSo, after checking that authentication is successful,\nyou should check whether this field is defined and, if so, redirect to the\nspecified location.","optional":true,"defaultValue":"","expandable":false,"children":[]}]}]},{"kind":"heading","level":3,"text":"register","id":"register"},{"kind":"markdown","html":"This method receives credentails to create a new auth identity. It performs any validation necessary\nbefore creating the auth identity.\n\nFor example, in the `emailpass` provider, this method ensures that the provided email doesn't exist\nbefore creating the auth identity.\n\nThis method is only used in a basic authentication flow, such as when using an email and password\nto register and authenticate a user.\n\nRelated Read: [Learn about the different authentication flows in Medusa](https://docs.medusajs.com/resources/commerce-modules/auth/authentication-route)."},{"kind":"heading","level":4,"text":"Example","id":"example-4"},{"kind":"markdown","html":"```ts\nimport {\n AuthIdentityProviderService,\n AuthenticationInput,\n AuthenticationResponse\n} from \"@medusajs/framework/types\"\nimport { MedusaError } from \"@medusajs/framework/utils\"\n// ...\n\nclass MyAuthProviderService extends AbstractAuthModuleProvider {\n // ...\n async register(\n data: AuthenticationInput,\n authIdentityProviderService: AuthIdentityProviderService\n ): Promise<AuthenticationResponse> {\n try {\n await authIdentityService.retrieve({\n entity_id: data.body.email, // email or some ID\n })\n\n return {\n success: false,\n error: \"Identity with email already exists\",\n }\n } catch (error) {\n if (error.type === MedusaError.Types.NOT_FOUND) {\n const createdAuthIdentity = await authIdentityProviderService.create({\n entity_id: data.body.email, // email or some ID\n provider: this.provider,\n provider_metadata: {\n // can include password or any other relevant information\n }\n })\n\n return {\n success: true,\n authIdentity: createdAuthIdentity,\n }\n }\n\n return { success: false, error: error.message }\n }\n }\n}\n```"},{"kind":"heading","level":4,"text":"Parameters","id":"register-parameters"},{"kind":"typeList","sectionTitle":"register","types":[{"name":"data","type":"[AuthenticationInput](/references/types/interfaces/types.AuthenticationInput)","description":"The details of the authentication request.","optional":false,"defaultValue":"","expandable":false,"children":[{"name":"url","type":"`string`","description":"URL of the incoming authentication request.","optional":true,"defaultValue":"","expandable":false,"children":[]},{"name":"headers","type":"`Record<string, string>`","description":"Headers of incoming authentication request.","optional":true,"defaultValue":"","expandable":false,"children":[]},{"name":"query","type":"`Record<string, string>`","description":"Query params of the incoming authentication request.","optional":true,"defaultValue":"","expandable":false,"children":[]},{"name":"body","type":"`Record<string, string>`","description":"Body of the incoming authentication request.\n\nOne of the arguments that is suggested to be treated in a standard manner is a `callback_url` field.\nThe field specifies where the user is redirected to after a successful authentication in the case of Oauth auhentication.\nIf not passed, the provider will fallback to the callback\\_url provided in the provider options.","optional":true,"defaultValue":"","expandable":false,"children":[]},{"name":"protocol","type":"`string`","description":"Protocol of the incoming authentication request (For example, `https`).","optional":true,"defaultValue":"","expandable":false,"children":[]}]},{"name":"authIdentityProviderService","type":"[AuthIdentityProviderService](/references/types/interfaces/types.AuthIdentityProviderService)","description":"The service used to retrieve or\ncreate an auth identity. It has two methods: `create` to create an auth identity,\nand `retrieve` to retrieve an auth identity. When you authenticate the user, you can create an auth identity\nusing this service.","optional":false,"defaultValue":"","expandable":false,"children":[{"name":"retrieve","type":"(`selector`: ``{ entity_id: string }``) => Promise&#60;[AuthIdentityDTO](/references/auth/interfaces/auth.AuthIdentityDTO)&#62;","description":"","optional":false,"defaultValue":"","expandable":false,"children":[]},{"name":"create","type":"(`data`: ``{ entity_id: string ; provider_metadata?: Record&#60;string, unknown&#62; ; user_metadata?: Record&#60;string, unknown&#62; }``) => Promise&#60;[AuthIdentityDTO](/references/auth/interfaces/auth.AuthIdentityDTO)&#62;","description":"","optional":false,"defaultValue":"","expandable":false,"children":[]},{"name":"update","type":"(`entity_id`: `string`, `data`: ``{ provider_metadata?: Record&#60;string, unknown&#62; ; user_metadata?: Record&#60;string, unknown&#62; }``) => Promise&#60;[AuthIdentityDTO](/references/auth/interfaces/auth.AuthIdentityDTO)&#62;","description":"","optional":false,"defaultValue":"","expandable":false,"children":[]},{"name":"setState","type":"(`key`: `string`, `value`: `Record<string, unknown>`, `ttlSeconds?`: `number`) => Promise&#60;void&#62;","description":"","optional":false,"defaultValue":"","expandable":false,"children":[]},{"name":"getState","type":"(`key`: `string`) => Promise&#60;null \\| Record&#60;string, unknown&#62;&#62;","description":"","optional":false,"defaultValue":"","expandable":false,"children":[]}]}]},{"kind":"heading","level":4,"text":"Returns","id":"register-returns"},{"kind":"typeList","sectionTitle":"register","types":[{"name":"Promise","type":"Promise&#60;[AuthenticationResponse](/references/types/interfaces/types.AuthenticationResponse)&#62;","optional":false,"defaultValue":"","description":"The created authentication identity if no errors occur.","expandable":false,"children":[{"name":"success","type":"`boolean`","description":"Whether the authentication was successful.","optional":false,"defaultValue":"","expandable":false,"children":[]},{"name":"authIdentity","type":"[AuthIdentityDTO](/references/auth/interfaces/auth.AuthIdentityDTO)","description":"The authenticated user's details.","optional":true,"defaultValue":"","expandable":false,"children":[{"name":"id","type":"`string`","description":"The ID of the auth identity.","optional":false,"defaultValue":"","expandable":false,"children":[]},{"name":"provider_identities","type":"[ProviderIdentityDTO](/references/auth/interfaces/auth.ProviderIdentityDTO)[]","description":"The list of provider identities linked to the auth identity.","optional":true,"defaultValue":"","expandable":false,"children":[]},{"name":"app_metadata","type":"`Record<string, unknown>`","description":"Holds information related to the actor IDs tied to the auth identity.","optional":true,"defaultValue":"","expandable":false,"children":[]}]},{"name":"mfaChallenge","type":"[AuthMfaChallengeDTO](/references/auth/types/auth.AuthMfaChallengeDTO)","description":"The multi-factor authentication (MFA) challenge to complete before issuing a token.","optional":true,"defaultValue":"","expandable":false,"children":[{"name":"id","type":"`string`","description":"The multi-factor authentication (MFA) challenge's ID.","optional":false,"defaultValue":"","expandable":false,"children":[]},{"name":"auth_identity_id","type":"`string`","description":"The ID of the authentication identity being challenged.","optional":true,"defaultValue":"","expandable":false,"children":[]},{"name":"auth_identity","type":"[AuthIdentityDTO](/references/auth/interfaces/auth.AuthIdentityDTO)","description":"The authentication identity being challenged.","optional":true,"defaultValue":"","expandable":true,"children":[]},{"name":"auth_provider","type":"`string` \\| `null`","description":"The authentication provider handling the challenge.","optional":true,"defaultValue":"","expandable":false,"children":[]},{"name":"methods","type":"[AuthMfaChallengeMethod](/references/auth/types/auth.AuthMfaChallengeMethod)[]","description":"Available methods for completing this challenge.","optional":false,"defaultValue":"","expandable":false,"children":[]},{"name":"expires_at","type":"`Date`","description":"When the challenge expires.","optional":false,"defaultValue":"","expandable":false,"children":[]},{"name":"attempts","type":"`number`","description":"Number of verification attempts made.","optional":false,"defaultValue":"","expandable":false,"children":[]},{"name":"max_attempts","type":"`number`","description":"Maximum verification attempts allowed.","optional":false,"defaultValue":"","expandable":false,"children":[]},{"name":"completed_at","type":"`Date` \\| `null`","description":"When the challenge was completed.","optional":true,"defaultValue":"","expandable":false,"children":[]},{"name":"metadata","type":"`Record<string, unknown>` \\| `null`","description":"Additional metadata for the challenge.","optional":true,"defaultValue":"","expandable":false,"children":[]}]},{"name":"error","type":"`string`","description":"If an error occurs during the authentication process,\nwhether within the Auth Module or a third-party provider,\nthe error message is set in this field.","optional":true,"defaultValue":"","expandable":false,"children":[]},{"name":"location","type":"`string`","description":"The URL to redirect to for further authentication action\nwith a third-party provider. This takes precedence before\nthe `success` field.\n\nSo, after checking that authentication is successful,\nyou should check whether this field is defined and, if so, redirect to the\nspecified location.","optional":true,"defaultValue":"","expandable":false,"children":[]}]}]},{"kind":"heading","level":3,"text":"update","id":"update"},{"kind":"markdown","html":"This method is used to update an auth identity's details.\n\nFor example, the `emailpass` provider's implementation of this method updates a user's password."},{"kind":"heading","level":4,"text":"Example","id":"example-5"},{"kind":"markdown","html":"```ts\nimport {\n AuthIdentityProviderService,\n AuthenticationInput,\n AuthenticationResponse\n} from \"@medusajs/framework/types\"\nimport { MedusaError } from \"@medusajs/framework/utils\"\n// ...\n\nclass MyAuthProviderService extends AbstractAuthModuleProvider {\n // ...\n async update(\n data: Record<string, unknown>,\n authIdentityProviderService: AuthIdentityProviderService\n ): Promise<AuthenticationResponse> {\n try {\n const authIdentity = await authIdentityService.update(\n data.email, // email or some ID used to identify the auth identity\n {\n user: data.user // example\n }\n )\n\n return { success: true, authIdentity }\n } catch (error) {\n return { success: false, error: error.message }\n }\n }\n}\n```"},{"kind":"heading","level":4,"text":"Parameters","id":"update-parameters"},{"kind":"typeList","sectionTitle":"update","types":[{"name":"data","type":"`Record<string, unknown>`","description":"Data relevant to identify the auth identity and what to update in it. For example,\nthe `emailpass` provider expects in this object an `email` and `password` properties.","optional":false,"defaultValue":"","expandable":false,"children":[]},{"name":"authIdentityProviderService","type":"[AuthIdentityProviderService](/references/types/interfaces/types.AuthIdentityProviderService)","description":"The service used to retrieve or\ncreate an auth identity. It has two methods: `create` to create an auth identity,\nand `retrieve` to retrieve an auth identity. When you authenticate the user, you can create an auth identity\nusing this service.","optional":false,"defaultValue":"","expandable":false,"children":[{"name":"retrieve","type":"(`selector`: ``{ entity_id: string }``) => Promise&#60;[AuthIdentityDTO](/references/auth/interfaces/auth.AuthIdentityDTO)&#62;","description":"","optional":false,"defaultValue":"","expandable":false,"children":[]},{"name":"create","type":"(`data`: ``{ entity_id: string ; provider_metadata?: Record&#60;string, unknown&#62; ; user_metadata?: Record&#60;string, unknown&#62; }``) => Promise&#60;[AuthIdentityDTO](/references/auth/interfaces/auth.AuthIdentityDTO)&#62;","description":"","optional":false,"defaultValue":"","expandable":false,"children":[]},{"name":"update","type":"(`entity_id`: `string`, `data`: ``{ provider_metadata?: Record&#60;string, unknown&#62; ; user_metadata?: Record&#60;string, unknown&#62; }``) => Promise&#60;[AuthIdentityDTO](/references/auth/interfaces/auth.AuthIdentityDTO)&#62;","description":"","optional":false,"defaultValue":"","expandable":false,"children":[]},{"name":"setState","type":"(`key`: `string`, `value`: `Record<string, unknown>`, `ttlSeconds?`: `number`) => Promise&#60;void&#62;","description":"","optional":false,"defaultValue":"","expandable":false,"children":[]},{"name":"getState","type":"(`key`: `string`) => Promise&#60;null \\| Record&#60;string, unknown&#62;&#62;","description":"","optional":false,"defaultValue":"","expandable":false,"children":[]}]}]},{"kind":"heading","level":4,"text":"Returns","id":"update-returns"},{"kind":"typeList","sectionTitle":"update","types":[{"name":"Promise","type":"Promise&#60;[AuthenticationResponse](/references/types/interfaces/types.AuthenticationResponse)&#62;","optional":false,"defaultValue":"","description":"The updated authentication identity if no errors occur.","expandable":false,"children":[{"name":"success","type":"`boolean`","description":"Whether the authentication was successful.","optional":false,"defaultValue":"","expandable":false,"children":[]},{"name":"authIdentity","type":"[AuthIdentityDTO](/references/auth/interfaces/auth.AuthIdentityDTO)","description":"The authenticated user's details.","optional":true,"defaultValue":"","expandable":false,"children":[{"name":"id","type":"`string`","description":"The ID of the auth identity.","optional":false,"defaultValue":"","expandable":false,"children":[]},{"name":"provider_identities","type":"[ProviderIdentityDTO](/references/auth/interfaces/auth.ProviderIdentityDTO)[]","description":"The list of provider identities linked to the auth identity.","optional":true,"defaultValue":"","expandable":false,"children":[]},{"name":"app_metadata","type":"`Record<string, unknown>`","description":"Holds information related to the actor IDs tied to the auth identity.","optional":true,"defaultValue":"","expandable":false,"children":[]}]},{"name":"mfaChallenge","type":"[AuthMfaChallengeDTO](/references/auth/types/auth.AuthMfaChallengeDTO)","description":"The multi-factor authentication (MFA) challenge to complete before issuing a token.","optional":true,"defaultValue":"","expandable":false,"children":[{"name":"id","type":"`string`","description":"The multi-factor authentication (MFA) challenge's ID.","optional":false,"defaultValue":"","expandable":false,"children":[]},{"name":"auth_identity_id","type":"`string`","description":"The ID of the authentication identity being challenged.","optional":true,"defaultValue":"","expandable":false,"children":[]},{"name":"auth_identity","type":"[AuthIdentityDTO](/references/auth/interfaces/auth.AuthIdentityDTO)","description":"The authentication identity being challenged.","optional":true,"defaultValue":"","expandable":true,"children":[]},{"name":"auth_provider","type":"`string` \\| `null`","description":"The authentication provider handling the challenge.","optional":true,"defaultValue":"","expandable":false,"children":[]},{"name":"methods","type":"[AuthMfaChallengeMethod](/references/auth/types/auth.AuthMfaChallengeMethod)[]","description":"Available methods for completing this challenge.","optional":false,"defaultValue":"","expandable":false,"children":[]},{"name":"expires_at","type":"`Date`","description":"When the challenge expires.","optional":false,"defaultValue":"","expandable":false,"children":[]},{"name":"attempts","type":"`number`","description":"Number of verification attempts made.","optional":false,"defaultValue":"","expandable":false,"children":[]},{"name":"max_attempts","type":"`number`","description":"Maximum verification attempts allowed.","optional":false,"defaultValue":"","expandable":false,"children":[]},{"name":"completed_at","type":"`Date` \\| `null`","description":"When the challenge was completed.","optional":true,"defaultValue":"","expandable":false,"children":[]},{"name":"metadata","type":"`Record<string, unknown>` \\| `null`","description":"Additional metadata for the challenge.","optional":true,"defaultValue":"","expandable":false,"children":[]}]},{"name":"error","type":"`string`","description":"If an error occurs during the authentication process,\nwhether within the Auth Module or a third-party provider,\nthe error message is set in this field.","optional":true,"defaultValue":"","expandable":false,"children":[]},{"name":"location","type":"`string`","description":"The URL to redirect to for further authentication action\nwith a third-party provider. This takes precedence before\nthe `success` field.\n\nSo, after checking that authentication is successful,\nyou should check whether this field is defined and, if so, redirect to the\nspecified location.","optional":true,"defaultValue":"","expandable":false,"children":[]}]}]},{"kind":"heading","level":3,"text":"validateCallback","id":"validatecallback"},{"kind":"markdown","html":"This method validates the callback of an authentication request.\n\nIn an authentication flow that requires performing an action with a third-party service, such as login\nwith a social account, the [authenticate](/references/auth/provider#authenticate) method is called first.\n\nThen, the third-party service redirects to a frontend URL passing it a `code` query parameter.\nThe frontend should then send a request to the Medusa application's validate callback API route, passing it the code.\nThat route uses this method to verify the callback's code.\n\nIf the callback is verified successfully, the provider creates an auth identity for the user, or updates the auth identity's user information.\n\nIn the auth identity, use the following properties to store additional data:\n\n- `provider_metadata`: Store metadata useful for the provider, such as a password hash.\n- `user_metadata`: Store metadata of the user's details. For example, if the third-party service returns the user's information such as email\nor name, you store this data in this property.\n\nRelated Guide: [Learn about the different authentication flows in Medusa](https://docs.medusajs.com/resources/commerce-modules/auth/authentication-route)."},{"kind":"heading","level":4,"text":"Example","id":"example-6"},{"kind":"markdown","html":"```ts\nimport {\n AuthIdentityProviderService,\n AuthenticationInput,\n AuthenticationResponse\n} from \"@medusajs/framework/types\"\n// ...\n\nclass MyAuthProviderService extends AbstractAuthModuleProvider {\n // ...\n async validateCallback(\n data: AuthenticationInput,\n authIdentityProviderService: AuthIdentityProviderService\n ): Promise<AuthenticationResponse> {\n const isAuthenticated = false\n\n // optional, useful for third-party providers that require a redirect URL\n // to continue the authentication flow\n // const stateKey = data.query?.state as string\n // const state = await authIdentityService.getState(stateKey)\n // if (!state) {\n // return { success: false, error: \"No state provided, or session expired\" }\n // }\n // // use callback URL with the third-party service\n // const callbackUrl = state.callback_url\n // TODO perform custom logic to authenticate the user\n // ...\n\n if (!isAuthenticated) {\n // if the authentication didn't succeed, return\n // an object of the following format\n return {\n success: false,\n error: \"Something went wrong\"\n }\n }\n\n // authentication is successful, create an auth identity\n // if doesn't exist\n let authIdentity\n\n try {\n authIdentity = await authIdentityProviderService.retrieve({\n entity_id: data.body.email, // email or some ID\n provider: this.provider\n })\n } catch (e) {\n // The auth identity doesn't exist so create it\n authIdentity = await authIdentityProviderService.create({\n entity_id: data.body.email, // email or some ID\n provider: this.provider,\n provider_metadata: {\n // can include password or any other relevant information\n },\n user_metadata: {\n // can include data retrieved from the third-party service\n }\n })\n }\n\n return {\n success: true,\n authIdentity\n }\n }\n}\n```"},{"kind":"heading","level":4,"text":"Parameters","id":"validatecallback-parameters"},{"kind":"typeList","sectionTitle":"validateCallback","types":[{"name":"data","type":"[AuthenticationInput](/references/types/interfaces/types.AuthenticationInput)","description":"The details of the authentication request.","optional":false,"defaultValue":"","expandable":false,"children":[{"name":"url","type":"`string`","description":"URL of the incoming authentication request.","optional":true,"defaultValue":"","expandable":false,"children":[]},{"name":"headers","type":"`Record<string, string>`","description":"Headers of incoming authentication request.","optional":true,"defaultValue":"","expandable":false,"children":[]},{"name":"query","type":"`Record<string, string>`","description":"Query params of the incoming authentication request.","optional":true,"defaultValue":"","expandable":false,"children":[]},{"name":"body","type":"`Record<string, string>`","description":"Body of the incoming authentication request.\n\nOne of the arguments that is suggested to be treated in a standard manner is a `callback_url` field.\nThe field specifies where the user is redirected to after a successful authentication in the case of Oauth auhentication.\nIf not passed, the provider will fallback to the callback\\_url provided in the provider options.","optional":true,"defaultValue":"","expandable":false,"children":[]},{"name":"protocol","type":"`string`","description":"Protocol of the incoming authentication request (For example, `https`).","optional":true,"defaultValue":"","expandable":false,"children":[]}]},{"name":"authIdentityProviderService","type":"[AuthIdentityProviderService](/references/types/interfaces/types.AuthIdentityProviderService)","description":"The service used to retrieve or\ncreate an auth identity. It has two methods: `create` to create an auth identity,\nand `retrieve` to retrieve an auth identity. When you authenticate the user, you can create an auth identity\nusing this service.","optional":false,"defaultValue":"","expandable":false,"children":[{"name":"retrieve","type":"(`selector`: ``{ entity_id: string }``) => Promise&#60;[AuthIdentityDTO](/references/auth/interfaces/auth.AuthIdentityDTO)&#62;","description":"","optional":false,"defaultValue":"","expandable":false,"children":[]},{"name":"create","type":"(`data`: ``{ entity_id: string ; provider_metadata?: Record&#60;string, unknown&#62; ; user_metadata?: Record&#60;string, unknown&#62; }``) => Promise&#60;[AuthIdentityDTO](/references/auth/interfaces/auth.AuthIdentityDTO)&#62;","description":"","optional":false,"defaultValue":"","expandable":false,"children":[]},{"name":"update","type":"(`entity_id`: `string`, `data`: ``{ provider_metadata?: Record&#60;string, unknown&#62; ; user_metadata?: Record&#60;string, unknown&#62; }``) => Promise&#60;[AuthIdentityDTO](/references/auth/interfaces/auth.AuthIdentityDTO)&#62;","description":"","optional":false,"defaultValue":"","expandable":false,"children":[]},{"name":"setState","type":"(`key`: `string`, `value`: `Record<string, unknown>`, `ttlSeconds?`: `number`) => Promise&#60;void&#62;","description":"","optional":false,"defaultValue":"","expandable":false,"children":[]},{"name":"getState","type":"(`key`: `string`) => Promise&#60;null \\| Record&#60;string, unknown&#62;&#62;","description":"","optional":false,"defaultValue":"","expandable":false,"children":[]}]}]},{"kind":"heading","level":4,"text":"Returns","id":"validatecallback-returns"},{"kind":"typeList","sectionTitle":"validateCallback","types":[{"name":"Promise","type":"Promise&#60;[AuthenticationResponse](/references/types/interfaces/types.AuthenticationResponse)&#62;","optional":false,"defaultValue":"","description":"The authentication response.","expandable":false,"children":[{"name":"success","type":"`boolean`","description":"Whether the authentication was successful.","optional":false,"defaultValue":"","expandable":false,"children":[]},{"name":"authIdentity","type":"[AuthIdentityDTO](/references/auth/interfaces/auth.AuthIdentityDTO)","description":"The authenticated user's details.","optional":true,"defaultValue":"","expandable":false,"children":[{"name":"id","type":"`string`","description":"The ID of the auth identity.","optional":false,"defaultValue":"","expandable":false,"children":[]},{"name":"provider_identities","type":"[ProviderIdentityDTO](/references/auth/interfaces/auth.ProviderIdentityDTO)[]","description":"The list of provider identities linked to the auth identity.","optional":true,"defaultValue":"","expandable":false,"children":[]},{"name":"app_metadata","type":"`Record<string, unknown>`","description":"Holds information related to the actor IDs tied to the auth identity.","optional":true,"defaultValue":"","expandable":false,"children":[]}]},{"name":"mfaChallenge","type":"[AuthMfaChallengeDTO](/references/auth/types/auth.AuthMfaChallengeDTO)","description":"The multi-factor authentication (MFA) challenge to complete before issuing a token.","optional":true,"defaultValue":"","expandable":false,"children":[{"name":"id","type":"`string`","description":"The multi-factor authentication (MFA) challenge's ID.","optional":false,"defaultValue":"","expandable":false,"children":[]},{"name":"auth_identity_id","type":"`string`","description":"The ID of the authentication identity being challenged.","optional":true,"defaultValue":"","expandable":false,"children":[]},{"name":"auth_identity","type":"[AuthIdentityDTO](/references/auth/interfaces/auth.AuthIdentityDTO)","description":"The authentication identity being challenged.","optional":true,"defaultValue":"","expandable":true,"children":[]},{"name":"auth_provider","type":"`string` \\| `null`","description":"The authentication provider handling the challenge.","optional":true,"defaultValue":"","expandable":false,"children":[]},{"name":"methods","type":"[AuthMfaChallengeMethod](/references/auth/types/auth.AuthMfaChallengeMethod)[]","description":"Available methods for completing this challenge.","optional":false,"defaultValue":"","expandable":false,"children":[]},{"name":"expires_at","type":"`Date`","description":"When the challenge expires.","optional":false,"defaultValue":"","expandable":false,"children":[]},{"name":"attempts","type":"`number`","description":"Number of verification attempts made.","optional":false,"defaultValue":"","expandable":false,"children":[]},{"name":"max_attempts","type":"`number`","description":"Maximum verification attempts allowed.","optional":false,"defaultValue":"","expandable":false,"children":[]},{"name":"completed_at","type":"`Date` \\| `null`","description":"When the challenge was completed.","optional":true,"defaultValue":"","expandable":false,"children":[]},{"name":"metadata","type":"`Record<string, unknown>` \\| `null`","description":"Additional metadata for the challenge.","optional":true,"defaultValue":"","expandable":false,"children":[]}]},{"name":"error","type":"`string`","description":"If an error occurs during the authentication process,\nwhether within the Auth Module or a third-party provider,\nthe error message is set in this field.","optional":true,"defaultValue":"","expandable":false,"children":[]},{"name":"location","type":"`string`","description":"The URL to redirect to for further authentication action\nwith a third-party provider. This takes precedence before\nthe `success` field.\n\nSo, after checking that authentication is successful,\nyou should check whether this field is defined and, if so, redirect to the\nspecified location.","optional":true,"defaultValue":"","expandable":false,"children":[]}]}]},{"kind":"heading","level":3,"text":"validateOptions","id":"validateoptions"},{"kind":"markdown","html":"This method validates the options of the provider set in `medusa-config.ts`.\nImplementing this method is optional. It's useful if your provider requires custom validation.\n\nIf the options aren't valid, throw an error."},{"kind":"heading","level":4,"text":"Example","id":"example-7"},{"kind":"markdown","html":"```ts\nclass MyAuthProviderService extends AbstractAuthModuleProvider {\n static validateOptions(options: Record<any, any>) {\n if (!options.apiKey) {\n throw new MedusaError(\n MedusaError.Types.INVALID_DATA,\n \"API key is required in the provider's options.\"\n )\n }\n }\n // ...\n}\n```"},{"kind":"heading","level":4,"text":"Parameters","id":"validateoptions-parameters"},{"kind":"typeList","sectionTitle":"validateOptions","types":[{"name":"options","type":"`Record<any, any>`","description":"The provider's options.","optional":false,"defaultValue":"","expandable":false,"children":[]}]},{"kind":"markdown","html":"---"},{"kind":"heading","level":2,"text":"3. Create Module Provider Definition File","id":"3-create-module-provider-definition-file"},{"kind":"markdown","html":"Create the file `src/modules/my-auth/index.ts` with the following content:\n\n```ts title=\"src/modules/my-auth/index.ts\"\nimport MyAuthProviderService from \"./service\"\nimport { \n ModuleProvider, \n Modules\n} from \"@medusajs/framework/utils\"\n\nexport default ModuleProvider(Modules.AUTH, {\n services: [MyAuthProviderService],\n})\n```\n\nThis exports the module provider's definition, indicating that the `MyAuthProviderService` is the module provider's service."},{"kind":"note","variant":"note","title":"Tip","html":"A auth module provider can have export multiple provider services, where each are registered as a separate auth provider."},{"kind":"markdown","html":"---"},{"kind":"heading","level":2,"text":"4. Use Module Provider","id":"4-use-module-provider"},{"kind":"markdown","html":"To use your Auth Module Provider, add it to the `providers` array of the Auth Module in `medusa-config.ts`:\n\n```ts title=\"medusa-config.ts\"\nimport { Modules, ContainerRegistrationKeys } from \"@medusajs/framework/utils\"\n\nmodule.exports = defineConfig({\n // ...\n modules: [\n {\n resolve: \"@medusajs/medusa/auth\",\n dependencies: [Modules.CACHE, ContainerRegistrationKeys.LOGGER],\n options: {\n mfa: {\n encryption_key: process.env.AUTH_MFA_ENCRYPTION_KEY,\n },\n providers: [\n // default provider\n {\n resolve: \"@medusajs/medusa/auth-emailpass\",\n id: \"emailpass\",\n },\n {\n // if module provider is in a plugin, use `plugin-name/providers/my-auth`\n resolve: \"./src/modules/my-auth\",\n id: \"my-auth\",\n options: {\n // provider options...\n },\n },\n ],\n },\n },\n ]\n})\n```\n\n\n---"},{"kind":"heading","level":2,"text":"5. Test it Out","id":"5-test-it-out"},{"kind":"markdown","html":"To test out your Authentication Module Provider, use any of the [Authentication Routes](https://docs.medusajs.com/resources/commerce-modules/auth/authentication-route), using your provider's ID as a path parameter.\n\nFor example, to get a registration token for a customer, send a `POST` request to `/auth/customer/my-auth/register` replacing `my-auth` with your Authentication Module Provider's ID:\n\n```bash\ncurl -X POST http://localhost:9000/auth/customer/my-auth/register\n-H 'Content-Type: application/json' --data-raw '{\n \"email\": \"Whitney_Schultz@gmail.com\",\n \"password\": \"supersecret\"\n}'\n```\n\nChange the request body to pass the data required for your Authentication Module Provider to register the customer.\n\nIf registration is successful, the response will have a `token` property.\n\nYou can then use the token to create a customer by sending a request to the [Create Customer API route](https://docs.medusajs.com/api/store/customers/register-customer)."}]}