Tuesday, September 22, 2020

In this blog post I’ll demonstrate how set auth0 for an angular 4 applications.

Create a new client:

You should see something similar to this:

First install angular2-jwt and auth0-js

npm install --save auth0-js angular2-jwt

Create a new angular service and paste this code:

import { Injectable } from '@angular/core';
import { AUTH_CONFIG } from './auth0-variables';
import { Router } from '@angular/router';
import * as auth0 from 'auth0-js';
declare var Auth0Lock: any;

@Injectable()
export class AuthService {
    profile: any;
    auth0 = new auth0.WebAuth({
        clientID: AUTH_CONFIG.clientID,
        domain: AUTH_CONFIG.domain,
        responseType: 'token id_token',
        audience: `https://${AUTH_CONFIG.domain}/userinfo`,
        redirectUri: 'http://localhost:4200/callback',
        scope: 'openid',
        internalOptions: {
            audience: 'https://api.investips.com'
        }
    });

    lock = new Auth0Lock(
    'Tvuppr5MN-nyZ9JDBIlhE_Jsvy3TmABj',
    'investips.auth0.com');

    constructor(public router: Router) {
        this.profile = JSON.parse(localStorage.getItem('profile'));
    }

    public login(): void {
        this.auth0.authorize();
    }

    public handleAuthentication(): void {
        this.auth0.parseHash((err, authResult) => {
            if (authResult && authResult.accessToken) {
                window.location.hash = '';
                this.setSession(authResult);
                this.lock.getUserInfo(authResult.accessToken, function(error, profile) {
                    if (error) {
                        // Handle error
                        return;
                    }

                    localStorage.setItem('profile', JSON.stringify(profile));
                    this.profile = profile;
                });
                this.router.navigate(['/']);
            } else if (err) {
                this.router.navigate(['/']);
                console.log(err);
                alert(`Error: ${err.error}. Check the console for further details.`);
            }
        });
    }

    private setSession(authResult): void {
        // Set the time that the access token will expire at
        const expiresAt = JSON.stringify((authResult.expiresIn * 1000) + new Date().getTime());
        localStorage.setItem('access_token', authResult.accessToken);
        //localStorage.setItem('id_token', authResult.idToken);
        localStorage.setItem('expires_at', expiresAt);
    }

    public logout(): void {
        // Remove tokens and expiry time from localStorage
        localStorage.removeItem('access_token');
        //localStorage.removeItem('id_token');
        localStorage.removeItem('expires_at');
        localStorage.removeItem('profile');
        this.profile = null;
        // Go back to the home route
        this.router.navigate(['/']);
    }

    public isAuthenticated(): boolean {
        // Check whether the current time is past the
        // access token's expiry time
        const expiresAt = JSON.parse(localStorage.getItem('expires_at'));
        return new Date().getTime() < expiresAt;
    }

}

create another ts file named auth0-variables and paste this code:

interface AuthConfig {
    clientID: string;
    domain: string;
    callbackURL: string;
}

export const AUTH_CONFIG: AuthConfig = {
    clientID: 'gh3DJB5h5gPWGxtUkHMwdXFqpj92klVX',
    domain: 'investips.auth0.com',
    callbackURL: 'http://localhost:4200/callback'
};

Your client ID and domain can be found in here:

For the callback component, you can create just a default callback component or set it to default:

http://localhost:4200 in Auth0 client configuration page.

If you want to refer to a tutorial from Aut0 on how to create this callback component here is the link:

https://auth0.com/docs/quickstart/spa/angular2?framed=1&sq=1#add-a-callback-component

 

Then somewhere in your menu you need to add something like this:

<li (click)="auth.logout()"  *ngIf="auth.isAuthenticated()" role="menuitem">
       <a href="#" class="ripplelink" [attr.tabindex]="!active ? '-1' : null">
          <i class="material-icons">power_settings_new</i>
          <span>Logout</span>
      </a>
</li>
<li *ngIf="!auth.isAuthenticated()" role="menuitem">
       <a (click)="auth.login()" class="ripplelink" [attr.tabindex]="!active ? '-1' : null">
        <i class="material-icons">power_settings_new</i>
       <span>Login</span>
    </a>
</li>

This is the minimum code you need to write in order to configure authentication & authorization using Auth0 in an Angular application.

In a future post I’ll demonstrate how to this angular app can interact with an ASP.NET Core API using Auth0.