DEV Community

Yevheniia
Yevheniia

Posted on

πŸ” Angular Authentication with Okta – Secure Your App in Minutes

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'],
};

Enter fullscreen mode Exit fullscreen mode

πŸ”Ή 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;
    }
}


Enter fullscreen mode Exit fullscreen mode

πŸ“Œ 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();
  }
}
Enter fullscreen mode Exit fullscreen mode

πŸ“Œ 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' },
        },
    },
];

Enter fullscreen mode Exit fullscreen mode

πŸ“Œ 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,
          }),
      }),
  ),
  ]
};



Enter fullscreen mode Exit fullscreen mode

πŸ“Œ 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);
    }
}

Enter fullscreen mode Exit fullscreen mode

🎯 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!

Top comments (0)