angularoktaangular-providersangular17

ERROR NullInjectorError: NullInjectorError: No provider for OktaAuthStateService


Attempting to implement a guard with Okta authentication in Angular v17, I encountered an error indicating a lack of provider for the OktaAuthStateService.
Upon logging in through Okta, I gain access to the login status component. However, when attempting to navigate to the dashboard using routes, I encounter an error related to the absence of a provider, specifically the OktaAuthStateService.

auth.guard.ts

import { Router, UrlTree, } from '@angular/router';
import {  Injectable } from '@angular/core';
import { OktaAuthStateService } from '@okta/okta-angular';
import { Observable, map, take } from 'rxjs';

@Injectable({ providedIn: 'root' }) export class AuthGuard { constructor( public authStateService: OktaAuthStateService, private router: Router ) {}

canActivate(): Observable<boolean | UrlTree> { 
return this.authStateService.authState$.pipe( map((loggedIn) => { console.log('loggedIn', loggedIn);
if (!loggedIn) {
      this.router.navigate(['/login']);
      return false;
    }
    return true;
  }),
  take(1)
);
} }

app.module.ts


import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { OktaAuthModule, OKTA_CONFIG } from '@okta/okta-angular';
import { OktaAuth } from '@okta/okta-auth-js';
import myAppConfig from './app.config';
const oktaConfig = myAppConfig.oidc;
const oktaAuth = new OktaAuth(oktaConfig);

@NgModule({
declarations: [],
imports: [OktaAuthModule],
providers: [{ provide: OKTA_CONFIG, useValue: { oktaAuth } }],
bootstrap: [AppComponent],
})
export class AppModule {}

app.routes.ts


import { Routes, mapToCanActivate } from '@angular/router';
import { OktaCallbackComponent, OktaAuthGuard } from '@okta/okta-angular';
import { LoginComponent } from './modules/auth/components/login/login.component';
import { AuthGuard } from './core/guards/auth.guard';
import { DashboardComponent } from './modules/pages/dashboard/dashboard.component';
import { LoginStatusComponent } from './modules/auth/components/login-status/login-status.component';
import { CommonGuard } from './core/guards/common.guard';

export const routes: Routes = [
{
path: '',
redirectTo: 'login',
pathMatch: 'full',
},
{
path: 'login',
component: LoginComponent,
},
{ path: 'login-status', component: LoginStatusComponent },
{ path: 'implicit/callback', component: OktaCallbackComponent },
{
path: 'dashboard',
canActivate: mapToCanActivate([AuthGuard]),
component: DashboardComponent,
},
];

Solution

  • The problem has been resolved with the following configuration update:

    app.config.ts

    export const appConfig: ApplicationConfig = {
      providers: [
        importProvidersFrom(
          OktaAuthModule.forRoot({ oktaAuth }),
        ),
      ],
    };