guides
Guide

How to Integrate Magic’s Passwordless Authentication With AWS Amplify

Magic Staff · December 27, 2021
info

This guide is a guest post by Tomoaki Imai, CTO at Knot, Inc, as part of our Guest Author program.

AWS Amplify is a fully managed framework that lets developers quickly build full-stack web applications on AWS. It has built-in authentication support, which uses Amazon Cognito under the hood. Because Amplify meant to use its tools as much as possible, you need to make a few customizations to your codebase if you want to introduce passwordless authentication.

In this article, I will share a way to integrate Magic into your Amplify web application if you want to jump into the code first, head over to this link.

https://github.com/tomoima525/magic-amplify-authentication

#Overall architecture

Here's the overall authentication flow in a nutshell. Let me briefly explain.

  • User inputs an email address and requests credentials from Magic through Email
  • Using didtoken and issuer id received as a callback, the client application calls Lambda function through API for Authentication
  • Backend Lambda function accesses Cognito Federated Identity and returns OpenID token(Token and Identity) to the client-side
  • The client application then signup with OpenID. Cognito Federated Identity authorize users to access AWS services.

Also, note that the Amplify session expires every hour; Amplify refreshes the token when using the default authentication. With a custom federated Provider, you need to update that token every time it expires(see this document and this issue). Before I explain each implementation, let's make sure we understand the concept and tools of the Cognito authentication process.

#Amazon Cognito

Amazon Cognito is a tool that provides authentication(Sign-in, Sign-up) and authorization to access AWS services. It has two main functionalities:

  • Cognito User Pools A complete set of user directory services to handle user registration, authentication, and account recovery.
  • Cognito Federated Identity Pools A tool to authorize your users to use AWS services. It provides access tokens to control accesses for authenticated users.

By default, Amplify uses both functionalities. However, when we implement passwordless authentication, we can not use Cognito User Pools as it only supports a traditional email/password or Social Provider like Google or Facebook. Then how can we authenticate our users?

The answer is : Developer authenticated identity.

#Developer authenticated identities

Developer authenticated identity can integrate a custom identity provider into your authentication process and still allow Cognito to manage user data and access AWS services. Developer authenticated identity retrieves OpenID Connect token using identity provided from the third-party.

So in short, we can authenticate users and obtain access tokens from Developer authenticated identity by using Magic as an identity provider!

If you want to know more about Developer authenticated identity and OpenID Connect, take a look at these documents below.

#Backend implementation

Now let's dive into the actual implementation. We assume that you have setup Amplify in your project and generated Api key on Magic. We will go through these steps:

  • Step 1 - Setup Amplify Auth
  • Step 2 - Setup Cognito Federated Identity
  • Step 3 - Implement Lambda function for retrieving OpenID Connect token
  • Step 4 - Add API Gateway

#Step 1 - Setup Amplify Auth

We are starting by implementing the authentication service using Amplify.

