npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@colin-etchells/okta-angular

v1.2.3

Published

Angular support for Okta

Downloads

2

Readme

Okta Angular SDK

npm version build status

An Angular wrapper around Okta Auth JS, that builds on top of Okta's OpenID Connect API.

This library currently supports:

This library has been tested for compatibility with the following Angular versions: 4, 5, 6, 7, 8

okta-angular works directly with @angular/router.

Getting Started

  • If you do not already have a Developer Edition Account, you can create one at https://developer.okta.com/signup/.
  • An Okta Application, configured for Single-Page App (SPA) mode. This is done from the Okta Developer Console and you can find instructions here. When following the wizard, use the default properties. They are are designed to work with our sample applications.

Helpful Links

  • Angular Quickstart
    • If you don't have an Angular app, or are new to Angular, please start with this guide. It will walk you through the creation of an Angular app, creating routes, and other application development essentials.
  • Okta Sample Application
    • A fully functional sample application.
  • Okta Angular Quickstart
    • Helpful resource for integrating an existing Angular application into Okta.

Installation

This library is available through npm. To install it, simply add it to your project:

npm install --save @okta/okta-angular

Usage

Add OktaAuthModule to your module's imports. Create a configuration object and provide this as OKTA_CONFIG.

// myApp.module.ts

import {
  OKTA_CONFIG,
  OktaAuthModule
} from '@okta/okta-angular';

const oktaConfig = {
  issuer: 'https://{yourOktaDomain}.com/oauth2/default',
  clientId: '{clientId}',
  redirectUri: 'http://localhost:{port}/implicit/callback'
}

@NgModule({
  imports: [
    ...
    OktaAuthModule
  ],
  providers: [
    { provide: OKTA_CONFIG, useValue: oktaConfig }
  ],
})
export class MyAppModule { }

OKTA_CONFIG

An Angular InjectionToken used to configure the OktaAuthService. This value must be provided by your own application. It is initialized by a plain object which can have the following properties:

  • issuer (required): The OpenID Connect issuer

  • clientId (required): The OpenID Connect client_id

  • redirectUri (required): Where the callback is hosted

  • scope (deprecated in v1.2.2): Use scopes instead

  • scopes (optional): Reserved for custom claims to be returned in the tokens. Defaults to ['openid'], which will only return the sub claim. To obtain more information about the user, use openid profile. For a list of scopes and claims, please see Scope-dependent claims for more information.

  • responseType (optional): Desired token grant types. Default: ['id_token', 'token']. For PKCE flow, this should be left undefined or set to ['code'].

  • pkce (optional): If true, PKCE flow will be used

  • onAuthRequired (optional): Accepts a callback to make a decision when authentication is required. If not supplied, okta-angular will redirect directly to Okta for authentication.

  • storage (optional): Specify the type of storage for tokens. The types are:

    Defaults to localStorage. If local storage is not available, falls back to sessionStorage or cookie.

  • autoRenew (optional): By default, the library will attempt to renew expired tokens. When an expired token is requested by the library, a renewal request is executed to update the token. If you wish to to disable auto renewal of tokens, set autoRenew to false.

OktaAuthModule

The top-level Angular module which provides these components and services:

OktaAuthGuard

Routes are protected by the OktaAuthGuard, which verifies there is a valid accessToken stored. To ensure the user has been authenticated before accessing your route, add the canActivate guard to one of your routes:

// myApp.module.ts

import {
  OktaAuthGuard,
  ...
} from '@okta/okta-angular';

const appRoutes: Routes = [
  {
    path: 'protected',
    component: MyProtectedComponent,
    canActivate: [ OktaAuthGuard ]
  },
  ...
]

If a user does not have a valid session, they will be redirected to the Okta Login Page for authentication. Once authenticated, they will be redirected back to your application's protected page.

OktaCallbackComponent

In order to handle the redirect back from Okta, you need to capture the token values from the URL. You'll use /implicit/callback as the callback URL, and specify the default OktaCallbackComponent and declare it in your NgModule.

// myApp.module.ts
import {
  OktaCallbackComponent,
  ...
} from '@okta/okta-angular';

const appRoutes: Routes = [
  {
    path: 'implicit/callback',
    component: OktaCallbackComponent
  },
  ...
]

@NgModule({
  ...
  declarations: [
    ...
    OktaCallbackComponent
  ]
})

OktaLoginRedirectComponent

By default, the OktaLoginRedirect component redirects users to your Okta organization for login. Simply import and add it to your appRoutes to offset authentication to Okta entirely:

// myApp.module.ts
import {
  OktaLoginRedirectComponent,
  ...
} from '@okta/okta-angular';

