• Stars
    star
    1,890
  • Rank 24,538 (Top 0.5 %)
  • Language
    TypeScript
  • License
    MIT License
  • Created almost 8 years ago
  • Updated 4 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Support for OAuth 2 and OpenId Connect (OIDC) in Angular.

angular-oauth2-oidc

Support for OAuth 2 and OpenId Connect (OIDC) in Angular. Already prepared for the upcoming OAuth 2.1.

OIDC Certified Logo

Credits

Resources

Tested Environment

Successfully tested with Angular 4.3 to Angular 15 and its Router, PathLocationStrategy as well as HashLocationStrategy and CommonJS-Bundling via webpack.

At server side we've used IdentityServer (.NET / .NET Core), Redhat's Keycloak (Java), and Auth0 (Auth0 is officially supported since version 10 of this lib). For Auth0, please have a look into the respective documentation page here.

For using this library with Azure Active Directory (Azure AD), we recommend an additional look to this blog post and the example linked at the end of this blog post.

Also, the Okta community created some guidelines on how to use this lib with Okta. See the links at the end of this page for more information.

Angular 15: Use 15.x versions of this library (should also work with older Angular versions!).

Angular 14: Use 14.x versions of this library (should also work with older Angular versions!).

Angular 13: Use 13.x versions of this library (should also work with older Angular versions!).

Angular 12: Use 12.x versions of this library (should also work with older Angular versions!).

Angular 11: Use 10.x versions of this library (should also work with older Angular versions!).

Angular 10: Use 10.x versions of this library (should also work with older Angular versions!).

Angular 9: Use 9.x versions of this library (should also work with older Angular versions!).

Angular 8: Use 8.x versions of this library.

Angular 7: Use 7.x versions of this library.

Angular 6: Use Version 4.x of this library. Version 4.x was tested with Angular 6. You can also try the newer version 5.x of this library which has a much smaller bundle size.

Angular 5.x or 4.3: If you need support for Angular < 6 (4.3 to 5.x) you can download the former version 3.1.4 (npm i angular-oauth2-oidc@^3 --save).

Release Cycle

  • We plan one major release for each Angular version
    • Will contain new features
    • Will contain bug fixes and PRs
  • Critical bugfixes on demand

Contributions

  • Feel free to file pull requests

  • The issues contain some ideas for PRs and enhancements (see labels)

  • If you want to contribute to the docs, you can do so in the docs-src folder. Make sure you update summary.json as well. Then generate the docs with the following commands:

    npm install -g @compodoc/compodoc
    npm run docs

Features

  • Logging in via Code Flow + PKCE
    • Hence, you are safe for the upcoming OAuth 2.1
  • Logging in via Implicit Flow (where a user is redirected to Identity Provider)
  • "Logging in" via Password Flow (where a user enters their password into the client)
  • Token Refresh for all supported flows
  • Automatically refreshing a token when/some time before it expires
  • Querying Userinfo Endpoint
  • Querying Discovery Document to ease configuration
  • Validating claims of the id_token regarding the specs
  • Hook for further custom validations
  • Single-Sign-Out by redirecting to the auth-server's logout-endpoint
  • Tested with all modern browsers and IE
  • Token Revocation according to RFC 7009

Sample-Auth-Server

You can use the OIDC-Sample-Server used in our examples. It assumes, that your Web-App runs on http://localhost:4200

Username/Password:

  • max/geheim
  • bob/bob
  • alice/alice

clientIds:

  • spa (Code Flow + PKCE)
  • implicit (implicit flow)

redirectUris:

  • localhost:[4200-4202]
  • localhost:[4200-4202]/index.html
  • localhost:[4200-4202]/silent-refresh.html

Installing

npm i angular-oauth2-oidc --save

Option 1: Standalone APIs

If you use Standalone Components introduced with Angular 14, you can use our standalone API (call to provideOAuthClient) in your main.ts to setup the OAuthClient:

// main.ts -- Angular 15+ version
import { bootstrapApplication } from '@angular/platform-browser';

import { provideHttpClient } from '@angular/common/http';

import { AppComponent } from './app/app.component';
import { provideOAuthClient } from 'angular-oauth2-oidc';

bootstrapApplication(AppComponent, {
  providers: [
    provideHttpClient(),
    provideOAuthClient()
  ]
});

As Angular 14 does have Standalone Components but no Standalone API for its HttpClient, you need to go with the traditional HttpClientModule in this version:

