### Install Okta Angular SDK Source: https://github.com/okta/okta-angular/blob/master/README.md Installs the @okta/okta-angular and @okta/okta-auth-js packages using npm. These are the core dependencies for Okta authentication in Angular. ```bash npm install @okta/okta-angular @okta/okta-auth-js ``` -------------------------------- ### Create New Angular Test App with CLI Source: https://github.com/okta/okta-angular/blob/master/test/apps/README.md Generates a new Angular application using the Angular CLI, specifying the version, directory, and build options. This command is the first step in setting up a new test app for Okta integration. ```bash npx @angular/cli@ new angular-v --directory /test/apps/angular-v --skip-git --inline-template --inline-style --style css --ssr false ``` -------------------------------- ### Configure OktaConfig at Runtime with APP_INITIALIZER Source: https://github.com/okta/okta-angular/blob/master/README.md Loads Okta configuration at runtime using APP_INITIALIZER and OktaAuthConfigService. This allows fetching configuration dynamically, for example, from an API endpoint. ```typescript // myApp.module.ts import { OktaAuthModule, OktaConfig, OktaAuthOptions, OktaAuthConfigService, } from '@okta/okta-angular'; import { OktaAuth } from '@okta/okta-auth-js'; function configInitializer(configService: OktaAuthConfigService, httpBackend: HttpBackend): () => void { return () => new HttpClient(httpBackend) .get('/api/config') .pipe( map((res: any) => ({ issuer: res.issuer, clientId: res.clientId, redirectUri: window.location.origin + '/login/callback' })), tap((authConfig: OktaAuthOptions) => { const oktaAuth = new OktaAuth(authConfig); const moduleConfig: OktaConfig = { oktaAuth }; configService.setConfig(moduleConfig); }), take(1) ); }; @NgModule({ providers: [{ provide: APP_INITIALIZER, useFactory: configInitializer, deps: [OktaAuthConfigService, HttpBackend], multi: true }], imports: [ ... OktaAuthModule ], }) export class MyAppModule { } ``` -------------------------------- ### Install Dependencies with Yarn (Bash) Source: https://github.com/okta/okta-angular/blob/master/README.md This command is used to install project dependencies when contributing to the Okta Angular package. It utilizes Yarn, a package manager, to download and set up all the necessary libraries and tools required for development and testing. ```bash yarn install ``` -------------------------------- ### Configure OktaAuthModule with forRoot() Source: https://github.com/okta/okta-angular/blob/master/README.md Configures the OktaAuthModule using the static forRoot() method, which creates a singleton OktaAuth service instance with provided configuration. This is the preferred method starting from okta-angular 6.1.0. ```typescript // myApp.module.ts import { OktaAuthModule, OktaConfig } from '@okta/okta-angular'; import { OktaAuth } from '@okta/okta-auth-js'; const authConfig = { issuer: 'https://{yourOktaDomain}/oauth2/default', clientId: '{clientId}', redirectUri: window.location.origin + '/login/callback' } const oktaAuth = new OktaAuth(authConfig); const moduleConfig: OktaConfig = { oktaAuth }; @NgModule({ imports: [ ... OktaAuthModule.forRoot(moduleConfig) ], }) export class MyAppModule { } ``` -------------------------------- ### Import OktaAuthModule using forRoot() in Angular Source: https://github.com/okta/okta-angular/blob/master/MIGRATING.md Starting with @okta/okta-angular 6.1.0, OktaAuthModule should be imported using the forRoot() static method for singleton service creation. This replaces the previous method of importing OktaAuthModule directly. ```typescript import { OktaAuthModule } from '@okta/okta-angular'; @NgModule({ imports: [ ... OktaAuthModule.forRoot({ oktaAuth }) ] }) export class MyAppModule { } ``` -------------------------------- ### Configure OktaAuth with OktaAuth instance in Angular Source: https://github.com/okta/okta-angular/blob/master/MIGRATING.md Version 4.0 of @okta/okta-angular requires explicitly providing an OktaAuth instance to OktaConfig. This replaces the internal OktaAuthService and requires @okta/okta-auth-js to be installed as a peer dependency. ```typescript import { OKTA_CONFIG, OktaAuthModule } from '@okta/okta-angular'; import { OktaAuth } from '@okta/okta-auth-js'; const config = { issuer: 'https://{yourOktaDomain}/oauth2/default', clientId: '{clientId}', redirectUri: window.location.origin + '/login/callback' } const oktaAuth = new OktaAuth(config); @NgModule({ imports: [ ... OktaAuthModule ], providers: [ { provide: OKTA_CONFIG, useValue: { oktaAuth } } ], }) export class MyAppModule {} ``` -------------------------------- ### Standalone Components Configuration with Okta Angular SDK Source: https://context7.com/okta/okta-angular/llms.txt Configures Okta Angular SDK in Angular standalone component applications using `importProvidersFrom`. This approach is compatible with Angular 14+ standalone components and does not require NgModules. It uses `bootstrapApplication` and `provideRouter` for setup. ```typescript // main.ts import { bootstrapApplication } from '@angular/platform-browser'; import { importProvidersFrom } from '@angular/core'; import { provideRouter, Routes } from '@angular/router'; import { OktaAuthModule, OktaAuthGuard, OktaCallbackComponent } from '@okta/okta-angular'; import { OktaAuth } from '@okta/okta-auth-js'; import { AppComponent } from './app/app.component'; const oktaAuth = new OktaAuth({ issuer: 'https://dev-123456.okta.com/oauth2/default', clientId: '0oa1234567890abcdef', redirectUri: window.location.origin + '/login/callback', scopes: ['openid', 'profile', 'email'] }); const routes: Routes = [ { path: '', loadComponent: () => import('./app/home.component').then(m => m.HomeComponent) }, { path: 'login/callback', component: OktaCallbackComponent }, { path: 'profile', loadComponent: () => import('./app/profile.component').then(m => m.ProfileComponent), canActivate: [OktaAuthGuard] } ]; bootstrapApplication(AppComponent, { providers: [ provideRouter(routes), importProvidersFrom(OktaAuthModule.forRoot({ oktaAuth })) ] }); // profile.component.ts - Standalone component example import { Component, Inject, OnInit } from '@angular/core'; import { CommonModule } from '@angular/common'; import { OKTA_AUTH, OktaAuthStateService } from '@okta/okta-angular'; import { OktaAuth } from '@okta/okta-auth-js'; @Component({ selector: 'app-profile', standalone: true, imports: [CommonModule], template: `

