Raw
1 ---
2 sidebar_label: "Authentication Flows"
3 ---
4
5 export const metadata = {
6 title: `Authentication Flows with the Auth Main Service`,
7 }
8
9 # {metadata.title}
10
11 In this guide, you'll learn how to use the methods of the Auth Module's service to implement authentication flows and reset a user's password.
12
13 <Note>
14
15 This guide is only recommended for complex cases, where you may need to heavily customize the authentication flows and need to use the Auth Module's service methods directly. For most use cases, you should use the [auth routes](../authentication-route/page.mdx) instead.
16
17 </Note>
18
19 ## Authentication Methods
20
21 ### Register
22
23 The [register method of the Auth Module's service](/references/auth/register) creates an auth identity that can be authenticated later.
24
25 For example:
26
27 ```ts
28 const data = await authModuleService.register(
29 "emailpass",
30 // passed to auth provider
31 {
32 // pass data from request parameters, such as
33 url: "example.com",
34 headers: req.headers,
35 query: req.query,
36 // pass in the body the data necessary for the authentication provider
37 // to register the user, such as email and password
38 body: {
39 email: "user@example.com",
40 password: "supersecret",
41 },
42 protocol: req.protocol,
43 }
44 )
45 ```
46
47 This method calls the `register` method of the provider specified in the first parameter. The method passes the second parameter as input for the provider, and returns its data.
48
49 Based on the returned data, you can determine if the registration was successful, and if any further action is required to complete the registration. This is explained further in the auth flows sections below.
50
51 ### Authenticate
52
53 To authenticate or log in a user, you use the [authenticate method of the Auth Module's service](/references/auth/authenticate). For example:
54
55 ```ts
56 const data = await authModuleService.authenticate(
57 "emailpass",
58 // passed to auth provider
59 {
60 // pass data from request parameters, such as
61 url: "example.com",
62 headers: req.headers,
63 query: req.query,
64 // pass in the body the data necessary for the authentication provider
65 // to authenticate the user, such as email and password
66 body: {
67 email: "user@example.com",
68 password: "supersecret",
69 },
70 protocol: req.protocol,
71 }
72 )
73 ```
74
75 This method calls the `authenticate` method of the provider specified in the first parameter. The method passes the second parameter as input for the provider, and returns its data.
76
77 Based on the returned data, you can determine if the authentication was successful, and if any further action is required to complete the authentication. This is explained further in the auth flows sections below.
78
79 ---
80
81 ## Auth Flow 1: Basic Authentication
82
83 The basic authentication flow requires first using the `register` method, then the `authenticate` method.
84
85 ![Diagram showcasing the basic authentication flow](https://res.cloudinary.com/dza7lstvk/image/upload/v1711373749/Medusa%20Resources/basic-auth_lgpqsj.jpg)
86
87 ### Step 1: Register User
88
89 ```ts
90 const {
91 success,
92 authIdentity,
93 error,
94 } = await authModuleService.register(
95 "emailpass",
96 // passed to auth provider
97 {
98 // pass data from request parameters, such as
99 url: "example.com",
100 headers: req.headers,
101 query: req.query,
102 // pass in the body the data necessary for the authentication provider
103 // to register the user, such as email and password
104 body: {
105 email: "user@example.com",
106 password: "supersecret",
107 },
108 protocol: req.protocol,
109 }
110 )
111
112 if (error) {
113 // registration failed
114 // TODO return an error
115 return
116 }
117 ```
118
119 If the `register` method returns an `error` property, the registration failed, and you can return an error message to the user.
120
121 Otherwise, if the `success` property is `true`, the registration was successful, and the user's authentication details are available within the `authIdentity` object.
122
123 <Note>
124
125 Check out the [AuthIdentity](/references/auth/models/AuthIdentity) reference for the received properties in `authIdentity`.
126
127 </Note>
128
129 #### Registering Auth Identities with Same Identifier
130
131 If an auth identity, such as a `customer`, tries to register with an email of another auth identity, the `register` method returns an error. This can happen either if another customer is using the same email, or an admin user has the same email.
132
133 There are two ways to handle this:
134
135 - Consider the customer authenticated if the `authenticate` method validates that the email and password are correct. This allows admin users, for example, to authenticate as customers.
136 - Return an error message to the customer, informing them that the email is already in use.
137
138 ### Step 2: Authenticate User
139
140 ```ts
141 // later (can be another route for login)
142 const {
143 success,
144 authIdentity,
145 location,
146 } = await authModuleService.authenticate(
147 "emailpass",
148 // passed to auth provider
149 {
150 // pass data from request parameters, such as
151 url: "example.com",
152 headers: req.headers,
153 query: req.query,
154 // pass in the body the data necessary for the authentication provider
155 // to authenticate the user, such as email and password
156 body: {
157 email: "user@example.com",
158 password: "supersecret",
159 },
160 protocol: req.protocol,
161 }
162 )
163
164 if (success && !location) {
165 // user is authenticated
166 }
167 ```
168
169 If the `authenticate` method returns a `success` property that is `true`, and the `location` property is not set, the user is authenticated successfully. Their authentication details are available within the `authIdentity` object.
170
171 Otherwise, if the `location` property is set, you must follow the [third-party service authentication flow](#auth-flow-2-third-party-service-authentication) to complete the authentication.
172
173 ---
174
175 ## Auth Flow 2: Third-Party Service Authentication
176
177 The third-party service authentication method requires using the `authenticate` method first:
178
179 ```ts
180 const { success, authIdentity, location } = await authModuleService.authenticate(
181 "google",
182 // passed to auth provider
183 {
184 // pass data from request parameters, such as
185 url: "example.com",
186 headers: req.headers,
187 query: req.query,
188 body: req.body,
189 protocol: req.protocol,
190 }
191 )
192
193 if (location) {
194 // return the location for the frontend to redirect to
195 }
196
197 if (!success) {
198 // authentication failed
199 }
200
201 // authentication successful
202 ```
203
204 If the `authenticate` method returns a `location` property, the authentication process requires the user to perform an action with a third-party service. So, you return the `location` to the frontend or client to redirect to that URL.
205
206 For example, when using the `google` provider, the `location` is the URL that the user must be redirected to in order to log in with their Google account.
207
208 ![Diagram showcasing the first part of the third-party authentication flow](https://res.cloudinary.com/dza7lstvk/image/upload/v1711374847/Medusa%20Resources/third-party-auth-1_enyedy.jpg)
209
210 ### Overriding Callback URL
211
212 The Google and GitHub providers allow you to override their `callbackUrl` option during authentication. This is useful when you redirect the user after authentication to a URL based on their actor type. For example, you redirect admin users and customers to different pages.
213
214 ```ts
215 const {
216 success,
217 authIdentity,
218 location,
219 } = await authModuleService.authenticate(
220 "google",
221 // passed to auth provider
222 {
223 // ...
224 callback_url: "example.com",
225 }
226 )
227 ```
228
229 ### validateCallback
230
231 Providers handling this authentication flow must implement the `validateCallback` method. It implements the logic to validate the authentication with the third-party service.
232
233 So, once the user performs the required action with the third-party service (for example, log in with Google), the frontend must redirect to an API route that uses the [validateCallback method of the Auth Module's service](/references/auth/validateCallback).
234
235 The method calls the specified provider’s `validateCallback` method passing it the authentication details it received in the second parameter:
236
237 ```ts
238 const { success, authIdentity } = await authModuleService.validateCallback(
239 "google",
240 // passed to auth provider
241 {
242 // request data, such as
243 url,
244 headers,
245 query,
246 body,
247 protocol,
248 }
249 )
250
251 if (success) {
252 // authentication succeeded
253 }
254 ```
255
256 <Note title="Tip">
257
258 For providers like Google, the `query` object contains the query parameters from the original callback URL, such as the `code` and `state` parameters.
259
260 </Note>
261
262 If the returned `success` property is `true`, the authentication with the third-party provider was successful.
263
264 ![Diagram showcasing the second part of the third-party authentication flow](https://res.cloudinary.com/dza7lstvk/image/upload/v1711375123/Medusa%20Resources/third-party-auth-2_kmjxju.jpg)
265
266 ---
267
268 ## Reset Password
269
270 To update a user's password or other authentication details, use the [updateProvider method of the Auth Module's service](/references/auth/updateProvider). It calls the `update` method of the specified authentication provider.
271
272 For example:
273
274 ```ts
275 const { success } = await authModuleService.updateProvider(
276 "emailpass",
277 // passed to the auth provider
278 {
279 entity_id: "user@example.com",
280 password: "supersecret",
281 }
282 )
283
284 if (success) {
285 // password reset successfully
286 }
287 ```
288
289 The method accepts as a first parameter the ID of the provider, and as a second parameter the data necessary to reset the password.
290
291 In the example above, you use the `emailpass` provider, so you have to pass an object having `entity_id` and `password` properties.
292
293 If the returned `success` property is `true`, the password has been reset successfully.