-
I am aware of the auth plugin and of the recently merged bearer-token authentication feature. But more generally, how should I go about having a custom code to authenticate a request to the api ? For instance, I'd like to use a third party auth provider (like clerkjs or even a custom one based on ory) so that my token can be accepted by my ecommerce solution as well as my custom product API that resides on a different server. How would you go about that ? Is authentication easily customizable ? Thanks ! |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments 10 replies
-
This simplest method is to just modify the authService. Replace authenticate function to modify user auth and authenticateCustomer function to modify customer auth. With this method, the initial authentication can be offloaded via those functions, but sessions and tokens and everything else stays exactly the same. Another approach is to implement auth directly in your app using something like Cognito or clerk or auth0 or whatever. In this case, you will need to change the middleware functions that are attached to the admin and store api routes for authentication. I'm most familiar with Cognito. What I have done experimentally, and what I plan to switch to soon, is use Cognito fully in the storefront app. Handle session in the storefront app. This avoids having to go to the Medusa server on every page load. Calls to Medusa are made only from the storefront app (not the user browser). This is key for this setup to make sense. When the app does need to interact with medusa, it sends the id token from cognito that is stored in user session (which is store in Redis). That id token is verified with Medusa by using the aws-jwt-verifier package on the route middleware. |
Beta Was this translation helpful? Give feedback.
-
PR here: #5262 |
Beta Was this translation helpful? Give feedback.
-
I've come up with a solution by overriding the passport strategy in Medusa loaders.
|
Beta Was this translation helpful? Give feedback.
The service that handles auth requests is here: https://github.com/medusajs/medusa/blob/2b91049f58b2bd70cbee53e1ace7d36f59da6fa4/packages/medusa/src/services/auth.ts
The authenticate method handles user auth. (users in medusa means admin users, aka anything on the /admin routes). The authenticateCustomer method handles customer auth. (meaning, on the /store routes that require auth, which is not all of them)
These methods get invoked via middleware attached to the routes. These are here: https://github.com/medusajs/medusa/blob/2b91049f58b2bd70cbee53e1ace7d36f59da6fa4/packages/medusa/src/api/middlewares/authenticate-customer.ts
And here: https://github.com/medusajs/medusa/blob/2b91049f58b2…