// main.ts -- Angular 14 version
import { bootstrapApplication } from '@angular/platform-browser';

import { HttpClientModule } from '@angular/common/http';

import { AppComponent } from './app/app.component';
import { provideOAuthClient } from 'angular-oauth2-oidc';
import { importProvidersFrom } from '@angular/core';

bootstrapApplication(AppComponent, {
  providers: [
    importProvidersFrom(HttpClientModule),
    provideOAuthClient()
  ]
});

The provideOAuthClient function takes the same parameters as the forRoot function of the OAuthModule that is still in place for the sake of compatibility with existing code bases.

Option 2: Using NgModules

import { HttpClientModule } from '@angular/common/http';
import { OAuthModule } from 'angular-oauth2-oidc';
// etc.

@NgModule({
  imports: [
    // etc.
    HttpClientModule,
    OAuthModule.forRoot()
  ],
  declarations: [
    AppComponent,
    HomeComponent,
    // etc.
  ],
  bootstrap: [
    AppComponent
  ]
})
export class AppModule {
}

Logging in

Since Version 8, this library supports code flow and PKCE to align with the current draft of the OAuth 2.0 Security Best Current Practice document. This is also the foundation of the upcoming OAuth 2.1.

To configure your solution for code flow + PKCE you have to set the responseType to code:

  import { AuthConfig } from 'angular-oauth2-oidc';

  export const authCodeFlowConfig: AuthConfig = {
    // Url of the Identity Provider
    issuer: 'https://idsvr4.azurewebsites.net',

    // URL of the SPA to redirect the user to after login
    redirectUri: window.location.origin + '/index.html',

    // The SPA's id. The SPA is registerd with this id at the auth-server
    // clientId: 'server.code',
    clientId: 'spa',

    // Just needed if your auth server demands a secret. In general, this
    // is a sign that the auth server is not configured with SPAs in mind
    // and it might not enforce further best practices vital for security
    // such applications.
    // dummyClientSecret: 'secret',

    responseType: 'code',

    // set the scope for the permissions the client should request
    // The first four are defined by OIDC.
    // Important: Request offline_access to get a refresh token
    // The api scope is a usecase specific one
    scope: 'openid profile email offline_access api',

    showDebugInformation: true,
  };

After this, you can initialize the code flow using:

this.oauthService.initCodeFlow();

There is also a convenience method initLoginFlow which initializes either the code flow or the implicit flow depending on your configuration.

this.oauthService.initLoginFlow();

Also -- as shown in the readme -- you have to execute the following code when bootstrapping to make the library to fetch the token:

this.oauthService.configure(authCodeFlowConfig);
this.oauthService.loadDiscoveryDocumentAndTryLogin();

Logging out

The logOut method clears the used token store (by default sessionStorage) and forwards the user to the auth servers logout endpoint if one was configured (manually or via the discovery document).

this.oauthService.logOut();

If you want to revoke the existing access token and the existing refresh token before logging out, use the following method:

this.oauthService.revokeTokenAndLogout();

Skipping the Login Form

If you don't want to display a login form that tells the user that they are redirected to the identity server, you can use the convenience function this.oauthService.loadDiscoveryDocumentAndLogin(); instead of this.oauthService.loadDiscoveryDocumentAndTryLogin(); when setting up the library.

This directly redirects the user to the identity server if there are no valid tokens. Ensure you have your issuer set to your discovery document endpoint!

Calling a Web API with an Access Token

You can automate this task by switching sendAccessToken on and by setting allowedUrls to an array with prefixes for the respective URLs. Use lower case for the prefixes.

OAuthModule.forRoot({
    resourceServer: {
        allowedUrls: ['http://www.angular.at/api'],
        sendAccessToken: true
    }
})

If you need more versatility, you can look in the documentation how to setup a custom interceptor.

Token Refresh

See docs: https://manfredsteyer.github.io/angular-oauth2-oidc/docs/additional-documentation/refreshing-a-token.html

Routing

If you use the PathLocationStrategy (which is on by default) and have a general catch-all-route (path: '**') you should be fine. Otherwise look up the section Routing with the HashStrategy in the documentation.

Implicit Flow

Nowadays, using code flow + PKCE -- as shown above -- is the recommended OAuth 2/OIDC flow for SPAs. To use the older implicit flow, lookup this docs: https://manfredsteyer.github.io/angular-oauth2-oidc/docs/additional-documentation/using-implicit-flow.html