Profile

Name: {{ auth.idToken?.claims?.name }}

Email: {{ auth.idToken?.claims?.email }}

` }) export class ProfileComponent { authState$ = this.authStateService.authState$; constructor( @Inject(OKTA_AUTH) private oktaAuth: OktaAuth, private authStateService: OktaAuthStateService ) {} } ``` -------------------------------- ### Replace loginRedirect with signInWithRedirect (Angular) Source: https://github.com/okta/okta-angular/blob/master/MIGRATING.md Demonstrates how to replace the deprecated `loginRedirect` method with the new `signInWithRedirect` method in the Okta Angular SDK. The `originalUri` option replaces the `fromUri` parameter, and additional parameters can be passed within the `options` object. ```javascript okta.signInWithRedirect({ originalUri: '/profile', scopes: ['openid', 'profile'] }); ``` -------------------------------- ### Replace logout with signOut (Angular) Source: https://github.com/okta/okta-angular/blob/master/MIGRATING.md Illustrates the replacement of the `logout` method with the `signOut` method in the Okta Angular SDK. The `signOut` method exclusively accepts an options object, and `postLogoutRedirectUri` must be an absolute URL. ```javascript okta.signOut({ postLogoutRedirectUri: window.location.orign + '/goodbye' }); ``` -------------------------------- ### Access TokenManager via tokenManager property (Angular) Source: https://github.com/okta/okta-angular/blob/master/MIGRATING.md Shows how to access the TokenManager in the Okta Angular SDK. The `getTokenManager` method has been removed, and the TokenManager is now directly accessible via the `tokenManager` property. ```javascript const tokens = oktaAuth.tokenManager.getTokens(); ``` -------------------------------- ### Track Auth State using OktaAuthStateService in Angular Source: https://github.com/okta/okta-angular/blob/master/MIGRATING.md In versions 4.x and later, the OktaAuth instance no longer provides an observable auth state. The OktaAuthStateService should be used to track the authentication state in UI components. ```typescript import { Component } from '@angular/core'; import { OktaAuthStateService } from '@okta/okta-angular'; @Component({ selector: 'app-component', template: ` `, }) export class MyComponent { constructor(private authStateService: OktaAuthStateService) {} } ``` -------------------------------- ### Inject OktaAuth instance using OKTA_AUTH token in Angular Source: https://github.com/okta/okta-angular/blob/master/MIGRATING.md From version 5.x, the OktaAuth instance is injected using the OKTA_AUTH injection token instead of implicit type referencing. This change addresses production build issues in Angular 7 & 8. ```typescript import { Component, Inject } from '@angular/core'; import { OKTA_AUTH } from '@okta/okta-angular'; import { OktaAuth } from '@okta/okta-auth-js'; @Component({ selector: 'app-component', template: `
page content
`, }) export class MyComponent { constructor(@Inject(OKTA_AUTH) private oktaAuth: OktaAuth) {} } ``` -------------------------------- ### Runtime Configuration with APP_INITIALIZER in Angular Source: https://context7.com/okta/okta-angular/llms.txt Loads Okta configuration dynamically at runtime using Angular's APP_INITIALIZER. This is useful when configuration values are fetched from an external API or environment-specific endpoints. It requires HttpClient and HttpBackend for fetching configuration and OktaAuthConfigService to set the configuration. ```typescript // app.module.ts import { NgModule, APP_INITIALIZER } from '@angular/core'; import { HttpClient, HttpBackend, HttpClientModule } from '@angular/common/http'; import { OktaAuthModule, OktaConfig, OktaAuthConfigService } from '@okta/okta-angular'; import { OktaAuth } from '@okta/okta-auth-js'; import { map, tap, take } from 'rxjs/operators'; interface AppConfig { okta: { issuer: string; clientId: string; }; } function configInitializer( configService: OktaAuthConfigService, httpBackend: HttpBackend ): () => Promise { return () => new HttpClient(httpBackend) .get('/api/config') .pipe( map(config => ({ issuer: config.okta.issuer, clientId: config.okta.clientId, redirectUri: window.location.origin + '/login/callback', scopes: ['openid', 'profile', 'email'], pkce: true })), tap(authConfig => { const oktaAuth = new OktaAuth(authConfig); const moduleConfig: OktaConfig = { oktaAuth }; configService.setConfig(moduleConfig); }), take(1) ) .toPromise() .then(() => {}); } @NgModule({ imports: [ HttpClientModule, OktaAuthModule // No forRoot() when using APP_INITIALIZER ], providers: [ { provide: APP_INITIALIZER, useFactory: configInitializer, deps: [OktaAuthConfigService, HttpBackend], multi: true } ] }) export class AppModule { } ``` -------------------------------- ### Manage Authentication State with OktaAuthStateService Source: https://github.com/okta/okta-angular/blob/master/README.md Demonstrates how to use OktaAuthStateService to expose authentication state as an observable. This allows UI components to reactively display login/logout buttons based on the user's authentication status. ```typescript // sample.component.ts import { Component, Inject } from '@angular/core'; import { OktaAuth } from '@okta/okta-auth-js'; import { OktaAuthStateService, OKTA_AUTH } from '@okta/okta-angular'; @Component({ selector: 'app-component', template: ` `, }) export class MyComponent { constructor( @Inject(OKTA_AUTH) public oktaAuth: OktaAuth, private authStateService: OktaAuthStateService ) {} async login() { await this.oktaAuth.signInWithRedirect(); } async logout() { await this.oktaAuth.signOut(); } } ``` -------------------------------- ### Inject OktaAuth Instance in Angular Source: https://github.com/okta/okta-angular/blob/master/README.md Demonstrates how to inject the OktaAuth instance using the OKTA_AUTH token in an Angular component. This allows direct interaction with the OktaAuth SDK for managing authentication states and user information. ```typescript import { Component, Inject, OnInit } from '@angular/core'; import { OKTA_AUTH } from '@okta/okta-angular'; import { OktaAuth } from '@okta/okta-auth-js'; @Component({ selector: 'app-component', template: `
{{ user | json }}
`, }) export class MyProtectedComponent implements OnInit { user: string = ''; constructor(@Inject(OKTA_AUTH) private oktaAuth: OktaAuth) {} async ngOnInit() { const user = await this.oktaAuth.getUser(); } } ``` -------------------------------- ### Configure Custom Login Page with OktaConfig Source: https://github.com/okta/okta-angular/blob/master/README.md Details how to set up a custom login page using the Okta Signin Widget by providing an `onAuthRequired` callback in the `OktaConfig`. This callback handles the authentication process without redirects. ```typescript // myApp.module.ts function onAuthRequired(oktaAuth, injector, options) { // `options` object can contain `acrValues` if it was provided in route data // Use injector to access any service available within your application const router = injector.get(Router); // Redirect the user to your custom login page router.navigate(['/custom-login']); } const oktaAuth = new OktaAuth({ ... }); @NgModule({ imports: [ ... OktaAuthModule.forRoot({oktaAuth, onAuthRequired}) ], }) export class MyAppModule { } ``` -------------------------------- ### Configure OktaCallbackComponent Route Source: https://github.com/okta/okta-angular/blob/master/README.md Defines a route for the Okta callback URL, typically '/login/callback', to handle the redirect after user authentication. This route uses the OktaCallbackComponent to process authentication tokens. ```typescript // myApp.module.ts import { OktaCallbackComponent, ... } from '@okta/okta-angular'; const appRoutes: Routes = [ { path: 'login/callback', component: OktaCallbackComponent }, ... ] ``` -------------------------------- ### Protect Routes with OktaAuthGuard in Angular Source: https://github.com/okta/okta-angular/blob/master/README.md Illustrates how to use the OktaAuthGuard to protect Angular routes, ensuring users are authenticated before accessing specific components. The guard verifies the presence of a valid idToken. ```typescript // myApp.module.ts import { OktaAuthGuard, ... } from '@okta/okta-angular'; const appRoutes: Routes = [ { path: 'protected', component: MyProtectedComponent, canActivate: [ OktaAuthGuard ], children: [{ // children of a protected route are also protected path: 'also-protected' }] }, ... ] ``` -------------------------------- ### Test AppComponent with Mocked OktaAuth Source: https://context7.com/okta/okta-angular/llms.txt Demonstrates testing an Angular AppComponent that uses Okta authentication. It mocks the `OktaAuth` service and `OktaAuthStateService` to simulate authentication states and verify component behavior, such as showing a login button or initiating the login process. ```javascript // app.component.spec.ts - Testing with mocked OktaAuth import { ComponentFixture, TestBed } from '@angular/core/testing'; import { RouterTestingModule } from '@angular/router/testing'; import { OktaAuthModule, OKTA_AUTH, OktaAuthStateService } from '@okta/okta-angular'; import { OktaAuth } from '@okta/okta-auth-js'; import { BehaviorSubject } from 'rxjs'; import { AppComponent } from './app.component'; describe('AppComponent', () => { let component: AppComponent; let fixture: ComponentFixture; let mockOktaAuth: jasmine.SpyObj; let authState$: BehaviorSubject; beforeEach(async () => { authState$ = new BehaviorSubject({ isAuthenticated: false }); mockOktaAuth = jasmine.createSpyObj('OktaAuth', [ 'signInWithRedirect', 'signOut', 'getUser', 'isAuthenticated' ], { authStateManager: { getAuthState: () => authState$.value, subscribe: (fn: any) => authState$.subscribe(fn), unsubscribe: () => {} } }); await TestBed.configureTestingModule({ imports: [RouterTestingModule], declarations: [AppComponent], providers: [ { provide: OKTA_AUTH, useValue: mockOktaAuth }, { provide: OktaAuthStateService, useValue: { authState$ } } ] }).compileComponents(); fixture = TestBed.createComponent(AppComponent); component = fixture.componentInstance; }); it('should show login button when not authenticated', () => { authState$.next({ isAuthenticated: false }); fixture.detectChanges(); const loginBtn = fixture.nativeElement.querySelector('button'); expect(loginBtn.textContent).toContain('Login'); }); it('should call signInWithRedirect on login', async () => { await component.login(); expect(mockOktaAuth.signInWithRedirect).toHaveBeenCalled(); }); }); ``` -------------------------------- ### Configure OktaAuthModule with OktaAuth Instance in Angular Source: https://context7.com/okta/okta-angular/llms.txt Configures the Okta Angular SDK by creating a singleton OktaAuth service. This method is typically called in the application's root module and requires an OktaAuth instance with issuer, clientId, redirectUri, and scopes. ```typescript import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { RouterModule, Routes } from '@angular/router'; import { OktaAuthModule, OktaAuthGuard, OktaCallbackComponent } from '@okta/okta-angular'; import { OktaAuth } from '@okta/okta-auth-js'; const oktaAuth = new OktaAuth({ issuer: 'https://dev-123456.okta.com/oauth2/default', clientId: '0oa1234567890abcdef', redirectUri: window.location.origin + '/login/callback', scopes: ['openid', 'profile', 'email'], pkce: true }); const routes: Routes = [ { path: '', component: HomeComponent }, { path: 'login/callback', component: OktaCallbackComponent }, { path: 'protected', component: ProtectedComponent, canActivate: [OktaAuthGuard] } ]; @NgModule({ imports: [ BrowserModule, RouterModule.forRoot(routes), OktaAuthModule.forRoot({ oktaAuth }) ], declarations: [HomeComponent, ProtectedComponent], bootstrap: [AppComponent] }) export class AppModule { } ``` -------------------------------- ### Lazy Loading Protected Modules with OktaAuthGuard Source: https://github.com/okta/okta-angular/blob/master/README.md Explains how to use `canLoad` with OktaAuthGuard to protect lazily loaded modules. This ensures that the module is only loaded after the user has been successfully authenticated, improving initial load performance. ```typescript // myApp.module.ts import { OktaAuthGuard, ... } from '@okta/okta-angular'; const appRoutes: Routes = [ { path: 'lazy', canLoad: [ OktaAuthGuard ], loadChildren: () => import('./lazy-load/lazy-load.module').then(mod => mod.LazyLoadModule) }, ... ] ``` -------------------------------- ### Configure OktaAuthModule with OKTA_CONFIG Source: https://github.com/okta/okta-angular/blob/master/README.md Configures the OktaAuthModule by providing an OktaAuth instance via the OKTA_CONFIG injection token. This is a common method for setting up Okta authentication in an Angular application's root module. ```typescript // myApp.module.ts import { OKTA_CONFIG, OktaAuthModule } from '@okta/okta-angular'; import { OktaAuth } from '@okta/okta-auth-js'; const authConfig = { issuer: 'https://{yourOktaDomain}/oauth2/default', clientId: '{clientId}', redirectUri: window.location.origin + '/login/callback' } const oktaAuth = new OktaAuth(authConfig); @NgModule({ imports: [ ... OktaAuthModule ], providers: [ { provide: OKTA_CONFIG, useValue: { oktaAuth } } ], }) export class MyAppModule { } ``` -------------------------------- ### Configure Jest for Okta Angular Transformations (JavaScript) Source: https://github.com/okta/okta-angular/blob/master/README.md This code snippet shows how to configure Jest for testing applications using `@okta/okta-angular`. It involves adding `@okta/okta-angular` and its dependencies to the `transformIgnorePatterns` in your `jest.config.js` file. This is necessary because `@okta/okta-angular` version 6 exports files using the `.js` extension, which Jest needs to be configured to transform. ```javascript export default { preset: 'jest-preset-angular', transformIgnorePatterns: [ 'node_modules/(?!.*\.mjs$|rxjs|@okta/okta-auth-js|jsonpath-plus|@okta/okta-angular)' ], ... } ``` -------------------------------- ### Implement Role-Based Access Control with OktaHasAnyGroup Directive Source: https://github.com/okta/okta-angular/blob/master/README.md Shows how to use the OktaHasAnyGroup directive for lite role-based access control, allowing content to be rendered only for authenticated users belonging to specified groups. It supports string, array, and object formats for group names. ```typescript @Component({ template: `
In group
` }) class RBACComponent { } @Component({ template: `
In group
` }) class RBACComponent { } ``` -------------------------------- ### Configure Jest for Okta Angular SDK Testing Source: https://context7.com/okta/okta-angular/llms.txt Configures Jest to test Angular applications using the Okta Angular SDK. It specifies necessary `transformIgnorePatterns` and `moduleNameMapper` to correctly handle ES module exports from the SDK and its dependencies. ```javascript // jest.config.js export default { preset: 'jest-preset-angular', setupFilesAfterEnv: ['/setup-jest.ts'], testPathIgnorePatterns: ['/node_modules/', '/dist/'], transformIgnorePatterns: [ 'node_modules/(?!.*\.mjs$|rxjs|@okta/okta-auth-js|jsonpath-plus|@okta/okta-angular)' ], moduleNameMapper: { '^@okta/okta-angular$': '/node_modules/@okta/okta-angular' } }; ``` -------------------------------- ### Route Protection with ACR Values using OktaAuthGuard Source: https://github.com/okta/okta-angular/blob/master/README.md Shows how to configure OktaAuthGuard to enforce specific levels of end-user assurance (ACR values) for route access. This is achieved by adding `acrValues` to the route's data configuration. ```typescript // myApp.module.ts import { OktaAuthGuard } from '@okta/okta-angular'; const appRoutes: Routes = [ { path: 'protected', component: MyProtectedComponent, canActivate: [ OktaAuthGuard ], data: { okta: { // requires any 2 factors before accessing the route acrValues: 'urn:okta:loa:2fa:any' } }, }, ... ] ``` -------------------------------- ### Protect Routes with OktaAuthGuard (Angular) Source: https://context7.com/okta/okta-angular/llms.txt The OktaAuthGuard implements route protection by verifying ID tokens and optionally checking authentication assurance levels. It can be used with `canActivate`, `canActivateChild`, and `canLoad` interfaces. Dependencies include `@okta/okta-angular` and `@angular/router`. ```typescript // app-routing.module.ts import { NgModule } from '@angular/core'; import { RouterModule, Routes } from '@angular/router'; import { OktaAuthGuard, OktaCallbackComponent } from '@okta/okta-angular'; const routes: Routes = [ { path: '', component: HomeComponent }, { path: 'login/callback', component: OktaCallbackComponent }, // Basic protected route { path: 'dashboard', component: DashboardComponent, canActivate: [OktaAuthGuard] }, // Protected route with step-up authentication (requires 2FA) { path: 'admin', component: AdminComponent, canActivate: [OktaAuthGuard], data: { okta: { acrValues: 'urn:okta:loa:2fa:any' // Requires any 2-factor authentication } } }, // Protect child routes { path: 'account', component: AccountLayoutComponent, canActivateChild: [OktaAuthGuard], children: [ { path: 'settings', component: SettingsComponent }, { path: 'billing', component: BillingComponent } ] }, // Lazy-loaded protected module { path: 'reports', canLoad: [OktaAuthGuard], loadChildren: () => import('./reports/reports.module').then(m => m.ReportsModule) } ]; @NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule] }) export class AppRoutingModule { } ``` -------------------------------- ### Protect Child Routes with OktaAuthGuard in Angular Source: https://github.com/okta/okta-angular/blob/master/README.md Demonstrates using `canActivateChild` with OktaAuthGuard to protect child routes within an otherwise public parent route. This allows for granular control over access to nested routing. ```typescript // myApp.module.ts import { OktaAuthGuard, ... } from '@okta/okta-angular'; const appRoutes: Routes = [ { path: 'public', component: MyPublicComponent, canActivateChild: [ OktaAuthGuard ], children: [{ path: 'protected', component: MyProtectedComponent }] }, ... ] ``` -------------------------------- ### Access OktaAuth Instance for User Operations in Angular Component Source: https://context7.com/okta/okta-angular/llms.txt Provides direct access to the OktaAuth instance within an Angular component using the OKTA_AUTH injection token. This allows for performing authentication operations such as user sign-in, sign-out, and retrieving user claims. ```typescript import { Component, Inject, OnInit } from '@angular/core'; import { OKTA_AUTH } from '@okta/okta-angular'; import { OktaAuth, UserClaims } from '@okta/okta-auth-js'; @Component({ selector: 'app-user-profile', template: `