01$ amplify add auth
02 Do you want to use the default authentication and security configuration? Manual configuration
03 Select the authentication/authorization services that you want to use: User Sign-Up, Sign-In, connected with AWS IAM controls (Enables per-user Storage features for images or other content, Analy
04tics, and more)
05 Provide a friendly name for your resource that will be used to label this category in the project: magicAuth
06 Enter a name for your identity pool. magic33015299_identitypool_33015299
07 Allow unauthenticated logins? (Provides scoped down permissions that you can control via AWS IAM) Yes
08 Do you want to enable 3rd party authentication providers in your identity pool? No
09 Provide a name for your user pool: magic33015299_userpool_33015299
10 Warning: you will not be able to edit these selections.
11 How do you want users to be able to sign in? Email
12 Do you want to add User Pool Groups? No
13 Do you want to add an admin queries API? No
14 Multifactor authentication (MFA) user login options: OFF
15 Email based user registration/forgot password: Enabled (Requires per-user email entry at registration)
16 Specify an email verification subject: Your verification code
17 Specify an email verification message: Your verification code is {####}
18 Do you want to override the default password policy for this User Pool? No
19 Warning: you will not be able to edit these selections.
20 What attributes are required for signing up? Email
21 Specify the app's refresh token expiration period (in days): 30
22 Do you want to specify the user attributes this app can read and write? No
23 Do you want to enable any of the following capabilities?
24 Do you want to use an OAuth flow? No
25 Do you want to configure Lambda Triggers for Cognito? No
26✅ Successfully added auth resource magicAuth locally

Here we setup User Pool and some sign in details as Amplify requires it regardless. Then push this setup with amplify push --y.

#Step 2 - Setup Cognito Federated Identity

We will add our custom authentication provider into Cognito Federated Identity. Open AWS website and go to Amazon Cognito Console and click Federated Identities section.

Press "Edit identity pool", then find Authentication providers and add your identifier name in Custom tab. Make sure to save changes. Identifier can be anything but should be unique. We'll be using this later.

#Step 3 - Implement Lambda function for retrieving OpenID Connect token

Now let's create a lambda function in which we check the validity of did generated by Magic and obtain OpenId Connect Token.

01$ amplify add function
02? Select which capability you want to add: Lambda function (serverless function)
03? Provide an AWS Lambda function name: magicAuthentication
04? Choose the runtime that you want to use: NodeJS
05? Choose the function template that you want to use: Hello World
06
07Available advanced settings:
08- Resource access permissions
09- Scheduled recurring invocation
10- Lambda layers configuration
11- Environment variables configuration
12- Secret values configuration
13
14? Do you want to configure advanced settings? Yes
15? Do you want to access other resources in this project from your Lambda function? No
16? Do you want to invoke this function on a recurring schedule? No
17? Do you want to enable Lambda layers for this function? No
18? Do you want to configure environment variables for this function? No
19? Do you want to configure secret values this function can access? Yes
20? Enter a secret name (this is the key used to look up the secret value): MAGIC_PUB_KEY
21? Enter the value for MAGIC_PUB_KEY: [hidden]
22? What do you want to do? I'm done
23Use the AWS SSM GetParameter API to retrieve secrets in your Lambda function.
24More information can be found here: <https://docs.aws.amazon.com/systems-manager/latest/APIReference/API_GetParameter.html>
25? Do you want to edit the local lambda function now? Yes
26Edit the file in your editor: /Users/tomoima525/workspace/aws/amplify/magic-test/amplify/backend/function/magicAuthentication/src/index.js
27? Press enter to continue
28Successfully added resource magicAuthentication locally.

MAGIC_PUB_KEY is the key you find in Magic Console.

Now let's write some code. First, install @magic-sdk/admin which we use for the did validation. Run the command below at amplify/backend/function/magicAuthentication/src/.

01yarn add @magic-sdk/admin

Here's the code we need.

01const AWS = require("aws-sdk");
02const { Magic } = require("@magic-sdk/admin");
03const cognitoidentity = new AWS.CognitoIdentity({ apiVersion: "2014-06-30" });
04
05const getSecret = async () => {
06  return new AWS.SSM()
07    .getParameters({
08      Names: ["MAGIC_PUB_KEY"].map((secretName) => process.env[secretName]),
09      WithDecryption: true,
10    })
11    .promise();
12};
13
14exports.handler = async (event) => {
15  const { Parameters } = await getSecret();
16  const magic = new Magic(Parameters[0].Value);
17
18  const { didToken, issuer } = JSON.parse(event.body);
19  try {
20    // Validate didToken sent from the client
21    magic.token.validate(didToken);
22
23    const param = {
24      IdentityPoolId: process.env.IDENTITY_POOL_ID,
25      Logins: {
26        // The identifier name you set at Step 2
27        [`com.magic.link`]: issuer,
28      },
29      TokenDuration: 3600, // expiration time of connected id token
30    };
31
32    // Retrieve OpenID Connect Token
33    const result = await cognitoidentity
34      .getOpenIdTokenForDeveloperIdentity(param)
35      .promise();
36
37    const response = {
38      statusCode: 200,
39      headers: {
40        "Access-Control-Allow-Origin": "*",
41        "Access-Control-Allow-Headers": "*",
42        "Access-Control-Allow-Methods":
43          "DELETE,GET,HEAD,OPTIONS,PATCH,POST,PUT",
44      },
45      body: JSON.stringify(result),
46    };
47    return response;
48  } catch (error) {
49    const response = {
50      statusCode: 500,
51      body: JSON.stringify(error.message),
52      headers: {
53        "Access-Control-Allow-Origin": "*",
54        "Access-Control-Allow-Headers": "*",
55        "Access-Control-Allow-Methods":
56          "DELETE,GET,HEAD,OPTIONS,PATCH,POST,PUT",
57      },
58    };
59    return response;
60  }
61};

You need to make a few tweaks in order to make this Lambda function work. First, to use CognitoIdentity from Lambda function, you need to grant access permission in the cloudforamtion file. Add below under PolicyDocument section of your lambdaexecutionpolicy in cloud-formation-template.yml

01"PolicyDocument": {
02  "Version": "2012-10-17",
03  "Statement": [
04    {
05      ...
06    },
07    // Add this
08    {
09      "Effect": "Allow",
10      "Action": [
11        "cognito-identity:GetOpenIdTokenForDeveloperIdentity"
12      ],
13      "Resource": {
14        "Fn::Sub": [
15          "arn:aws:cognito-identity:${region}:${account}:identitypool/${region}:*",
16          {
17            "region": {
18              "Ref": "AWS::Region"
19            },
20            "account": {
21              "Ref": "AWS::AccountId"
22            }
23          }
24        ]
25      }
26    }
27  ]
28}

Second, you need to pass IDENTITY_POOL_ID as an environment variable. It is a little bit tricky so let's go through this carefully.

Open team-provider-info.yml and add identityPoolId which you can find in Cognito Web console(Idenity pool).

01"categories": {
02      "function": {
03        "magicAuth": {
04          "identityPoolId": "us-west-2:2477d5cd-cxxxxx", // <- Add this
05          "secretsPathAmplifyAppId": "xxdfsd",
06          "deploymentBucketName": "amplify-magictest-dev-233202-deployment",
07          "s3Key": "amplify-builds/magicAuth-7738665a44657a304142-build.zip"
08        },

Then add these to cloud-formation-template.yml as well.

01{
02  "AWSTemplateFormatVersion": "2010-09-09",
03  "Parameters": {
04    ...
05    // Add this
06    "identityPoolId": {
07      "Type": "String"
08    }
09  },
10  "Resources": {
11    "LambdaFunction": {
12      ...
13      "Properties": {
14        "Environment": {
15          "Variables": {
16            ...
17            // Add this
18            "IDENTITY_POOL_ID": {
19              "Ref": "identityPoolId"
20            }
21          }
22        },
23      }
24    },
25    ...
26  }
27}

Finally amplify push --y to deploy updates on Cloud.

#Step 4 - Add API Gateway

Now you need to add API Gateway to access this Lambda function.

01$ amplify add api
02? Select from one of the below mentioned services: REST
03✔ Provide a friendly name for your resource to be used as a label for this category in the project: · magicRestApi
04✔ Provide a path (e.g., /book/{isbn}): · /auth
05✔ Choose a Lambda source · Use a Lambda function already added in the current Amplify project
06Only one option for [Choose the Lambda function to invoke by this path]. Selecting [magicAuthFunction].
07✔ Restrict API access? (Y/n) · no
08✔ Do you want to add another path? (y/N) · no
09✅ Successfully added resource magicRestApi locally

Make sure that you don't restrict the access as users will need to access this API before authentication.

#Frontend implementation

Let's move on to Frontend implementation. This time we use React for Frontend.

  • Step 1 - Check user session
  • Step 2 - Sign up flow
  • Step 3 - Receiving callback and authenticate
  • Step 4 - Token refresh logic

#Step 1 - Check user session

We will first check the user session. At the entry point of the app, add below

01useEffect(() => {
02    setUser({ loading: true });
03    Auth.currentUserCredentials()
04      .catch((e) => {
05        console.log("=== currentcredentials", { e });
06      });
07    Auth.currentAuthenticatedUser()
08      .then((user) => {
09        magic.user
10          .isLoggedIn()
11          .then((isLoggedIn) => {
12            return isLoggedIn
13              ? magic.user
14                  .getMetadata()
15                  .then((userData) =>
16                    setUser({ ...userData, identityId: user.id })
17                  )
18              : setUser({ user: null });
19          })
20          .catch((e) => {
21            console.log("currentUser", { e });
22          });
23      })
24      .catch((e) => {
25        setUser({ user: null });
26      });
27  }, []);

Auth.currentUserCredentials() triggers token refresh(which we will implement in Step4). Auth.currentAuthenticatedUser() checks user info which is stored in Cognito. Then we also check if Magic authenticates this user.

#Step 2 - Add Sign up flow

If a user has not been signed up, we will redirect this user to Login screen. When a user posts their email address, we'll send them the email through Magic.

01async function handleLoginWithEmail(email) {
02    try {
03      // Prevent login state inconsistency between Magic and the client side
04      await magic.user.logout();
05      // Trigger Magic link to be sent to user
06      await magic.auth.loginWithMagicLink({
07        email,
08        redirectURI: new URL("/callback", window.location.origin).href, // optional redirect back to your app after magic link is clicked
09      });
10    } catch (error) {
11      console.log(error);
12    }
13  }

This function triggers the view below(A modal screen from Magic)

#Step 3 - Receiving callback and authenticate

Callback screen is where all the authentication processes happen. You might notice that we set 1 hour ahead for expire_at. This can be any number larger than 1 hour as the token expires in 1 hour anyway.

01const authenticateWithServer = async (didToken) => {
02    let userMetadata = await magic.user.getMetadata();
03    // Get Token and IdentityId from Cognito
04    const res = await API.post(
05      awsconfig.aws_cloud_logic_custom[0].name,
06      "/auth",
07      {
08        body: {
09          didToken,
10          issuer: userMetadata.issuer,
11        },
12      }
13    );
14
15    // Federated Sign in using OpenId Token
16    const credentials = await Auth.federatedSignIn(
17      "developer",
18      {
19        identity_id: res.IdentityId,
20        token: res.Token,
21        expires_at: 3600 * 1000 + new Date().getTime(),
22      },
23      user
24    );
25    if (credentials) {
26      // Set the UserContext to the now logged in user
27      let userMetadata = await magic.user.getMetadata();
28      await setUser({ ...userMetadata, identityId: credentials.identityId });
29      history.push("/profile");
30    }
31  };

Now this user is authenticated and has access to private API and AWS resources. You will find that this user is authenticated on Cognito Dashboard.

#Step 4 - Add token update

One last step, we will add refresh token logic. As we mentioned, Amplify will not automatically refresh your token when you use your custom authentication. Fortunately you can configure Amplify to update manually.

Go to index.js (the entry point of your application) and add below.

01async function refreshToken() {
02  const didToken = await magic.user.getIdToken();
03  const userMetadata = await magic.user.getMetadata();
04  const body = JSON.stringify({
05    didToken,
06    issuer: userMetadata.issuer,
07  });
08  const res = await fetch(
09    `${awsconfig.aws_cloud_logic_custom[0].endpoint}/auth`,
10    {
11      method: "POST",
12      body,
13    }
14  );
15  const json = await res.json();
16  return {
17    identity_id: json.IdentityId,
18    token: json.Token,
19    expires_at: 3600 * 1000 + new Date().getTime(),
20  };
21}
22
23Auth.configure({
24  refreshHandlers: {
25    developer: refreshToken,
26  },
27});

We are using fetch as we just need a simple request to fetch the refreshed token and the identity. This function will refresh the token whenever 1 hour passes after the previous token update.

That's all there is to it!

#Things to keep in mind

When you consider introducing/migrating to passwordless authentication, you should be aware of a few things.

  • you no longer rely on Cognito User Pool. Your backend becomes simpler but also loses some benefits that Cognito User Pool offers. For example, you can not use group access control.
  • Cognito Federated Identities' custom provider can not be updated once you configured it. Define the identifier name carefully. If you have multiple environments, you should change those names such as com.magic.link.dev for development and com.magic.link.production for production. This way you do not share Identity pools.

#Beyond passwordless authentication: Connecting Web2 and Web3

In this article, I shared how to implement passwordless authentication using Email. But there's more to it! Magic supports various crypto wallet connections. When a wallet is connected, you can obtain a unique address. That means we can basically take the same approach that I wrote if we want to apply the access control to web3 applications. I am not going to share that in this article, but you can definitely try it out using the example repo!

Let's make some magic!