More Documentation (!)

See the documentation for more information about this library.

Breaking Change in Version 9

With regards to tree shaking, beginning with version 9, the JwksValidationHandler has been moved to a library of its own. If you need it for implementing implicit flow, please install it using npm:

npm i angular-oauth2-oidc-jwks --save

After that, you can import it into your application by using this:

import { JwksValidationHandler } from 'angular-oauth2-oidc-jwks';

instead of that:

import { JwksValidationHandler } from 'angular-oauth2-oidc';

Please note, that this dependency is not needed for the code flow, which is nowadays the recommended flow for single page applications. This also results in smaller bundle sizes.

Breaking change in 9.1.0

The use of encodeURIComponent on the argument passed to initImplicitFlow and its Code Flow counterparts was mandatory before this version.

Since that was considered a bug, the need to do so was removed. Now the reverse is true if you're upgrading from before 9.0.0: you need to remove any call to encode URI components in your own application, as the library will now do it for you.

Tutorials

Thanks to all Contributors

alexandisanbiniyaranoordendeArsProgrammanihanth007

bobvandevijverBobCui20BottswanaErazerBrechtChris3773

ChristianMurphyd-moosenterprisebugcraniodevFabianGosebrink

FabienDehopreFRosnerMisterJamesJessePreinerjesusbotella

JojofoulkkristofdegravesaxiceklukasmattaMaximaximum

mpbalmeidamhyfritzmdaehnertmcserranhumblot

l1b3roleersoyOskarsPakershellerbardepaweldyminski

bechhansenpeterneavepmccloghrylaingakehirRubenVermeulen

ryanmwrightscttcperabshoffSpazzMarticussrenatus

sven-codecultureRocket18CetearethvadjsVarada-Schneider

Gimlyakkaradejcoyoteecddarbiofilipvh

kyubisationluciimonmike-riveradrobert-bfmroblabat

wdunn001adrianbenjuyaAndreas-Hjortlandademattecgatian

dirkbolteenricodeleoGregordyjeroenhinfilinjie997

jfynekevincathcart-casmartin1cernymarvinosswaldnick1699

paulyoderreda-alaouiremiburtingingterskranich

StefanoChiodinotpeter1985dennisamelingdependabot[bot]jdgeier

mraibleajpiersonartnimfmalcherFlofie

mabdelaal86nhanceRazzeeemaxisamismcagdas

ToxicableManuelRaubervdveerjeroenheijmansmanfredsteyer

More Repositories

1

ngx-build-plus

Extend the Angular CLI's default build behavior without ejecting, e. g. for Angular Elements
TypeScript
1,163
star
2

angular-crud

TypeScript
283
star
3

module-federation-plugin-example

TypeScript
195
star
4

yarp-auth-proxy

C#
193
star
5

angular-elements-dashboard

Dynamic Dashboard with Angular Elements and Web Components
CSS
189
star
6

angular-microapp

CSS
145
star
7

standalone-example-cli

TypeScript
105
star
8

module-federation-with-angular-dynamic

Dynamic Module Federation with Angular
TypeScript
101
star
9

angular-microfrontend

JavaScript
87
star
10

module-federation-with-angular

Demonstrates webpack 5 Module Federation with Angular and the Angular Router.
TypeScript
72
star
11

angular-ddd

JavaScript
71
star
12

multi-framework-micro-frontend

TypeScript
64
star
13

angular2-oauth2

JavaScript
63
star
14

Angular_MicroApps_Different_Technologies

CSS
56
star
15

module-federation-with-angular-dynamic-workflow-designer

Example for building a plugin-based workflow designer with Angular and Dynamic Module Federation
TypeScript
54
star
16

meta-router

A lightweight and solid approach towards micro frontends (SPAs/ clients for micro services)
JavaScript
44
star
17

strategic-design

Example for using Strategic Design with Angular and Nx
TypeScript
38
star
18

native-federation-core-microfrontend

TypeScript
38
star
19

ddd-bk

36
star
20

federation-demo

TypeScript
28
star
21

monorepo_domains

TypeScript
27
star
22

angular-2-reuse-strategy-sample

TypeScript
26
star
23

multi-framework-version

TypeScript
26
star
24

native-federation-react-example

TypeScript
26
star
25

angular-oauth-oidc

Sample showing how to use Angular with OAuth2 & OIDC
JavaScript
23
star
26

