Adding Secure Authentication to Your Vue App with AWS Amplify

Authentication is a critical component of most modern web applications. It allows you to provide personalized experiences, protect sensitive data, and control access to certain features and pages. But implementing your own auth system from scratch is time-consuming and risky from a security standpoint.

Enter AWS Amplify – a powerful set of tools and services from Amazon Web Services that dramatically simplifies adding features like authentication, authorization, storage, hosting, and more to web and mobile apps. By leveraging AWS Amplify, you can quickly implement best-practice authentication in your Vue applications without needing to become a security expert yourself.

In this post, we‘ll walk through the process of adding login, logout, and sign up capabilities to a Vue app using AWS Amplify. You‘ll learn how to get Amplify up and running in your application and see concrete code examples of the key auth flows. Let‘s dive in!

What is AWS Amplify?

AWS Amplify is a suite of purpose-built tools and features that lets developers quickly and easily build full-stack applications on AWS. It consists of three main components:

  1. Amplify libraries – Open source UI components and SDKs that integrate with cloud services
  2. Amplify CLI – A command line tool for creating and managing your app‘s AWS infrastructure
  3. Amplify Console – A web console for configuring and administering your app

There‘s much more to Amplify than just authentication, but auth and user management are some of its most powerful and popular features. Out of the box, Amplify Auth provides:

  • User registration and sign-in, with customizable forms and multi-factor authentication
  • Social login via Google, Facebook, Amazon, etc.
  • Secure token handling and automatic refresh
  • Fine-grained access control for your app‘s data and resources
  • Easy integration with the rest of the Amplify ecosystem

Under the hood, Amplify uses Amazon Cognito as its auth provider. Cognito is a fully-managed user directory service that takes care of securely storing credentials, handling tokens, protecting against attacks, and so on. But you don‘t need to interact with Cognito directly or really understand how it works – the Amplify libraries and CLI abstract away the details and provide a simple, unified auth interface.

So in short, Amplify Auth saves you from the complexities of implementing your own auth system. It provides the core login, logout, and access control features most apps need, using current security best practices, in a way that‘s easy for developers to adopt. That‘s a big win for productivity and peace of mind.

Set Up

Before we start integrating Amplify into our Vue application, there are a few setup steps we need to complete:

Create an AWS Account

First, you‘ll need an AWS account. If you don‘t have one already, navigate to aws.amazon.com and choose "Create an AWS Account". You‘ll have to provide a credit card for verification. Don‘t worry though – we‘ll be using the free tier in this tutorial.

Install and Configure the Amplify CLI

Next, we need to install the Amplify command line interface. Open a terminal and run:

npm install -g @aws-amplify/cli

After that completes, run this command to configure the CLI with your AWS account:

amplify configure

This will open up a web browser and prompt you to sign in to the AWS Console. Once signed in, return to the terminal. Press Enter, then follow the prompts to create a new IAM user. Use the proposed default settings for the user name and permissions.

Amplify will then ask you to provide an access key and secret key for your new IAM user, which you can get from the AWS Console. Enter them in the terminal when prompted. Finally, choose a Profile Name to identify this particular setup, or just accept the default.

Create a Vue Project

With the AWS and Amplify setup out of the way, let‘s create a basic Vue application to work with. I‘ll assume you have Vue CLI installed, but if not, you can get it via:

npm install -g @vue/cli

Now generate a new project:

vue create amplify-auth-demo

Choose the default preset and wait for the project to be created. Now we have a working Vue starter project to add authentication to.

Initialize Amplify

With our Vue project created, let‘s start integrating Amplify. The first step is to initialize a new Amplify project inside our Vue app.

Navigate into your Vue project folder in the terminal, then run:

amplify init

Amplify will prompt you for some information about your project. Here‘s how to answer the questions:


