How to Integrate Okta SSO Authentication in an Angular App

Krishna KV
Technology Specialist
October 8, 2018
Rate this article
Views    11787

Authentication is one of the key aspects of any enterprise application. Okta as an enterprise class Identity Provider, helps us to enable Single SignOn (SSO) across applications within in an Enterprise. As an Angular application is a Single Page App (SPA), JWT based authentication is the recommended authentication approach and this article explains how to enable SSO with JWT authentication for an Angular application with Okta.

Let’s start by creating Angular 6 Application using CLI and create a free developer Okta account at https://developer.okta.com/

As a next step, add the users and groups in okta

Okta SSO Account Creation

okta sso group

Create an Application, In Okta for the authentication.

okta application

 

app type

Add the URL’s going to used by the OKTA and the assign group(s) used by the applications.

app info

 

After creating the Application, It will display the client ID, which is used by the angular application.

client id

Angular Application

If you have not installed the Angular CLI, install it from https://cli.angular.io/

Create a new application using ng new secure-site command.

It will create an application with basic layout and files to run the Angular 6 Application.

Let’s create two components home and project component, home is an anonymous and project with Authentication page.

AuthGuard

It is used to secure the authentication Page.

import { Injectable } from '@angular/core';
import { ActivatedRouteSnapshot, CanActivate, Router, RouterStateSnapshot } from '@angular/router';
import { OAuthService } from 'angular-oauth2-oidc';

@Injectable()
export class AuthGuard implements CanActivate {

    constructor(private oAuthSvc: OAuthService, private router: Router) { }

    public canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
        if (this.oAuthSvc.hasValidIdToken() && this.oAuthSvc.hasValidAccessToken()) { // Check for the authentication token.
            return true;
        } else {
            this.oAuthSvc.initImplicitFlow(state.url);
            return false;
        }
    }

    public canActivateChild(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
        return this.canActivate(route, state);
    }
}

Okta.Service.ts // It is used to configure the okta for the angular application

import { AuthConfig, OAuthService, JwksValidationHandler } from "angular-oauth2-oidc";
import { Router } from "@angular/router";
import { Injectable } from "@angular/core";

@Injectable()

export class OktaService {
    constructor(private oauthService: OAuthService, private router: Router) {
    }
    public okta: AuthConfig = {
        issuer: '[OktaURL]',
        oidc: true,
        redirectUri: window.location.origin + '/login',
        postLogoutRedirectUri: window.location.origin + '/home',
        clientId: '[clientId]',
        scope: 'openid profile email',
        showDebugInformation: true,
    };
    public configure() {
        const oauthService = this.oauthService;
        const router = this.router;
        oauthService.configure(this.okta);
        oauthService.tokenValidationHandler = new JwksValidationHandler();
        oauthService.showDebugInformation = true;
        oauthService.loadDiscoveryDocument().then((doc) => {
            oauthService.tryLogin({
                onTokenReceived: (context) => {
                    router.navigateByUrl(context.state);
                },
                onLoginError: (context) => {
                    console.log('error', context);
                }
            });
        });
    }

    public getClaims() {
        return this.oauthService.getIdentityClaims();
    }
}

App-routing.module.ts

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { RouterModule, Routes } from '@angular/router';
import { HomeComponent } from './home/home.component';
import { MyProjectsComponent } from './project/my-projects/my-projects.component';
import { AuthGuard } from './authenticate/auth.guard';
import { LoginComponent } from './authenticate/login.component';
const routes: Routes = [
  { path: '', redirectTo: '/home', pathMatch: 'full' },
  { path: 'home', component: HomeComponent },
  { path: 'login', component: LoginComponent },
  { path: 'project', component: MyProjectsComponent, canActivate: [AuthGuard] } //Add AuthGuard to secure the page.
];

@NgModule({
  imports: [
    RouterModule.forRoot(routes),
    CommonModule
  ],
  declarations: [],
  exports: [RouterModule]
})
export class AppRoutingModule { }

Clone/Download from GitHub.

In next article on Okta SSO, we can see how to validate the token from Express JS

Subscribe To Our Newsletter
Loading

Leave a comment