sa-cli

TypeScript
23
star
27

native-federation-vite-angular-demo

TypeScript
23
star
28

astro-last-minute

Astro
22
star
29

ngUpgrade-without-preparation

TypeScript
22
star
30

schematics-book

HTML
20
star
31

modern-arc

TypeScript
19
star
32

microservice-angular-iframe

Creating Angular-Frontends for Microservices
TypeScript
17
star
33

web-components

Examples for using Web Components in Angular
JavaScript
17
star
34

schematics-sample

My Schematics Sample, Updated Version
TypeScript
15
star
35

nx-and-module-federation

TypeScript
15
star
36

standalone-book

15
star
37

angular-without-modules

TypeScript
14
star
38

angular-ssr

TypeScript
14
star
39

module-federation-light

TypeScript
13
star
40

lazy-loading-ng-conf

TypeScript
12
star
41

snake

TypeScript
12
star
42

angular2-aot-webpack2-rollup

TypeScript
12
star
43

demo-nx-standalone

TypeScript
12
star
44

angular8

TypeScript
12
star
45

simple-microfrontend-demo

CSS
12
star
46

monorepo-demo

CSS
11
star
47

module_federation_shared_versions

TypeScript
11
star
48

progresive-web-apps-with-angular-2-demo

Showcase for PWA with Angular 2
TypeScript
11
star
49

angular-book

Beispiele von unserem Angular Buch
TypeScript
11
star
50

standalone-example-nx

TypeScript
10
star
51

angular2-pwa-serviceworker-basta2016

JavaScript
10
star
52

desserts

TypeScript
10
star
53

sa-nx

TypeScript
10
star
54

ngconf-angular-elements-workshop

CSS
9
star
55

build-elements

CSS
9
star
56

ivy-potential

JavaScript
9
star
57

DDD_Nx

JavaScript
9
star
58

ngconf-angular-elements-workshop-external

JavaScript
9
star
59

module_federation_nx_mono_repo

TypeScript
9
star
60

signals-component-communication

TypeScript
9
star
61

nx-module-federation-demo

TypeScript
8
star
62

angular2-newest-new-router-guards-oauth

TypeScript
8
star
63

angular-oidc-lib

Simple Lib for using OAuth2 and OIDC in Angular
JavaScript
8
star
64

adv-mf-examples

TypeScript
8
star
65

nx-ddd-demo

TypeScript
8
star
66

angular2-rc1-sample

TypeScript
7
star
67

angular-intro

TypeScript
7
star
68

microapps-hyperlinks

CSS
7
star
69

http-client-demo

CSS
7
star
70

flight-app

TypeScript
7
star
71

nx-angular-demo

TypeScript
7
star
72

angular2-oauth-oidc-demo

TypeScript
7
star
73

ngUpgrade-aot-sample

TypeScript
6
star
74

angular3-app

TypeScript
6
star
75

schematics-ng-add

TypeScript
6
star
76

hero-shop

TypeScript
6
star
77

workshop-fest-2020-05

JavaScript
6
star
78

schematics-intro

CSS
6
star
79

standalone-components-elements

TypeScript
6
star
80

5-best-practices-angular

JavaScript
6
star
81

angularjs_ce

CSS
6
star
82

ng-upgrade-workshop-starterkit

Starterkit for Angular migration workshop
TypeScript
6
star
83

module-federation-plugin-example-nx

TypeScript
6
star
84

flights-ddd-demo

TypeScript
6
star
85

dynamic-dashboard-with-dynamic-components-sample

TypeScript
5
star
86

basta_2019_angular_best_practices

JavaScript
5
star
87

microfrontend-prototype

JavaScript
5
star
88

ngUpgrade-lite-sample

TypeScript
5
star
89

pwa-show-case

TypeScript
5
star
90

import-maps-101

HTML
5
star
91

native-federation-core-example

TypeScript
5
star
92

ddd

TypeScript
5
star
93

advanced-routing-angular-days-munich-mar-2017

TypeScript
4
star
94

ngconf-performance

CSS
4
star
95

schematics-ngVikings-2018

CSS
4
star
96

articles

HTML
4
star
97

monorepo_mf

TypeScript
4
star
98

nx_monorepo

JavaScript
4
star
99

angular-elements-ngconf-2019

CSS
4
star
100

angular-architecture-ngHamburg-march-2018

CSS
4
star