const appRoutes: Routes = [
  {
    path: 'login',
    component: OktaLoginRedirectComponent
  },
  ...
]

Using a custom login-page

The okta-angular SDK supports the session token redirect flow for custom login pages. For more information, see the basic Okta Sign-in Widget functionality.

To handle the session-token redirect flow, you can modify the unauthentication callback functionality by adding a data attribute directly to your Route:

// myApp.module.ts

import {
  OktaAuthGuard,
  ...
} from '@okta/okta-angular';

export function onAuthRequired({oktaAuth, router}) {
  // Redirect the user to your custom login page
  router.navigate(['/custom-login']);
}

const appRoutes: Routes = [
  ...
  {
    path: 'protected',
    component: MyProtectedComponent,
    canActivate: [ OktaAuthGuard ],
    data: {
      onAuthRequired: onAuthRequired
    }
  }
]

Alternatively, set this behavior globally by adding it to your configuration object:

const oktaConfig = {
  issuer: environment.ISSUER,
  ...
  onAuthRequired: onAuthRequired
};

OktaAuthService

In your components, your can take advantage of all of okta-angular's features by importing the OktaAuthService. The example below shows connecting two buttons to handle login and logout:

// sample.component.ts

import { OktaAuthService } from '@okta/okta-angular';

@Component({
  selector: 'app-component',
  template: `
    <button *ngIf="!isAuthenticated" (click)="login()">Login</button>
    <button *ngIf="isAuthenticated" (click)="logout()">Logout</button>

    <router-outlet></router-outlet>
  `,
})
export class MyComponent {
  isAuthenticated: boolean;
  constructor(public oktaAuth: OktaAuthService) {
    // get authentication state for immediate use
    await this.isAuthenticated = this.oktaAuth.isAuthenticated();

    // subscribe to authentication state changes
    this.oktaAuth.$authenticatedState.subscribe(
      (isAuthenticated: boolean)  => this.isAuthenticated = isAuthenticated
    );
  }
  login() {
    this.oktaAuth.loginRedirect('/profile');
  }
  logout() {
    this.oktaAuth.logout('/');
  }
}

oktaAuth.loginRedirect(fromUri?, additionalParams?)

Performs a full page redirect to Okta based on the initial configuration. This method accepts a fromUri parameter to push the user to after successful authentication.

The optional parameter additionalParams is mapped to the AuthJS OpenID Connect Options. This will override any existing configuration. As an example, if you have an Okta sessionToken, you can bypass the full-page redirect by passing in this token. This is recommended when using the Okta Sign-In Widget. Simply pass in a sessionToken into the loginRedirect method follows:

this.oktaAuth.loginRedirect('/profile', {
  sessionToken: /* sessionToken */
})

Note: For information on obtaining a sessionToken using the Okta Sign-In Widget, please see the renderEl() example.

oktaAuth.isAuthenticated()

Returns a promise that resolves true if there is a valid access token or ID token.

oktaAuth.$authenticationState

An observable that returns true/false when the authenticate state changes. This will happen after a successful login via oktaAuth.handleAuthentication() or logout via oktaAuth.logout().

oktaAuth.getUser()

Returns a promise that will resolve with the result of the OpenID Connect /userinfo endpoint if an access token is provided, or returns the claims of the ID token if no access token is available. The returned claims depend on the requested response type, requested scopes, and authorization server policies. For more information see documentation for the UserInfo endpoint, ID Token Claims, and Customizing Your Authorization Server.

oktaAuth.getAccessToken() Promise<string>

Returns a promise that returns the access token string from storage (if it exists).

oktaAuth.getIdToken() Promise<string>

Returns a promise that returns the ID token string from storage (if it exists).

oktaAuth.handleAuthentication()

Parses the tokens returned as hash fragments in the OAuth 2.0 Redirect URI, then redirects to the URL specified when calling loginRedirect. Returns a promise that will be resolved when complete.

oktaAuth.logout(uri?)

Terminates the user's session in Okta and clears all stored tokens. Accepts an optional uri parameter to push the user to after logout.

oktaAuth.setFromUri(uri, queryParams)

Used to capture the current URL state before a redirect occurs. Used primarily for custom canActivate navigation guards.

oktaAuth.getFromUri()

Returns the stored URI and query parameters stored when the OktaAuthGuard and/or setFromUri was used.

Contributing

We welcome contributions to all of our open-source packages. Please see the contribution guide to understand how to structure a contribution.

Installing dependencies for contributions

We use yarn for dependency management when developing this package:

yarn install

Commands

| Command | Description | |--------------|------------------------------------| | yarn start | Start the sample app using the SDK | | yarn test | Run unit and integration tests | | yarn lint | Run eslint linting tests |