Welcome, {{ user.name }}

Email: {{ user.email }}

{{ user | json }}
` }) export class UserProfileComponent implements OnInit { user: UserClaims | null = null; constructor(@Inject(OKTA_AUTH) private oktaAuth: OktaAuth) {} async ngOnInit(): Promise { // Get user claims from ID token or userinfo endpoint this.user = await this.oktaAuth.getUser(); } async logout(): Promise { // Sign out and redirect to home page await this.oktaAuth.signOut({ postLogoutRedirectUri: window.location.origin }); } } ``` -------------------------------- ### Configure Custom Login Page via Route Data Source: https://github.com/okta/okta-angular/blob/master/README.md An alternative method to configure a custom login page for specific routes by adding an `onAuthRequired` data attribute to the route definition. This allows for route-specific authentication handling. ```typescript // myApp.module.ts const appRoutes: Routes = [ ... { path: 'protected', component: MyProtectedComponent, canActivate: [ OktaAuthGuard ], data: { onAuthRequired: onAuthRequired } } ] ``` -------------------------------- ### Custom Login Page with onAuthRequired Callback Source: https://context7.com/okta/okta-angular/llms.txt This configuration demonstrates how to implement a custom login experience in an Angular application using the `onAuthRequired` callback. Instead of redirecting to Okta's hosted login page, this allows you to embed authentication directly using the Okta Sign-In Widget or a custom form. The `onAuthResume` callback is also provided for handling authentication flow resumption. ```typescript // app.module.ts import { NgModule, Injector } from '@angular/core'; import { Router } from '@angular/router'; import { OktaAuthModule, OktaConfig } from '@okta/okta-angular'; import { OktaAuth, TokenParams } from '@okta/okta-auth-js'; function onAuthRequired(oktaAuth: OktaAuth, injector: Injector, options?: TokenParams): void { const router = injector.get(Router); // Redirect to custom login page, preserving any ACR requirements router.navigate(['/login'], { queryParams: options?.acrValues ? { acr: options.acrValues } : {} }); } function onAuthResume(oktaAuth: OktaAuth, injector: Injector): void { const router = injector.get(Router); // Resume flow on custom login page (for external IdP callbacks) router.navigate(['/login']); } const oktaAuth = new OktaAuth({ issuer: 'https://dev-123456.okta.com/oauth2/default', clientId: '0oa1234567890abcdef', redirectUri: window.location.origin + '/login/callback', scopes: ['openid', 'profile', 'email'] }); const moduleConfig: OktaConfig = { oktaAuth, onAuthRequired, onAuthResume }; @NgModule({ imports: [ OktaAuthModule.forRoot(moduleConfig) ] }) export class AppModule { } // login.component.ts - Custom login page with Okta Sign-In Widget import { Component, OnInit, OnDestroy, Inject } from '@angular/core'; import { OKTA_AUTH } from '@okta/okta-angular'; import { OktaAuth } from '@okta/okta-auth-js'; import OktaSignIn from '@okta/okta-signin-widget'; @Component({ selector: 'app-login', template: `
` }) export class LoginComponent implements OnInit, OnDestroy { widget: OktaSignIn; constructor(@Inject(OKTA_AUTH) private oktaAuth: OktaAuth) { this.widget = new OktaSignIn({ baseUrl: 'https://dev-123456.okta.com', clientId: '0oa1234567890abcdef', redirectUri: window.location.origin + '/login/callback', authParams: { issuer: 'https://dev-123456.okta.com/oauth2/default', scopes: ['openid', 'profile', 'email'] } }); } ngOnInit(): void { this.widget.showSignInToGetTokens({ el: '#okta-signin-container' }).then(tokens => { this.oktaAuth.handleLoginRedirect(tokens); }).catch(err => { console.error('Login error:', err); }); } ngOnDestroy(): void { this.widget.remove(); } } ``` -------------------------------- ### Handle OAuth Redirects with OktaCallbackComponent (Angular) Source: https://context7.com/okta/okta-angular/llms.txt The OktaCallbackComponent is a built-in component that handles the OAuth redirect callback. It parses tokens from the URL, stores them in the token manager, and redirects the user. It can be customized for error handling. Dependencies include `@okta/okta-angular` and `@angular/router`. ```typescript // app-routing.module.ts import { Routes } from '@angular/router'; import { OktaCallbackComponent } from '@okta/okta-angular'; const routes: Routes = [ // Standard callback route - handles token parsing and storage { path: 'login/callback', component: OktaCallbackComponent } ]; // For custom error handling, create your own callback component: // custom-callback.component.ts import { Component, OnInit, Inject } from '@angular/core'; import { Router } from '@angular/router'; import { OKTA_AUTH } from '@okta/okta-angular'; import { OktaAuth } from '@okta/okta-auth-js'; @Component({ selector: 'app-custom-callback', template: `

