Step-by-Step guide for implementing Amazon login on the web with OAuth
Tags: oauth, nuxt, javascript, tutorial
Published: 2023-08-08 21:33:31

In today’s interconnected world, protecting your online identity is paramount. OAuth and authentication mechanisms ensure secure access to your digital resources. OAuth, a widely adopted authorization framework, enables users to grant limited access to their data and resources to third-party applications without compromising their credentials.

Appwrite is a self-hosted backend-as-a-service platform that provides developers with all the core APIs required to build any application. Appwrite delivers solutions that help in building backend servers for applications.

This article will discuss how to authenticate a Nuxt.js application using Appwrite’s Amazon OAuth provider.

## GitHub

Check out the complete source code [here](https://github.com/Tundesamson26/appwrite-nuxt-oauth).

## Prerequisites 

To follow along with this tutorial, you should have a working knowledge of the following:

- Vue, Nuxt.js, and CSS
- Amazon developer account; you can create one [here](https://developer.amazon.com/) if you don’t have one
- An Appwrite Cloud account; you can request access to Appwrite Cloud [here](https://appwrite.io/cloud/?utm_source=hackmamba&utm_medium=hackmamba-blog)

## Setting up the project

You need to create a Nuxt.js starter project by navigating to the desired directory and running the command below in your terminal.

```js
npx nuxi@latest init appwrite-amazon-auth
```
The command creates a Nuxt.js project called `appwrite-amazon-auth`.

Next, you need to install Nuxt.js dependencies by running the command below in your terminal.

```js
npm install
```

Next, go to the project directory and start the development server on `localhost:3000` with the commands below.

```js
cd appwrite-amazon-auth && npm run dev
```

## Installing dependencies
**Installing Pink Design**

[Pink Design](https://pink.appwrite.io/?utm_source=hackmamba&utm_medium=hackmamba-blog) is an open-source system from Appwrite used to build consistent and reusable user interfaces. It enhances collaboration, development experience, and accessibility.

To install Pink Design, open the terminal in the project directory and run the following command.

```js
npm install @appwrite.io/pink
```

To use Pink Design in your project, import it into your project’s files like this:

```js
import '@appwrite.io/pink';
import '@appwrite.io/pink-icons';
```

**Installing Appwrite**

[Appwrite](https://appwrite.io/?utm_source=hackmamba&utm_medium=hackmamba-blog) is a development platform that provides a powerful API and management console for building backend servers for web and mobile applications. To install it, run the command below:

```js
npm install appwrite
```

## Creating an Appwrite Cloud project

To get started, log into your Appwrite cloud, click the Create project button, input `appwrite-amazon-auth` as the name, and then click **Create**.

![appwrite-create-project](https://paper-attachments.dropboxusercontent.com/s_CC3216CDD9605E930F16C88A706B1201B4762DAAC1491E94D7255ED41C8DE996_1686865557531_image.png)

The project dashboard will appear on the console. Next, copy the **Project ID**; you’ll use this to set up your Nuxt.js application.

![appwrite-project-tab](https://paper-attachments.dropboxusercontent.com/s_CC3216CDD9605E930F16C88A706B1201B4762DAAC1491E94D7255ED41C8DE996_1686865945076_image.png)

**Creating an Auth user**
On the left side of the Appwrite Cloud dashboard, click on the **Auth** tab.

![Auth-tab](https://paper-attachments.dropboxusercontent.com/s_CC3216CDD9605E930F16C88A706B1201B4762DAAC1491E94D7255ED41C8DE996_1686866091078_image.png)


**Activating Amazon OAuth2 provider on Appwrite**
From the **Auth** tab, locate the **Settings** tab, where you will see the list of auth providers. Look out for **Amazon** amongst the OAuth2 providers.

![auth-setting](https://paper-attachments.dropboxusercontent.com/s_CC3216CDD9605E930F16C88A706B1201B4762DAAC1491E94D7255ED41C8DE996_1686866706819_image.png)


Toggle to **Enable** Amazon provider, and take note of the “Amazon redirect URL” provided, as you will need it for authentication on the Amazon dashboard.

![amazon-auth-settings](https://paper-attachments.dropboxusercontent.com/s_CC3216CDD9605E930F16C88A706B1201B4762DAAC1491E94D7255ED41C8DE996_1687252872393_image.png)


After applying the necessary configurations on Appwrite, let’s start building the application.

## Integrating Appwrite Cloud into the Nuxt.js project

To integrate Appwrite into the UI, create a `utils/web-init.js` file. The file should look like this.

```js
import { Client, Account } from "appwrite";
export const client = new Client();
export const account = new Account(client);
client
  .setEndpoint("https://cloud.appwrite.io/v1")
  .setProject("643fee63b2b5b506495c");
```
The code above does the following:

- Import the module `Client` and `Account` from appwrite
- Instantiates the `Client` and `Account` objects
- Uses the client object to set the endpoint and project

## Creating an Amazon app

Appwrite’s Amazon OAuth provider requires you to create an application on Amazon from the developer’s dashboard. Check out this [comprehensive documentation](https://developer.amazon.com/docs/login-with-amazon/register-web.html) on creating an **Amazon New Security Profile** from the **Login with Amazon** tab.

From there, you will add the **Amazon redirect URI** from the Appwrite application to the **Consent Privacy Notice URL** in the application.


![amazon-security-profile](https://paper-attachments.dropboxusercontent.com/s_CC3216CDD9605E930F16C88A706B1201B4762DAAC1491E94D7255ED41C8DE996_1688765115148_image.png)


You will finish this setup by copying the **Client ID** and **Client Secrets** from the application page on Amazon. You will add these keys to the **App ID** and **App Secret** fields in your Appwrite Amazon OAuth2 settings.

![login-with-amazon-config](https://paper-attachments.dropboxusercontent.com/s_CC3216CDD9605E930F16C88A706B1201B4762DAAC1491E94D7255ED41C8DE996_1688765366546_image.png)

## Building authentication in Nuxt.js

The application will have two pages - the login page, where authentication happens using the Appwrite Amazon provider, and another, which displays the user details.

**Creating the login page**
The login page is the application’s entry point where users get authenticated. To build this, you will update the `pages/index.vue` with the code below:

```vue 
<template>
  <h2 class="u-text-center u-font-size-32 u-margin-32">Login with Amazon</h2>
  <div class="card u-text-center u-max-width-400" style="margin: auto">
    <div class="u-text-center">
      <p>Click on this button to login</p>
      <button
        class="button u-margin-inline-auto u-margin-block-start-24"
        @click="loginWithAmazon"
      >
        <span class="text">Login with Amazon</span>
      </button>
    </div>
  </div>
</template>
<script setup>
import { Client, Account } from "appwrite";
import "@appwrite.io/pink";
import "@appwrite.io/pink-icons";

const client = new Client();
const account = new Account(client);
client
  .setEndpoint("https://cloud.appwrite.io/v1")
  .setProject("648b874f54b5092cdf00");
  
const loginWithAmazon = async () => {
  try {
    await account.createOAuth2Session(
      "amazon",
      "http://localhost:3000/dashboard"
    );
  } catch (e) {
    alert("user does not exist");
    console.log(e);
  }
};
</script>
```
The code block above achieved the following:

- The `<template>` tag contains the markup for displaying the login UI
- Imported the Apprwite SDK
- Created a `loginwithAmazon` asynchronous function that uses the imported Appwrite SDK; within this function, the Appwrite `createOAuth2Session` method received the following:
    - `amazon`: this is the OAuth2 provider you would like users to use to sign in
    - A redirect URL where users are directed after successful authentication

**Creating the dashboard page**
Next, you will create a page to which users are directed after a successful login. This page shows the user's **name** and **email** with an additional button that allows them to log out. To implement this, you will create a `pages/dashboard.vue` file and add the code below:

```vue 
<template>
  <section class="container">
    <div>
      <h2 class="u-text-center u-font-size-32 u-margin-32">
        Amazon Authentication with Appwrite
      </h2>
      <div
        class="card u-text-center u-cross-center u-width-full-line u-max-width-350"
        style="margin: auto"
      >
        <div class="">
          <h3 class="body-text-2 u-margin-block-start-16 u-bold">
            Name:
          </h3>
          <p class="">{{name}}</p>
          <h3 class="u-margin-block-start-4 u-color-text-gray u-bold">
            Email:
          </h3>
          <p>{{email}}</p>
        </div>
        <button class="button u-margin-inline-auto u-margin-block-start-24" @click="logOutWithAmazon">
          <span class="text">Logout</span>
        </button>
      </div>
    </div>
  </section>
</template>
<script setup>
import { ref, onMounted } from "vue";
import { useRouter } from 'vue-router';
import { Client, Account } from "appwrite";
import "@appwrite.io/pink"; // optionally, add icons
import "@appwrite.io/pink-icons";

const client = new Client();
const account = new Account(client);
client
  .setEndpoint("https://cloud.appwrite.io/v1")
  .setProject("648b874f54b5092cdf00");
  
const name = ref("");
const email = ref("");
const response = ref("");
const $router = useRouter();

onMounted(async () => {
  await getUserSession();
});

const getUserSession = async () => {
  try {
    response.value = await account.get();
    if (response.value) {
      name.value = response.value.name;
      email.value = response.value.email;
    }
  } catch (error) {
    console.log(error);
  }
};

const logOutWithAmazon = async () => {
  try {
    await account.deleteSession('current');
    $router.push('/');
  } catch (error) {
    console.log(error);
  }
};
</script>
```
The code block above achieved the following:

- Added the `<template>` tag for displaying the user information
- Imported the Appwrite SDK 
- Updated the data property with **name**, **email**, and **response** to hold the user’s information
- Created a `getSession()` function, which gets executed when the application is mounted. This function fetched the logged-in user information for the current and updated the variables declared in the data property with the information
- Added the `logOutWithAmazon()` function, which is connected to Appwrite’s `deleteSession()` method (the `logOutWithAmazon()` function logs the user out of the application and immediately routes the user to the home page)

At this stage, the application should look like the following:

{% embed
https://www.loom.com/share/e6606de391a746fab22effaa4b236bf1?sid=0ed93a2b-2249-41a8-b442-a70ad7509d6f %}

## Conclusion

This article explained how to implement Amazon login authentication to an application using Appwrite’s OAuth2 Amazon provider. It also discussed creating an application on Amazon from the developer’s dashboard and creating an Amazon **New Security Profile** from the **Login with Amazon**.

## Resources

Here are some resources that might be helpful:

- [Appwrite Cloud](https://appwrite.io/cloud?utm_source=hackmamba&utm_medium=hackmamba-blog)
- [Appwrite account API documentation](https://appwrite.io/docs/client/account?sdk=web-default#accountCreateOAuth2Session?utm_source=hackmamba&utm_medium=blog&utm_campaign=auth0_auth0-authentication-vue)
- [Appwrite Pink Design](https://pink.appwrite.io/?utm_source=hackmamba&utm_medium=hackmamba-blog)