Building a SaaS Product (2)

Building a SaaS Product (2)

Adding Auth via AWS Amplify

ยท

4 min read

In my prvevious post we put together a starter project for a SaaS product. Today, I am going to show you how to add Authentication to an Angular project by using AWS Amplify. This requires you to have an AWS account and may incur small charges to get this working.

๐Ÿฆ Follow me on Twitter to see all vital content! ๐Ÿฆ

TLDL: Here is the code in my GitHub. Here is a look at my pull-request with the necessary changes.

Prerequisite

  1. Follow these instructions on how to install and configure the Amplify CLI.

  2. Checkout my starter project on GitHub. Make sure you start on the feature/step-1-setting-up branch!

Initialize Amplify

  1. Run the following code in the webapp folder. This will initialize an amplify project in our Angular project. You will then configure authentication. Finally, we will push these changes to AWS. You will be asked to login to your AWS account.

    amplify init 
    # make sure you store your keys for the new user!
    amplify configure
    amplify add auth
    amplify push
    
  2. Install the UI using NPM.

    npm install aws-amplify @aws-amplify/ui-angular
    

Update Angular

  1. Update app.module with this new code. We need to add imports for the AWS packages.

    import Amplify, { Auth } from 'aws-amplify';
    import {AmplifyUIAngularModule} from "@aws-amplify/ui-angular";
    import awsconfig from './aws-exports'; 
    Amplify.configure(awsconfig);
    ...
    imports: [
      ...,
     AmplifyUIAngularModule
    ],
    
  2. AWS Amplify requires a global variable to be accessible. Add this to the top of the file src/polyfill.ts

    (window as any).global = window;
    (window as any).process = {
    env: { DEBUG: undefined },
    };
    
  3. Replace all the template code in app.component.html with this

    <amplify-authenticator>
    <div>
     My App
     <amplify-sign-out></amplify-sign-out>
    </div>
    </amplify-authenticator>
    
  4. Use a git ignore for amplify/team-provider-info.json. The file has sensitive info you don't want in source control!

That's it! You should be able to run ng serve and be greeted with a login screen.

If you simply want to pull my git repo you will need to delete the amplify folder and run the following commands:

amplify init 
# make sure you store your keys for the new user!
amplify configure
amplify add auth
amplify push

Here is the code in my GitHub. Here is a look at my pull-request with the necessary changes.

๐Ÿฆ Follow me on Twitter to see all vital content! ๐Ÿฆ

Here are some screenshots from my setup: amp-init.png amp add auth.png amplify-push.png

Resource

Did you find this article valuable?

Support Phillip Ninan's Blog by becoming a sponsor. Any amount is appreciated!