Enter a name for the project: amplify-auth-demo
Enter a name for the environment: dev
Choose your default editor: Visual Studio Code (or your editor of choice)
Choose the type of app that you‘re building: javascript
What javascript framework are you using: vue
Source Directory Path: src
Distribution Directory Path: dist
Build Command: npm run-script build
Start Command: npm run-script serve
Do you want to use an AWS profile? Y
Please choose the profile you want to use: default (or select your profile if there are multiple)

This process does a few important things:

  1. Creates a top-level directory called "amplify" that stores your backend configuration
  2. Adds an "aws-exports.js" file to your src directory with all your backend config
  3. Modifies your .gitignore to avoid checking in unnecessary Amplify files
  4. Creates an AWS Amplify Console project in your account for you to view and manage your backend

Add Authentication Service

Now that we have an Amplify project initialized inside our Vue app, we can add an authentication service to it.

From the root of your Vue project, run:

amplify add auth

You‘ll be guided through a few prompts to configure your auth setup:


Do you want to use the default authentication and security configuration? Default configuration
How do you want users to be able to sign in? Username
Do you want to configure advanced settings? No, I am done.

This will generate the infrastructure-as-code templates to define a complete authentication service in Amazon Cognito. To actually deploy this infrastructure to our AWS account, run:

amplify push

After a minute or two of provisioning, your auth service will be live!

Install Amplify Libraries

The final step in our setup process is to install the Amplify libraries in our Vue app so we can use the auth service we just deployed.

Run this command from your project root:

npm install aws-amplify

After the install completes, open up your Vue app‘s main.js file. At the top, add these lines:

import Amplify from ‘aws-amplify‘;
import awsconfig from ‘./aws-exports‘;

Amplify.configure(awsconfig);

This imports the Amplify configuration information that was generated for us by the amplify init command. The Amplify.configure() call then registers this configuration with the Amplify library so it can locate and access our auth service.

Implement Auth Flows

We‘re finally ready to start adding auth flows to our Vue app! We‘ll create three pages – a sign up page, a login page, and a logout button.

Sign Up

Let‘s start with the sign up flow. Create a new file SignUp.vue in your app‘s components directory. Paste in this code:

<template>
  <div>
    <h2>Sign Up</h2>
    <form @submit.prevent="signUp">
      <label>Username: <input v-model="username" /></label>
      <label>Password: <input type="password" v-model="password" /></label>
      <label>Email: <input type="email" v-model="email" /></label>
      <button type="submit">Sign Up</button>
    </form>
  </div>
</template>

<script>
import { Auth } from ‘aws-amplify‘;

export default {
  name: ‘SignUp‘, 
  data() {
    return {
      username: ‘‘,
      password: ‘‘,
      email: ‘‘,
    };
  },
  methods: {
    async signUp() {
      try {
        const { user } = await Auth.signUp({
          username: this.username,
          password: this.password,
          attributes: {
            email: this.email,
          }
        });
        console.log(‘User successfully signed up:‘, user);
        // navigate user to login page or request code here
      } catch (error) {
        alert(error.message);
        console.error(‘Error signing up:‘, error);
      }
    },
  },
};
</script>

This renders a simple form with fields for username, password, and email. When the form is submitted, the signUp method is called.

Inside signUp, we use the Auth class from aws-amplify to call Auth.signUp() with the form data. This signs the user up in our Cognito user pool and returns a user object if successful.

We‘ll also need to create a new route for this sign up page. Open router/index.js and add:

{
   path: ‘/signup‘,
   name: ‘SignUp‘,
   component: SignUp, 
},

Make sure to also import the SignUp component at the top:

import SignUp from ‘../components/SignUp.vue‘;

Now if you run your app and visit http://localhost:8080/signup, you should see a functioning sign up form. Try registering a new user and check that it appears in your Cognito user pool in the AWS Console.

Login

The login flow will look very similar. Create a new Login.vue component with the following code:

<template>
  <div>
    <h2>Login</h2>
    <form @submit.prevent="login">
      <label>Username: <input v-model="username" /></label>  
      <label>Password: <input type="password" v-model="password" /></label>
      <button type="submit">Login</button>
    </form>  
  </div>
