1 ---
2 sidebar_label: "Link Auth Provider to Existing Actor"
3 tags:
4 - auth
5 - how to
6 - server
7 ---
8
9 import { Prerequisites } from "docs-ui"
10
11 export const metadata = {
12 title: `Link an Additional Auth Provider to an Existing Actor`,
13 }
14
15 # {metadata.title}
16
17 In this guide, you'll learn how to allow an existing actor (such as a customer) to authenticate with an additional authentication provider. This is useful when you want to let a customer who registered with the Emailpass provider also log in with Google or a Magic Link, for example.
18
19 <Prerequisites
20 items={[
21 {
22 text: "Existing user of the actor.",
23 },
24 {
25 text: "Custom authentication provider registered for the actor type.",
26 link: "/references/auth/provider",
27 },
28 ]}
29 />
30
31 ## Why an Additional Provider Doesn't Resolve to the Actor
32
33 Each authentication provider creates its own [auth identity](../auth-identity-and-actor-types/page.mdx) for an actor. The auth identity holds an `app_metadata` property that associates it with an actor, such as a customer, using the key `{actor_type}_id`:
34
35 ```json
36 {
37 "app_metadata": {
38 "customer_id": "cus_123"
39 }
40 }
41 ```
42
43 When an actor registers with the Emailpass provider, its auth identity has the `{actor_type}_id` key set to the associated actor's ID. So, authenticating with Emailpass resolves to that actor.
44
45 However, when the same actor authenticates with a different provider for the first time, that provider creates a separate auth identity. This new auth identity has an empty `app_metadata`, so it isn't associated with any actor yet:
46
47 ```json
48 {
49 "app_metadata": {}
50 }
51 ```
52
53 Since the new auth identity isn't associated with an actor, Medusa treats the authentication as if a new actor is registering, rather than an existing actor logging in. So, authenticating with the new provider returns a token that has an `auth_identity_id` but no `actor_id`. As a result, requests to protected routes, such as `GET /store/customers/me`, are rejected with a `401` error.
54
55 To allow the new provider to resolve to the existing customer, you must set the `{actor_type}_id` key of the new auth identity's `app_metadata` to the existing actor's ID. You do that with the [setAuthAppMetadataStep](/references/medusa-workflows/steps/setAuthAppMetadataStep).
56
57 <Note>
58
59 The rest of this guide uses the `customer` actor type as an example, but the same approach applies to admin users and [custom actor types](../create-actor-type/page.mdx). Replace `customer` with the relevant actor type.
60
61 </Note>
62
63 ---
64
65 ## Step 1: Create the Linking Workflow
66
67 Create a [workflow](!docs!/learn/fundamentals/workflows) that finds the existing customer matching the new auth identity and associates the auth identity with that customer.
68
69 Create the file `src/workflows/link-customer-identity.ts` with the following content:
70
71 export const workflowHighlights = [
72 ["23", "getIdentityEmailStep", "Extract and validate the email from the provider identity."],
73 ["63", "useQueryGraphStep", "Retrieve the auth identity with its provider identity."],
74 ["73", "useQueryGraphStep", "Find the existing customer by that email."],
75 ["79", "get-customer", "Name the second query step to avoid a duplicate step ID."],
76 ["95", "setAuthAppMetadataStep", "Associate the auth identity with the existing customer."],
77 ]
78
79 ```ts title="src/workflows/link-customer-identity.ts" highlights={workflowHighlights}
80 import {
81 createWorkflow,
82 createStep,
83 StepResponse,
84 transform,
85 WorkflowResponse,
86 } from "@medusajs/framework/workflows-sdk"
87 import {
88 setAuthAppMetadataStep,
89 useQueryGraphStep,
90 } from "@medusajs/medusa/core-flows"
91 import { MedusaError } from "@medusajs/framework/utils"
92 import { CustomerDTO } from "@medusajs/framework/types"
93
94 type WorkflowInput = {
95 auth_identity_id: string
96 }
97
98 type AuthIdentityData = {
99 provider_identities?: { entity_id: string }[]
100 }[]
101
102 const getIdentityEmailStep = createStep(
103 "get-identity-email",
104 ({ authIdentities }: { authIdentities: AuthIdentityData }) => {
105 const email =
106 authIdentities[0]?.provider_identities?.[0]?.entity_id
107
108 if (!email) {
109 throw new MedusaError(
110 MedusaError.Types.INVALID_DATA,
111 "Couldn't determine the identity's email."
112 )
113 }
114
115 return new StepResponse(email)
116 }
117 )
118
119 const validateCustomerExistsStep = createStep(
120 "validate-customer-exists",
121 ({
122 customers,
123 email,
124 }: {
125 customers: CustomerDTO[]
126 email: string
127 }) => {
128 if (!customers.length) {
129 throw new MedusaError(
130 MedusaError.Types.NOT_FOUND,
131 `No customer found with email ${email}`
132 )
133 }
134
135 return new StepResponse(customers[0])
136 }
137 )
138
139 export const linkCustomerIdentityWorkflow = createWorkflow(
140 "link-customer-identity",
141 (input: WorkflowInput) => {
142 const { data: authIdentities } = useQueryGraphStep({
143 entity: "auth_identity",
144 fields: ["provider_identities.entity_id"],
145 filters: {
146 id: input.auth_identity_id,
147 },
148 })
149
150 const email = getIdentityEmailStep({ authIdentities })
151
152 const { data: customers } = useQueryGraphStep({
153 entity: "customer",
154 fields: ["id"],
155 filters: {
156 email,
157 },
158 }).config({ name: "get-customer" })
159
160 const customer = validateCustomerExistsStep({
161 customers,
162 email,
163 })
164
165 const stepInput = transform(
166 { input, customer },
167 ({ input, customer }) => ({
168 authIdentityId: input.auth_identity_id,
169 actorType: "customer",
170 value: customer.id,
171 })
172 )
173
174 setAuthAppMetadataStep(stepInput)
175
176 return new WorkflowResponse({
177 customer_id: customer.id,
178 })
179 }
180 )
181 ```
182
183 The workflow accepts the ID of the auth identity created by the new provider. Then, it:
184
185 1. Retrieves the auth identity with its provider identity using [useQueryGraphStep](/references/helper-steps/useQueryGraphStep). The provider identity's `entity_id` holds the identifier the provider authenticated the customer with, such as the email.
186 2. Extracts and validates the email using the `getIdentityEmailStep`, throwing an error if the identity has no email.
187 3. Finds the existing customer by that email using `useQueryGraphStep` again. Adjust the `filters` if your provider identifies customers by a property other than the email.
188 4. Validates that a customer was found using the `validateCustomerExistsStep`, throwing an error if not.
189 5. Prepares the step's input using `transform`, then associates the new auth identity with the existing customer using the `setAuthAppMetadataStep`.
190
191 <Note>
192
193 Since you call `useQueryGraphStep` twice in the same workflow, you must set a unique name for the second call with `.config({ name: "get-customer" })`. Otherwise, the workflow throws an error for having two steps with the same ID.
194
195 </Note>
196
197 <Note type="warning">
198
199 Derive the email from the authenticated auth identity, as shown above, rather than accepting it in the request body. Otherwise, a customer could link their auth identity to another customer's account by passing a different email.
200
201 </Note>
202
203 <Note title="Tip">
204
205 The `setAuthAppMetadataStep` throws an error if the auth identity is already associated with the same actor type. So, this workflow only succeeds for a new auth identity that isn't linked to a customer yet.
206
207 </Note>
208
209 ---
210
211 ## Step 2: Create the Linking API Route
212
213 Next, create an [API route](!docs!/learn/fundamentals/api-routes) that executes the workflow after the customer authenticates with the new provider.
214
215 Create the file `src/api/auth/link/route.ts` with the following content:
216
217 export const routeHighlights = [
218 ["13", "actor_id", "Reject the request if the identity is already linked to a customer."],
219 ["23", "auth_identity_id", "Pass the authenticated identity's ID to the workflow."],
220 ]
221
222 ```ts title="src/api/auth/link/route.ts" highlights={routeHighlights}
223 import {
224 AuthenticatedMedusaRequest,
225 MedusaResponse,
226 } from "@medusajs/framework/http"
227 import { MedusaError } from "@medusajs/framework/utils"
228 import { linkCustomerIdentityWorkflow } from "../../../workflows/link-customer-identity"
229
230 export const POST = async (
231 req: AuthenticatedMedusaRequest,
232 res: MedusaResponse
233 ) => {
234 // The auth identity is already linked to a customer.
235 if (req.auth_context.actor_id) {
236 throw new MedusaError(
237 MedusaError.Types.INVALID_DATA,
238 "Auth identity is already linked to a customer."
239 )
240 }
241
242 const { result } = await linkCustomerIdentityWorkflow(req.scope)
243 .run({
244 input: {
245 auth_identity_id: req.auth_context.auth_identity_id,
246 },
247 })
248
249 res.status(200).json(result)
250 }
251 ```
252
253 In the API route, you:
254
255 1. Reject the request if the auth identity is already linked to a customer, indicated by the `actor_id` property in the request's `auth_context`.
256 2. Execute the `linkCustomerIdentityWorkflow`, passing it the authenticated auth identity's ID from the request's `auth_context`.
257
258 Refer to the [Auth Flow with Routes](../authentication-route/page.mdx) guide to learn how the `auth_context` is set on the request.
259
260 ---
261
262 ## Step 3: Protect the API Route
263
264 The customer hasn't been linked to an actor yet when they access the linking route, so you must allow unregistered auth identities to access it.
265
266 To do that, apply the [authenticate middleware](!docs!/learn/fundamentals/api-routes/protected-routes) to the route with the `allowUnregistered` option enabled.
267
268 Create the file `src/api/middlewares.ts` with the following content, or add the route to your existing middlewares:
269
270 export const middlewareHighlights = [
271 ["13", "allowUnregistered", "Allow auth identities not linked to a customer to access the route."],
272 ]
273
274 ```ts title="src/api/middlewares.ts" highlights={middlewareHighlights}
275 import {
276 defineMiddlewares,
277 authenticate,
278 } from "@medusajs/framework/http"
279
280 export default defineMiddlewares({
281 routes: [
282 {
283 matcher: "/auth/link",
284 method: "POST",
285 middlewares: [
286 authenticate("customer", ["bearer"], {
287 allowUnregistered: true,
288 }),
289 ],
290 },
291 ],
292 })
293 ```
294
295 This protects the `/auth/link` route so that only auth identities of the `customer` actor type, including unregistered ones, can access it.
296
297 ---
298
299 ## Test the Linking Flow
300
301 To link the new provider to an existing customer:
302
303 1. Authenticate the customer with the new provider to obtain a token. Refer to the [Auth Flow with Routes](../authentication-route/page.mdx) guide for the authentication steps.
304 2. Send a `POST` request to `/auth/link` with the token in the `Authorization` header:
305
306 ```bash
307 curl -X POST http://localhost:9000/auth/link \
308 -H "Authorization: Bearer {token}"
309 ```
310
311 Afterwards, the customer can authenticate with the new provider and their token will resolve to the existing customer.
312
313 <Note title="Warning" type="warning">
314
315 Only link providers that verify the customer owns the identity, such as an email the provider confirmed. Otherwise, a customer could link their auth identity to another customer's account and gain access to it.
316
317 </Note>
318
319 ---
320
321 ## Unlink a Provider
322
323 To remove the association between an auth identity and a customer, such as when a customer disconnects a provider, pass `null` as the `value` to the `setAuthAppMetadataStep`:
324
325 ```ts
326 setAuthAppMetadataStep({
327 authIdentityId: "au_123",
328 actorType: "customer",
329 value: null,
330 })
331 ```
332
333 Learn more about the `setAuthAppMetadataStep` in the [setAuthAppMetadataWorkflow reference](/references/medusa-workflows/setAuthAppMetadataWorkflow).