All Projects → source-inc → ng-oidc-client

source-inc / ng-oidc-client

Licence: MIT license
A package for managing OpenID-Connect authentication in Angular apps, wrapping oidc-client-js

Programming Languages

typescript
32286 projects
HTML
75241 projects
javascript
184084 projects - #8 most used programming language
CSS
56736 projects

Projects that are alternatives of or similar to ng-oidc-client

AspNetCore6Experiments
ASP.NET Core Blazor BFF with Azure AD and Razor page
Stars: ✭ 43 (-10.42%)
Mutual labels:  oidc
AspNetCoreBackChannelLogout
ASP.NET Core Back-Channel Logout for Hybrid Clients, Redis, Key Vault, Azure
Stars: ✭ 17 (-64.58%)
Mutual labels:  oidc
example-oidc
OIDC (OpenID Connect) Example for http://openid.net/connect/
Stars: ✭ 221 (+360.42%)
Mutual labels:  oidc
loginapp
Web application for Kubernetes CLI configuration with OIDC
Stars: ✭ 74 (+54.17%)
Mutual labels:  oidc
wired-vpn
WireGuard behind OIDC
Stars: ✭ 21 (-56.25%)
Mutual labels:  oidc
casdoor-go-sdk
Go client SDK for Casdoor
Stars: ✭ 37 (-22.92%)
Mutual labels:  oidc
ms-identity-javascript-tutorial
A chapterwise tutorial that will take you through the fundamentals of modern authentication with Microsoft identity platform in Vanilla JavaScript.
Stars: ✭ 100 (+108.33%)
Mutual labels:  oidc
angular-auth-oidc-sample-google-openid
Angular oidc client with google Identity OpenID
Stars: ✭ 23 (-52.08%)
Mutual labels:  oidc
sotsera.blazor.oidc
OpenID Connect client for Blazor client-side projects
Stars: ✭ 21 (-56.25%)
Mutual labels:  oidc
okta-react-native-spring-boot-example
React Native + Spring Boot + OIDC
Stars: ✭ 24 (-50%)
Mutual labels:  oidc
fab-oidc
Flask-AppBuilder SecurityManager for OpenIDConnect
Stars: ✭ 28 (-41.67%)
Mutual labels:  oidc
auth-backends
Custom authentication backends and views for edX services
Stars: ✭ 20 (-58.33%)
Mutual labels:  oidc
authentik
The authentication glue you need.
Stars: ✭ 2,941 (+6027.08%)
Mutual labels:  oidc
dex-operator
A Kubernetes operator for Dex
Stars: ✭ 16 (-66.67%)
Mutual labels:  oidc
oidckube
Wrapper for minikube that provisions and integrates it with Keycloak
Stars: ✭ 40 (-16.67%)
Mutual labels:  oidc
token-cli
Command line utility for interacting with OAuth2 infrastructure to generate tokens
Stars: ✭ 19 (-60.42%)
Mutual labels:  oidc
oidc
Easy to use OpenID Connect client and server library written for Go and certified by the OpenID Foundation
Stars: ✭ 475 (+889.58%)
Mutual labels:  oidc
kubernetes-localdev
Create a local Kubernetes development environment on macOS or Windows and WSL2, including HTTPS/TLS and OAuth2/OIDC authentication.
Stars: ✭ 210 (+337.5%)
Mutual labels:  oidc
osprey
Kubernetes OIDC CLI login
Stars: ✭ 49 (+2.08%)
Mutual labels:  oidc
keycloak-springsecurity5-sample
Spring Security 5 OAuth2 Client/OIDC integration with Keycloak sample
Stars: ✭ 55 (+14.58%)
Mutual labels:  oidc

NG OIDC Client

npm npm Maintenance

An Angular package wrapping oidc-client-js to manage authentication with OIDC and OAuth2 in a reactive way using NgRx.

OIDC State in Redux DevTools

Getting started 🚀

The configuration for the examples are based on running IdentityServer4 on localhost. A ready-to-go reference implementation for testing purposes can be found at ng-oidc-client-server.

Install the package

npm install -s ng-oidc-client

if not already the case, install the necessary peer dependencies

npm install -s @ngrx/store 
npm install -s @ngrx/effects 
npm install -s oidc-client

Add the NgOidcClientModule to your AppModule

export interface State {
  router: RouterReducerState;
}
export const rootStore: ActionReducerMap<State> = {
  router: routerReducer
};