</template>

<script>
import { Auth } from ‘aws-amplify‘;

export default {
  name: ‘Login‘,
  data() { 
    return {
      username: ‘‘, 
      password: ‘‘,
    };
  },
  methods: {
    async login() {
      try {
        const user = await Auth.signIn(this.username, this.password);
        alert(`Logged in as ${user.username}`); 
      } catch (error) {
        alert(error.message);
        console.error(‘Error logging in:‘, error); 
      }
    },
  },
};
</script>

The key part here is the login method, which calls Auth.signIn() with the supplied username and password. If the login succeeds, we alert a success message.

Add a /login route for this component as well:

{
   path: ‘/login‘,
   name: ‘Login‘,
   component: Login,
},

Logout

Finally, let‘s add a logout button. Open up App.vue and add a new method:

async logout() {
  try {
    await Auth.signOut();
    alert(‘Logged out‘);
  } catch (error) {
    alert(error.message);
    console.error(‘Error logging out:‘, error);
  }
},  

And add a button to call it in your template:

<button @click="logout">Logout</button>

The Auth.signOut() method deletes the user‘s tokens from storage and revokes them with Cognito, effectively logging the user out.

More Advanced Auth Features

We‘ve only scratched the surface of what‘s possible with Amplify Auth. Some other common auth-related tasks you can accomplish:

  • Requiring a verficiation code: By default, users are immediately confirmed upon signup. You can change your user pool settings to require a multi-factor auth code sent via email or SMS before enabling the user.

  • Capturing detailed user info: You can collect additional user metadata on sign up like name, birthdate, profile picture, etc and store it in Cognito.

  • Customizing the UI: Amplify also provides a set of preconfigured auth UI components that you can drop into your app and customize via CSS, including forms, buttons, and a full authenticator component that encapsulates sign up, login, and MFA prompts.

  • Enabling federated sign-in: You can use Amplify Auth with Amazon Cognito Identity Pools to enable sign in via Facebook, Google, Amazon, Apple, and more, without needing to integrate with each provider separately.

Check out the Amplify Auth docs for more configuration options and code samples.

Alternatives to Amplify

Amplify Auth is not your only option for implementing authentication in a Vue app. Some other popular choices:

  • Firebase Auth – Google‘s alternative to Cognito. Provides similar email/password, social, and phone auth options. May be easier to implement if you‘re already using other Firebase products.

  • Auth0 – A dedicated auth platform that offers many advanced features like user management, single sign on, and extensive customization options. More powerful than Amplify Auth but also more complex.

  • Okta – Another enterprise-focused identity solution. Comparable in features to Auth0. Best if your app needs to integrate with existing Okta deployments in your organization.

  • Passport.js – If you have a Node/Express backend for your Vue app, you can implement auth yourself using Passport. It offers "strategies" for local email/password auth as well as dozens of OAuth providers. More involved than Amplify but gives you complete control.

Ultimately, Amplify Auth hits a sweet spot for me – it‘s simple to implement, provides the essential auth features most apps need, and integrates seamlessly with the rest of the Amplify ecosystem. But it‘s worth evaluating the other options to see what best fits your app‘s particular requirements.

Conclusion

Adding authentication to your Vue application has never been easier thanks to AWS Amplify. In just a few lines of code, we were able to implement secure sign up, login, and logout flows, without needing to manage the underlying auth infrastructure ourselves.

Beyond the core auth flows we implemented, Amplify offers a full suite of turnkey auth and user management features, as well as easy integration with the broader Amplify ecosystem for creating full-stack serverless apps.

I encourage you to dive deeper into the Amplify Auth docs and experiment with adding auth to your own Vue projects. Authentication doesn‘t have to be a chore – tools like Amplify let you focus on building features unique to your app.

Drop any questions in the comments and thanks for reading!

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *