Web JS with Angular

Prerequisites

Required client settings

As this library is designed for SPAs, make sure you have selected Application Type in your client settings as Single Page Application.

For a fully functional integration ensure that Callback redirect URIs and Signout redirect URIs are configured.

Install web-js package

npm i @axioms/web-js

Custom webpack config

As web-js requires Node.js Crypto and Stream libraries, you will need to use custom webpack builder and config for your Angular project.

  1. First install Angular custom webpack builder and dotenv for webpack
npm i -D @angular-builders/custom-webpack dotenv-webpack
  1. Create custom webpack config in project root
extra-webpack.config.js
const webpack = require('webpack');
const Dotenv = require('dotenv-webpack');
module.exports = {
node: {
crypto: true,
stream: true
},
plugins: [
// To use .env file in your project root
new Dotenv({
path: './.env', // Path to .env file (this is the default)
safe: true // load .env.example (defaults to "false" which does not use dotenv-safe)
}),
// To use environment variable of your build system i.e. Netlify
new webpack.EnvironmentPlugin(['NG_APP_Client_Id',
'NG_APP_Axioms_Domain',
'NG_APP_Redirect_Uri',
'NG_APP_Post_Logout_Uri',
'NG_APP_Response_Type',
'NG_APP_Scope',
'NG_APP_Post_Login_Navigate'])
]
}
  1. Update your angular.json. Basically update builder to use @angular-builders/custom-webpack:browser and in options add customWebpackConfig with path to extra-webpack.config.js
angular.json
"projects": {
...
"[project]": {
...
"architect": {
...
"[architect-target]": {
"builder": "@angular-builders/custom-webpack:browser"
"options": {
"customWebpackConfig": {
"path": "./extra-webpack.config.js"
},
...
}
...

Angular client configuration

  1. Grab the client key. Now, in your Angular app add auth.service.ts file and create web-js Auth object which looks like below.
src/app/auth.service.ts
import { Injectable } from '@angular/core';
import { Auth } from '@axioms/web-js';
@Injectable({providedIn: 'root'})
export class AuthService {
constructor() { }
$auth() {
return new Auth({
axioms_domain: process.env.NG_APP_Axioms_Domain,
response_type: process.env.NG_APP_Response_Type,
redirect_uri: process.env.NG_APP_Redirect_Uri,
post_logout_uri: process.env.NG_APP_Post_Logout_Uri,
client_id: process.env.NG_APP_Client_Id,
scope: process.env.NG_APP_Scope,
post_login_navigate: NG_APP_Post_Login_Navigate,
});
}
}
  1. In app directory add typing.d.ts
src/app/typing.d.ts
declare var process: Process;
interface Process {
env: Env
}
interface Env {
NG_APP_Axioms_Domain: string,
NG_APP_Client_Id: string,
NG_APP_Redirect_Uri: string,
NG_APP_Post_Logout_Uri: string,
NG_APP_Response_Type: string,
NG_APP_Scope: string,
NG_APP_Post_Login_Navigate: string
}
interface GlobalEnvironment {
process: Process
}
  1. Next add a .env file in your Angular project root, and populate following values,
.env.local
NG_APP_Client_Id=<Your-Client-ID>
NG_APP_Axioms_Domain=<Your-Axioms-Domain>
NG_APP_Redirect_Uri=https://<Your-App-Host>/callback
NG_APP_Post_Logout_Uri=https://<Your-App-Host>/login
NG_APP_Response_Type=<Your-Response-Type>
NG_APP_Scope=<Your-Scope>
NG_APP_Post_Login_Navigate=<Your-Post-Login-Navigate>

Here is an example version of .env

.env.local
NG_APP_Client_Id=MvnGPGwPJ7DNs0fQLpAr4dhi2PbfuQX1
NG_APP_Axioms_Domain=auth.test-unlimited.com
NG_APP_Redirect_Uri=http://localhost:4200/callback
NG_APP_Post_Logout_Uri=http://localhost:4200/login
NG_APP_Response_Type=code
NG_APP_Scope=openid profile
NG_APP_Post_Login_Navigate=/dashboard

Using web-js functions

In your component files access various web-js JavaScript functions using AuthService object and use constructor to create class variable $auth.

  • Using AuthService in your components
import { AuthService } from '../auth.service';
constructor(private authService: AuthService) {
this.$auth = this.authService.$auth();
}
  • To login with redirect,
this.$auth.login_with_redirect();
  • For logout with redirect,
this.$auth.logout_with_redirect();
  • To check if user is authenticated,
this.$auth.session.is_authenticated()

Add view for redirect URI

  1. Using Angular CLI Create callback component, add authorization response processing logic, and register as route /callback.
ng generate component callback

In component file add,

app/callback/callback.component.ts
import { Component, OnInit } from '@angular/core';
import { AuthService } from '../auth.service';
@Component({
selector: 'app-callback',
templateUrl: './callback.component.html',
styleUrls: ['./callback.component.scss']
})
export class CallbackComponent implements OnInit {
private $auth: any;
constructor(private authService: AuthService) {
this.$auth = this.authService.$auth();
}
ngOnInit(): void {
return this.$auth.process_authorize_response();
}
}
  1. Register redirect URI in your client's settings and also add in .env. URI should be https://{host}/callback or http://{host}/callback where host can be localhost i.e. localhost:8080 or domain hosting your Angular app i.e. app.my-domain.com.

Add view to initiate login

  1. Using Angular CLI Create login component, add logic to initiate login, and register as route /login.
ng generate component login

In component file add,

app/login/logout.component.ts
import { Component, OnInit } from '@angular/core';
import { AuthService } from '../auth.service';
@Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.scss']
})
export class LoginComponent implements OnInit {
private $auth: any;
constructor(private authService: AuthService) {
this.$auth = authService.$auth();
}
ngOnInit(): void {
return this.$auth.login_with_redirect();
}
}
  1. Your can use login endpoint https://{host}/login or http://{host}/login as post logout uri in your client's settings and also add in .env where where host can be localhost i.e. localhost:8080 or domain hosting your Angular app i.e. app.my-domain.com.

Add view to initiate logout

  1. Using Angular CLI Create logout component, add logic to initiate logout, and register as route /logout.
ng generate component logout

In component file add,

app/logout/logout.component.ts
import { Component, OnInit } from '@angular/core';
import { AuthService } from '../auth.service';
@Component({
selector: 'app-logout',
templateUrl: './logout.component.html',
styleUrls: ['./logout.component.scss']
})
export class LogoutComponent implements OnInit {
private $auth: any;
constructor(private authService: AuthService) {
this.$auth = this.authService.$auth();
}
ngOnInit(): void {
return this.$auth.logout_with_redirect();
}
}

Add Angular router guard

Using web-js, you can guard your Angular router for un-authenticated users and redirect them to login. This authentication guard will utilise canActivate attribute of defined routes.

app/_helpers/auth.guard.ts
import { Injectable } from '@angular/core';
import { Router, CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { AuthService } from '../auth.service';
@Injectable({ providedIn: 'root' })
export class AuthGuard implements CanActivate {
private $auth: any;
constructor(
private router: Router,
private authService: AuthService
) {
this.$auth = this.authService.$auth();
}
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
if (this.$auth.session.is_authenticated()) {
// logged in so return true
return true;
} else {
// not logged in so redirect to login page with the return url
this.router.navigate(['/login'], {});
return false;
}
}
}

Update Angular routing module

srs/app/app-routing.modules.ts
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
const routes: Routes = [];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }

Add Angular routes

srs/app/routing.module.ts
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { CallbackComponent } from './callback/callback.component';
import { LoginComponent } from './login/login.component';
import { LogoutComponent } from './logout/logout.component';
import { AuthGuard } from './_helpers/auth.guard';
const routes: Routes = [
// Routes for web-js authentication and authorization
{ path: 'callback', component: CallbackComponent },
{ path: 'login', component: LoginComponent },
{ path: 'logout', component: LogoutComponent, canActivate: [AuthGuard] }
// Routes for your other protected or private views
/*
{ path: 'dashboard', component: DashboardComponent, canActivate: [AuthGuard] },
*/
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class RoutingModule { }

Angular Sample

To learn more download our Angular sample from our Github repository. In less than 10 minutes you can deploy Angular sample to Netlify.

Deploy to Netlify

Edit sample-angular