@NgModule({
  declarations: [AppComponent, ProtectedComponent, HomeComponent, LoginComponent],
  imports: [
    BrowserModule,
    StoreModule.forRoot(rootStore),
    EffectsModule.forRoot([]),
+    NgOidcClientModule.forRoot({
+     oidc_config: {
+       authority: 'https://localhost:5001',
+       client_id: 'ng-oidc-client-identity',
+       redirect_uri: 'http://localhost:4200/callback.html',
+       response_type: 'id_token token',
+       scope: 'openid profile offline_access api1',
+       post_logout_redirect_uri: 'http://localhost:4200/signout-callback.html',
+       silent_redirect_uri: 'http://localhost:4200/renew-callback.html',
+       accessTokenExpiringNotificationTime: 10,
+       automaticSilentRenew: true,
+       userStore: new WebStorageStateStore({ store: window.localStorage })
+     },
+     log: {
+       logger: console,
+       level: Log.NONE
+     }
+   })
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule {}

For a complete list of configuration options please see the official oidc-client-js documentation.

Coming soon: Example configuration Using ng-oidc-client with Auth0 and Okta

Inject the OidcFacade in your Component

...
export class HomeComponent {
  constructor(private oidcFacade: OidcFacade) {
    // Call to get user from storage
    this.oidcFacade.getOidcUser();
  }

  loginPopup() {
    this.oidcFacade.signinPopup();
  }

  logoutPopup() {
    this.oidcFacade.signoutPopup();
  }
}

Alternatively you can you also use .signinRedirect(); or .signoutRedirect();.

Create a new directory called static below the src folder, to serve the static callback HTML sites.

src/static
├── callback.html
├── renew-callback.html
└── signout-callback.html

Example for a callback.html

<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8" />
  <title>Callback</title>
  <link rel="icon"
        type="image/x-icon"
        href="favicon.png">
  <script src="oidc-client.min.js"
          type="application/javascript"></script>
</head>

<body>
  <script>
    var Oidc = window.Oidc;

    var config = {
      userStore: new Oidc.WebStorageStateStore({ store: window.localStorage })
    }

    if ((Oidc && Oidc.Log && Oidc.Log.logger)) {
      Oidc.Log.logger = console;
    }
    var isPopupCallback = JSON.parse(window.localStorage.getItem('ngoidc:isPopupCallback'));

    if (isPopupCallback) {
      new Oidc.UserManager(config).signinPopupCallback();
    } else {
      new Oidc.UserManager(config).signinRedirectCallback().then(t => {
        window.location.href = '/';
      });
    }
  </script>
</body>

</html>

Example for a renew-callback.html

<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8" />
    <title>Renew Callback</title>
    <link rel="icon"
          type="image/x-icon"
          href="favicon.png">
</head>

<body>
    <script src="oidc-client.min.js"></script>
    <script>
        var config = {
            userStore: new Oidc.WebStorageStateStore({ store: window.localStorage })
        }
        new Oidc.UserManager(config).signinSilentCallback().catch(function (e) {
            console.error(e);
        });
    </script>
</body>

</html>

Example for a signout-callback.html

<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8" />
  <title>Signout Callback</title>
  <link rel="icon"
        type="image/x-icon"
        href="favicon.png">
  <script src="oidc-client.min.js"
          type="application/javascript"></script>
</head>

<body>
  <script>
    var Oidc = window.Oidc;

    var config = {
      userStore: new Oidc.WebStorageStateStore({ store: window.localStorage })
    }

    if ((Oidc && Oidc.Log && Oidc.Log.logger)) {
      Oidc.Log.logger = console;
    }

    var isPopupCallback = JSON.parse(window.localStorage.getItem('ngoidc:isPopupCallback'));

    if (isPopupCallback) {
      new Oidc.UserManager(config).signoutPopupCallback();
    } else {
      new Oidc.UserManager(config).signoutRedirectCallback().then(test => {
        window.location.href = '/';
      });
    }
  </script>
</body>

</html>

Modify your angular.json to include the static assets and oidc-client

...
"assets": [
    "src/favicon.ico",
    "src/assets",
+   {
+     "glob": "**/*",
+     "input": "src/static",
+     "output": "/"
+   },
+   {
+     "glob": "oidc-client.min.js",
+     "input": "node_modules/oidc-client/dist",
+     "output": "/"
+   }
  ],
...

You will be able to authenticate against your configurated identity provider and the obtained user will be accessible in through the created state.

Protecting Routes using an AuthGuard 💂

Create a new Service and implement the AuthGuard interface

export class OidcGuardService implements CanActivate {
  constructor(private router: Router, private oidcFacade: OidcFacade) {}

  public canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | boolean {
    return this.oidcFacade.identity$.pipe(
      take(1),
      switchMap(user => {
        console.log('Auth Guard - Checking if user exists', user);
        console.log('Auth Guard - Checking if user is expired:', user && user.expired);
        if (user && !user.expired) {
          return of(true);
        } else {
          this.router.navigate(['/login']);
          return of(false);
        }
      })
    );
  }
}

The guard needs to inject the OidcFacade to check if the user exists and is not expired. It is up to the application flow if the unauthenticated user is redirected to a login route or not.

Add the Guard to the list of providers in your AppModule

...
providers: [
+   OidcGuardService,
  ],
...

Using HTTP Interceptor to add the Bearer token to API calls 🐻

In case an API requires a valid access token to interact with it, an HTTP Interceptor can be used to add the required Bearer token to each call.

Create a new Service and implement the HttpInterceptor interface

export class OidcInterceptorService implements HttpInterceptor {
  static OidcInterceptorService: any;
  constructor(private oidcFacade: OidcFacade) {}

  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    return this.oidcFacade.identity$.pipe(
      take(1),
      switchMap(user => {
        if (user && !user.expired && user.access_token) {
          req = req.clone({
            setHeaders: {
              Authorization: `Bearer ${user.access_token}`
            }
          });
        }
        return next.handle(req);
      })
    );
  }
}

The interceptor needs to inject the OidcFacade to check if the user exists, is not expired and has an access token. The outgoing request will be cloned and an Authorization Header will be added to the request. Additionally, the requests should be filtered to only add the Bearer token where it is needed.

Add the Interceptor to the list of providers in your AppModule

...
providers: [
+   {
+     provide: HTTP_INTERCEPTORS,
+     useClass: OidcInterceptorService,
+     multi: true
+   }
  ],
...

Docs

You'll find a more detailed Documentation in our Wiki

Articles

Examples

Coming soon

Licence

This software is licensed under the MIT

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].