Hey devs! 👋 In this guide, we’ll integrate OAuth 2.0 + OpenID Connect step by step. If you followed my previous article on Okta setup, you’re all set to continue!


What We’ll Cover

✅ Installing the Okta Angular SDK
✅ Setting up Okta configuration
✅ Creating an Okta authentication service
✅ Adding logic to Login component
✅ Updating Angular routing
✅ Checking if the user is logged in

Let’s get started! 🎯


📌 Step 1: Install Okta SDK

Run this command to install the Okta Angular SDK:

npm install @okta/okta-angular

This package simplifies authentication in Angular apps using OAuth 2.0 & OIDC.


📌 Step 2: Create okta.config.ts

import { OktaAuthOptions } from '@okta/okta-auth-js';

export const oktaConfig: OktaAuthOptions = {
    issuer: 'https://dev-your_acc.okta.com/oauth2/default',
    clientId: 'your_client_id',
    redirectUri: `${window.location.origin}/login/callback`,
    pkce: true,
    scopes: ['openid', 'profile', 'email'],
};

🔹 Why This Matters?

Issuer → Your Okta domain.

Client ID → From your Okta app.

Redirect URI → Must match Okta settings.

Scopes → Controls what user info can be accessed.



📌 Step 3: Create Okta Auth Service

import { Inject, Injectable } from '@angular/core';

import { OKTA_AUTH } from '@okta/okta-angular';
import { OktaAuth } from '@okta/okta-auth-js';

@Injectable({
    providedIn: 'root',
})
export class OktaAuthService {
  public isAuthenticated$ = new BehaviorSubject<boolean>(false);

    constructor(@Inject(OKTA_AUTH) private oktaAuth: OktaAuth) {}

    public async signIn(): Promise<void> {
        await this.oktaAuth.signInWithRedirect();
    }

    public async signOut() {
        await this.oktaAuth.signOut();
    }

    public getAccessToken() {
        return this.oktaAuth.getAccessToken();
    }

    public isAuthenticated() {
        return this.oktaAuth.authStateManager.getAuthState()?.isAuthenticated;
    }
}

📌 Step 4: Update/create login.component.ts

import { Component } from '@angular/core';
import { OktaAuthService } from '../okta-auth.service';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrl: './login.component.scss',
})
export class LoginComponent {
  constructor(private oktaService: OktaAuthService) {}

  public async login() {
    await this.oktaService.signIn();
  }
}

📌 Step 5: Update app.routes.ts

import { Routes } from '@angular/router';
import { OktaCallbackComponent } from '@okta/okta-angular';
import { AuthGuard } from './shared/guards/auth.guard';

export const routes: Routes = [
    {
        path: '',
        redirectTo: 'main',
        pathMatch: 'full',
    },
    {
        path: 'login/callback',//Handles Okta’s redirect callback after login.
        component: OktaCallbackComponent,
    },
    {
        path: 'login',
        loadChildren: () => import('./pages/login/login.module').then(m => m.LoginModule),
    },
    {
        path: 'main',
        loadChildren: () => import('./pages/main/main.module').then(m => m.MainModule),
        canActivate: [AuthGuard],
        data: {
            okta: { acrValues: 'urn:okta:loa:2fa:any' },
        },
    },
];

📌 Step 6: Update app.config.ts (e.g. This ensures OktaAuth is globally available in your app.)

import { ApplicationConfig, importProvidersFrom } from '@angular/core';
import { provideRouter } from '@angular/router';
import { provideAnimationsAsync } from '@angular/platform-browser/animations/async';
import { provideAnimations } from '@angular/platform-browser/animations';

import { OktaAuthModule } from '@okta/okta-angular';
import { OktaAuth } from '@okta/okta-auth-js';

import { routes } from './app.routes';
import { oktaConfig } from './configs/okta.config';

export const appConfig: ApplicationConfig = {
  providers: [
    provideRouter(routes),
    provideAnimationsAsync(),
    provideAnimations(),
    importProvidersFrom(
      OktaAuthModule.forRoot({
          oktaAuth: new OktaAuth({
              ...oktaConfig,
          }),
      }),
  ),
  ]
};

📌 Step 7: Check If User is Logged In and Set Auth State

import { CommonModule } from '@angular/common';
import { Component } from '@angular/core';
import { RouterOutlet } from '@angular/router';

import { OktaAuthService } from './shared/services/okta-auth.service';

@Component({
    selector: 'app-root',
    standalone: true,
    imports: [RouterOutlet, CommonModule],
    templateUrl: './app.component.html',
    styleUrl: './app.component.scss',
})
export class AppComponent {
    constructor(private oktaService: OktaAuthService) {}

    ngOnInit() {
        this.oktaService.isAuthenticated$.next(this.oktaService.isAuthenticated() || false);
    }
}

🎯 Now your Angular app is secured with Okta authentication!

➡️ In my next article, we’ll secure API requests with access tokens & backend verification. Stay tuned!

Got questions? Drop them in the comments!