Authentication Error

{{ error }}

Return to Home Contact Support

Processing authentication...

` }) export class CustomCallbackComponent implements OnInit { error: string | null = null; constructor( @Inject(OKTA_AUTH) private oktaAuth: OktaAuth, private router: Router ) {} async ngOnInit(): Promise { try { await this.oktaAuth.handleLoginRedirect(); } catch (e) { this.error = (e as Error).message; console.error('Authentication callback error:', e); } } } ``` -------------------------------- ### Manage Authentication State with OktaAuthStateService (Angular) Source: https://context7.com/okta/okta-angular/llms.txt The OktaAuthStateService exposes an observable `authState$` stream for reactive authentication state management. Components can subscribe to authentication changes and update the UI accordingly without manual polling. It requires `@okta/okta-angular` and `rxjs`. ```typescript // app.component.ts import { Component, Inject } from '@angular/core'; import { OktaAuthStateService, OKTA_AUTH } from '@okta/okta-angular'; import { OktaAuth, AuthState } from '@okta/okta-auth-js'; import { Observable } from 'rxjs'; import { map } from 'rxjs/operators'; @Component({ selector: 'app-root', template: ` ` }) export class AppComponent { authState$: Observable; userName$: Observable; constructor( @Inject(OKTA_AUTH) private oktaAuth: OktaAuth, public authStateService: OktaAuthStateService ) { this.authState$ = this.authStateService.authState$; this.userName$ = this.authState$.pipe( map(state => state.idToken?.claims?.name || 'User') ); } async login(): Promise { await this.oktaAuth.signInWithRedirect(); } async logout(): Promise { await this.oktaAuth.signOut(); } } ``` -------------------------------- ### Configure onAuthResume for Custom Login Resumption (TypeScript) Source: https://github.com/okta/okta-angular/blob/master/README.md This snippet demonstrates how to define an `onAuthResume` function within your Okta Angular module configuration. This function is invoked when the authentication flow needs to be resumed, typically after a redirect. It allows you to implement custom logic, such as redirecting the user to a custom login page that renders the OktaSignIn Widget. The function receives `oktaAuth` and `injector` as arguments, enabling access to application services like the Router. ```typescript // myApp.module.ts function onAuthResume(oktaAuth, injector) { // Use injector to access any service available within your application const router = injector.get(Router); // Redirect the user to custom login page which renders the Okta SignIn Widget router.navigate(['/custom-login']); } const oktaConfig = { ... onAuthResume: onAuthResume }; ``` -------------------------------- ### Conditional Content Rendering with OktaHasAnyGroup Directive Source: https://context7.com/okta/okta-angular/llms.txt The OktaHasAnyGroup directive conditionally renders HTML content based on the authenticated user's group membership. It supports single group strings, arrays of groups, and custom group claims for flexible access control. This directive is useful for implementing role-based access control (RBAC) within your Angular application. ```typescript // admin-dashboard.component.ts import { Component } from '@angular/core'; @Component({ selector: 'app-admin-dashboard', template: `

Admin Panel

Moderation Tools

Developer Tools

View Deployments

Premium Features

Access to advanced analytics and reporting

` }) export class AdminDashboardComponent { deleteUser(): void { /* implementation */ } approveContent(): void { /* implementation */ } } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.