Gathering detailed insights and metrics for integrator-angular-auth-oidc-client
Gathering detailed insights and metrics for integrator-angular-auth-oidc-client
Gathering detailed insights and metrics for integrator-angular-auth-oidc-client
Gathering detailed insights and metrics for integrator-angular-auth-oidc-client
npm package for OpenID Connect Implicit Flow
npm install integrator-angular-auth-oidc-client
Typescript
Module System
Node Version
NPM Version
TypeScript (94.72%)
JavaScript (5.28%)
Total Downloads
0
Last Day
0
Last Week
0
Last Month
0
Last Year
0
MIT License
728 Commits
1 Watchers
5 Branches
1 Contributors
Updated on Feb 21, 2019
Latest Version
2.0.1
Package Id
integrator-angular-auth-oidc-client@2.0.1
Unpacked Size
1.89 MB
Size
304.87 kB
File Count
142
NPM Version
6.7.0
Node Version
10.15.1
Cumulative downloads
Total Downloads
Last Day
0%
NaN
Compared to previous day
Last Week
0%
NaN
Compared to previous week
Last Month
0%
NaN
Compared to previous month
Last Year
0%
NaN
Compared to previous year
2
4
47
OpenID Code Flow with PKCE, OpenID Connect Implicit Flow
This library is certified by OpenID Foundation. (RP Implicit and Config RP)
Documentation : Quickstart | API Documentation | Changelog
Navigate to the level of your package.json and type
1 npm install angular-auth-oidc-client --save
or with yarn
1 yarn add angular-auth-oidc-client
or you can add the npm package to your package.json
1 "angular-auth-oidc-client": "9.0.2"
and type
1 npm install
Import the module and services in your module.
The OidcSecurityService has a dependency on the HttpClientModule which needs to be imported. The angular-auth-oidc-client module supports all versions of Angular 4.3 onwards.
1import { NgModule, APP_INITIALIZER } from '@angular/core'; 2import { HttpClientModule } from '@angular/common/http'; 3 4import { 5 AuthModule, 6 OidcSecurityService, 7 OpenIDImplicitFlowConfiguration, 8 OidcConfigService, 9 AuthWellKnownEndpoints 10} from 'angular-auth-oidc-client'; 11 12export function loadConfig(oidcConfigService: OidcConfigService) { 13 console.log('APP_INITIALIZER STARTING'); 14 return () => oidcConfigService.load(`${window.location.origin}/api/ClientAppSettings`); 15} 16 17@NgModule({ 18 imports: [ 19 ... 20 HttpClientModule, 21 AuthModule.forRoot() 22 ], 23 declarations: [ 24 ... 25 ], 26 providers: [ 27 OidcConfigService, 28 { 29 provide: APP_INITIALIZER, 30 useFactory: loadConfig, 31 deps: [OidcConfigService], 32 multi: true, 33 }, 34 ... 35 ], 36 bootstrap: [AppComponent], 37})
Set the AuthConfiguration properties to match the server configuration. At present only the 'code' with PKCE, 'id_token token' or the 'id_token' flows are supported.
1export class AppModule { 2 constructor( 3 private oidcSecurityService: OidcSecurityService, 4 private oidcConfigService: OidcConfigService 5 ) { 6 this.oidcConfigService.onConfigurationLoaded.subscribe(() => { 7 const openIDImplicitFlowConfiguration = new OpenIDImplicitFlowConfiguration(); 8 openIDImplicitFlowConfiguration.stsServer = this.oidcConfigService.clientConfiguration.stsServer; 9 openIDImplicitFlowConfiguration.redirect_url = this.oidcConfigService.clientConfiguration.redirect_url; 10 // The Client MUST validate that the aud (audience) Claim contains its client_id value registered at the Issuer 11 // identified by the iss (issuer) Claim as an audience. 12 // The ID Token MUST be rejected if the ID Token does not list the Client as a valid audience, 13 // or if it contains additional audiences not trusted by the Client. 14 openIDImplicitFlowConfiguration.client_id = this.oidcConfigService.clientConfiguration.client_id; 15 openIDImplicitFlowConfiguration.response_type = this.oidcConfigService.clientConfiguration.response_type; 16 openIDImplicitFlowConfiguration.scope = this.oidcConfigService.clientConfiguration.scope; 17 openIDImplicitFlowConfiguration.post_logout_redirect_uri = this.oidcConfigService.clientConfiguration.post_logout_redirect_uri; 18 openIDImplicitFlowConfiguration.start_checksession = this.oidcConfigService.clientConfiguration.start_checksession; 19 openIDImplicitFlowConfiguration.silent_renew = this.oidcConfigService.clientConfiguration.silent_renew; 20 openIDImplicitFlowConfiguration.silent_renew_url = this.oidcConfigService.clientConfiguration.silent_renew_url; 21 openIDImplicitFlowConfiguration.post_login_route = this.oidcConfigService.clientConfiguration.post_login_route; 22 // HTTP 403 23 openIDImplicitFlowConfiguration.forbidden_route = this.oidcConfigService.clientConfiguration.forbidden_route; 24 // HTTP 401 25 openIDImplicitFlowConfiguration.unauthorized_route = this.oidcConfigService.clientConfiguration.unauthorized_route; 26 openIDImplicitFlowConfiguration.log_console_warning_active = this.oidcConfigService.clientConfiguration.log_console_warning_active; 27 openIDImplicitFlowConfiguration.log_console_debug_active = this.oidcConfigService.clientConfiguration.log_console_debug_active; 28 // id_token C8: The iat Claim can be used to reject tokens that were issued too far away from the current time, 29 // limiting the amount of time that nonces need to be stored to prevent attacks.The acceptable range is Client specific. 30 openIDImplicitFlowConfiguration.max_id_token_iat_offset_allowed_in_seconds = this.oidcConfigService.clientConfiguration.max_id_token_iat_offset_allowed_in_seconds; 31 32 const authWellKnownEndpoints = new AuthWellKnownEndpoints(); 33 authWellKnownEndpoints.setWellKnownEndpoints(this.oidcConfigService.wellKnownEndpoints); 34 35 this.oidcSecurityService.setupModule( 36 openIDImplicitFlowConfiguration, 37 authWellKnownEndpoints 38 ); 39 }); 40 41 console.log('APP STARTING'); 42 } 43}
Create the login, logout component and use the oidcSecurityService
1import { Component, OnInit, OnDestroy } from '@angular/core'; 2import { Subscription } from 'rxjs/Subscription'; 3import { OidcSecurityService } from 'angular-auth-oidc-client'; 4 5@Component({ 6 selector: 'my-app', 7 templateUrl: 'app.component.html', 8}) 9export class AppComponent implements OnInit, OnDestroy { 10 constructor(public oidcSecurityService: OidcSecurityService) { 11 this.oidcSecurityService.getIsModuleSetup().pipe( 12 filter((isModuleSetup: boolean) => isModuleSetup), 13 take(1) 14 ).subscribe((isModuleSetup: boolean) => { 15 this.doCallbackLogicIfRequired(); 16 }); 17 } 18 19 ngOnInit() {} 20 21 ngOnDestroy(): void {} 22 23 login() { 24 25 // if you need to add extra parameters to the login 26 // let culture = 'de-CH'; 27 // this.oidcSecurityService.setCustomRequestParameters({ 'ui_locales': culture }); 28 29 this.oidcSecurityService.authorize(); 30 } 31 32 logout() { 33 this.oidcSecurityService.logoff(); 34 } 35 36 private doCallbackLogicIfRequired() { 37 console.log(window.location); 38 // Will do a callback, if the url has a code and state parameter. 39 this.oidcSecurityService.authorizedCallbackWithCode(window.location.toString()); 40 } 41} 42
Create the login, logout component and use the oidcSecurityService
1import { Component, OnInit, OnDestroy } from '@angular/core'; 2import { Subscription } from 'rxjs/Subscription'; 3import { OidcSecurityService } from 'angular-auth-oidc-client'; 4 5@Component({ 6 selector: 'my-app', 7 templateUrl: 'app.component.html', 8}) 9export class AppComponent implements OnInit, OnDestroy { 10 constructor(public oidcSecurityService: OidcSecurityService) { 11 this.oidcSecurityService.getIsModuleSetup().pipe( 12 filter((isModuleSetup: boolean) => isModuleSetup), 13 take(1) 14 ).subscribe((isModuleSetup: boolean) => { 15 this.doCallbackLogicIfRequired(); 16 }); 17 } 18 19 ngOnInit() {} 20 21 ngOnDestroy(): void {} 22 23 login() { 24 25 // if you need to add extra parameters to the login 26 // let culture = 'de-CH'; 27 // this.oidcSecurityService.setCustomRequestParameters({ 'ui_locales': culture }); 28 29 this.oidcSecurityService.authorize(); 30 } 31 32 logout() { 33 this.oidcSecurityService.logoff(); 34 } 35 36 private doCallbackLogicIfRequired() { 37 if (window.location.hash) { 38 this.oidcSecurityService.authorizedImplicitFlowCallback(); 39 } 40 } 41}
In the http services, add the token to the header using the oidcSecurityService
1private setHeaders() { 2 this.headers = new HttpHeaders(); 3 this.headers = this.headers.set('Content-Type', 'application/json'); 4 this.headers = this.headers.set('Accept', 'application/json'); 5 6 const token = this._securityService.getToken(); 7 if (token !== '') { 8 const tokenValue = 'Bearer ' + token; 9 this.headers = this.headers.set('Authorization', tokenValue); 10 } 11}
Note the configuration json must return a property stsServer for this to work.
1export function loadConfig(oidcConfigService: OidcConfigService) { 2 console.log('APP_INITIALIZER STARTING'); 3 return () => oidcConfigService.load(`${window.location.origin}/api/ClientAppSettings`); 4}
Example:
You can add any configurations to this json, as long as the stsServer is present. This is REQUIRED. Then you can map the properties in the AppModule.
1{ 2 "stsServer":"https://localhost:44318", 3 "redirect_url":"https://localhost:44311", 4 "client_id":"angularclient", 5 "response_type":"code", // "id_token token" 6 "scope":"dataEventRecords securedFiles openid profile", 7 "post_logout_redirect_uri":"https://localhost:44311", 8 "start_checksession":true, 9 "silent_renew":true, 10 "silent_renew_url":"https://localhost:44311/silent-renew.html" 11 "post_login_route":"/home", 12 "forbidden_route":"/forbidden", 13 "unauthorized_route":"/unauthorized", 14 "log_console_warning_active":true, 15 "log_console_debug_active":true, 16 "max_id_token_iat_offset_allowed_in_seconds":"10", 17 "apiServer":"https://localhost:44390/", 18 "apiFileServer":"https://localhost:44378/" 19}
See Auth documentation for the detail of each field.
1export class AppModule { 2 constructor(public oidcSecurityService: OidcSecurityService) { 3 const openIDImplicitFlowConfiguration = new OpenIDImplicitFlowConfiguration(); 4 5 openIDImplicitFlowConfiguration.stsServer = 'https://localhost:44363'; 6 openIDImplicitFlowConfiguration.redirect_url = 'https://localhost:44363'; 7 // The Client MUST validate that the aud (audience) Claim contains its client_id value registered at the Issuer identified by the iss (issuer) Claim as an audience. 8 // The ID Token MUST be rejected if the ID Token does not list the Client as a valid audience, or if it contains additional audiences not trusted by the Client. 9 openIDImplicitFlowConfiguration.client_id = 'singleapp'; 10 openIDImplicitFlowConfiguration.response_type = 'code'; // 'id_token token' Implicit Flow 11 openIDImplicitFlowConfiguration.scope = 'dataEventRecords openid'; 12 openIDImplicitFlowConfiguration.post_logout_redirect_uri = 13 'https://localhost:44363/Unauthorized'; 14 openIDImplicitFlowConfiguration.start_checksession = false; 15 openIDImplicitFlowConfiguration.silent_renew = true; 16 openIDImplicitFlowConfiguration.silent_renew_url = 17 'https://localhost:44363/silent-renew.html'; 18 openIDImplicitFlowConfiguration.post_login_route = '/dataeventrecords'; 19 // HTTP 403 20 openIDImplicitFlowConfiguration.forbidden_route = '/Forbidden'; 21 // HTTP 401 22 openIDImplicitFlowConfiguration.unauthorized_route = '/Unauthorized'; 23 openIDImplicitFlowConfiguration.log_console_warning_active = true; 24 openIDImplicitFlowConfiguration.log_console_debug_active = true; 25 // id_token C8: The iat Claim can be used to reject tokens that were issued too far away from the current time, 26 // limiting the amount of time that nonces need to be stored to prevent attacks.The acceptable range is Client specific. 27 openIDImplicitFlowConfiguration.max_id_token_iat_offset_allowed_in_seconds = 10; 28 29 const authWellKnownEndpoints = new AuthWellKnownEndpoints(); 30 authWellKnownEndpoints.issuer = 'https://localhost:44363'; 31 32 authWellKnownEndpoints.jwks_uri = 33 'https://localhost:44363/.well-known/openid-configuration/jwks'; 34 authWellKnownEndpoints.authorization_endpoint = 'https://localhost:44363/connect/authorize'; 35 authWellKnownEndpoints.token_endpoint = 'https://localhost:44363/connect/token'; 36 authWellKnownEndpoints.userinfo_endpoint = 'https://localhost:44363/connect/userinfo'; 37 authWellKnownEndpoints.end_session_endpoint = 'https://localhost:44363/connect/endsession'; 38 authWellKnownEndpoints.check_session_iframe = 39 'https://localhost:44363/connect/checksession'; 40 authWellKnownEndpoints.revocation_endpoint = 'https://localhost:44363/connect/revocation'; 41 authWellKnownEndpoints.introspection_endpoint = 42 'https://localhost:44363/connect/introspect'; 43 44 this.oidcSecurityService.setupModule( 45 openIDImplicitFlowConfiguration, 46 authWellKnownEndpoints 47 ); 48 } 49}
Sometimes it is required to load custom .well-known/openid-configuration. The load_using_custom_stsServer can be used for this.
1export function loadConfig(oidcConfigService: OidcConfigService) { 2 console.log('APP_INITIALIZER STARTING'); 3 return () => 4 oidcConfigService.load_using_custom_stsServer( 5 'https://login.microsoftonline.com/fabrikamb2c.onmicrosoft.com/v2.0/.well-known/openid-configuration?p=b2c_1_susi' 6 ); 7}
1import { Injectable } from '@angular/core'; 2import { Router, CanActivate, CanLoad, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router'; 3import { Observable } from 'rxjs'; 4import { tap } from 'rxjs/operators'; 5 6import { OidcSecurityService } from './auth/services/oidc.security.service'; 7 8@Injectable() 9export class AuthorizationGuard implements CanActivate, CanLoad { 10 constructor(private router: Router, private oidcSecurityService: OidcSecurityService) {} 11 12 canActivate( 13 route: ActivatedRouteSnapshot, 14 state: RouterStateSnapshot 15 ): Observable<boolean> { 16 return this.checkUser(); 17 } 18 19 canLoad(state: Route): Observable<boolean> { 20 return this.checkUser(); 21 } 22 23 private checkUser(): Observable<boolean> | boolean { 24 console.log(route + '' + state); 25 console.log('AuthorizationGuard, canActivate'); 26 27 return this.oidcSecurityService.getIsAuthorized().pipe( 28 tap((isAuthorized: boolean) => { 29 console.log('AuthorizationGuard, canActivate isAuthorized: ' + isAuthorized); 30 31 if(!isAuthorized) { 32 this.router.navigate(['/unauthorized']); 33 } 34 }) 35 ); 36 } 37}
If you need, you can create a custom storage (for example to use cookies).
Implement OidcSecurityStorage
class-interface and the read
and write
methods:
1@Injectable() 2export class CustomStorage implements OidcSecurityStorage { 3 4 public read(key: string): any { 5 ... 6 return ... 7 } 8 9 public write(key: string, value: any): void { 10 ... 11 } 12 13}
Then provide the class in the module:
1@NgModule({ 2 imports: [ 3 ... 4 AuthModule.forRoot({ storage: CustomStorage }) 5 ], 6 ... 7})
See also oidc.security.storage.ts
for an example.
The HttpClient allows you to write interceptors. A common usecase would be to intercept any outgoing HTTP request and add an authorization header. Keep in mind that injecting OidcSecurityService into the interceptor via the constructor results in a cyclic dependency. To avoid this use the injector instead.
1@Injectable() 2export class AuthInterceptor implements HttpInterceptor { 3 private oidcSecurityService: OidcSecurityService; 4 5 constructor(private injector: Injector) {} 6 7 intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> { 8 let requestToForward = req; 9 10 if (this.oidcSecurityService === undefined) { 11 this.oidcSecurityService = this.injector.get(OidcSecurityService); 12 } 13 if (this.oidcSecurityService !== undefined) { 14 let token = this.oidcSecurityService.getToken(); 15 if (token !== '') { 16 let tokenValue = 'Bearer ' + token; 17 requestToForward = req.clone({ setHeaders: { Authorization: tokenValue } }); 18 } 19 } else { 20 console.debug('OidcSecurityService undefined: NO auth header!'); 21 } 22 23 return next.handle(requestToForward); 24 } 25}
You can call the Provider's authorization endpoint in a popup or iframe instead of navigating to it in the app's parent window. This allows you to have the Provider's consent prompt display in a popup window to avoid unloading and reloading the app, or to authorize the user silently by loading the endpoint in a hidden iframe if that supported by the Provider.
To get the fully-formed authorization URL, pass a handler function to OidcSecurityService.authorize
(this will also prevent the default behavior of loading the authorization endpoint in the current window):
1login() { 2 this.oidcSecurityService.authorize((authUrl) => { 3 // handle the authorrization URL 4 window.open(authUrl, '_blank', 'toolbar=0,location=0,menubar=0'); 5 }); 6}
When silent renew is enabled, a DOM event will be automatically installed in the application's host window.
The event oidc-silent-renew-message
accepts a CustomEvent
instance with the token returned from the OAuth server
in its detail
field.
The event handler will send this token to the authorization callback and complete the validation.
Point the silent_renew_url
property to an HTML file which contains the following script element to enable authorization.
Code Flow with PKCE
<script>
window.onload = function () {
/* The parent window hosts the Angular application */
var parent = window.parent;
/* Send the id_token information to the oidc message handler */
var event = new CustomEvent('oidc-silent-renew-message', { detail: window.location });
parent.dispatchEvent(event);
};
</script>
Implicit Flow
<script>
window.onload = function () {
/* The parent window hosts the Angular application */
var parent = window.parent;
/* Send the id_token information to the oidc message handler */
var event = new CustomEvent('oidc-silent-renew-message', {detail: window.location.hash.substr(1) });
parent.dispatchEvent(event);
};
</script>
When silent renew is enabled, getIsAuthorized()
will attempt to perform a renew before returning the authorization state.
This allows the application to authorize a user, that is already authenticated, without redirects.
Silent renew requires CSP configuration, see next section.
If deploying the client application and the STS server application with 2 different domains, the X-Frame-Options HTTPS header needs to allow all iframes. Then use the CSP HTTPS header to only allow the required domains. The silent renew requires this.
Add this header to responses from the server that serves your SPA:
Content-Security-Policy: script-src 'self' 'unsafe-inline';style-src 'self' 'unsafe-inline';img-src 'self' data:;font-src 'self';frame-ancestors 'self' https://localhost:44318;block-all-mixed-content
where https://localhost:44318
is the address of your STS server.
e.g. if you use NginX to serve your Angular application, it would be
http {
server {
...
add_header Content-Security-Policy "script-src 'self' 'unsafe-inline';style-src 'self' 'unsafe-inline';img-src 'self' data:;font-src 'self';frame-ancestors 'self' https://localhost:44318;block-all-mixed-content";
https://github.com/damienbod/AspNetCoreAngularSignalRSecurity
https://github.com/damienbod/dotnet-template-angular
https://github.com/damienbod/angular-auth-oidc-sample-google-openid
https://github.com/HWouters/ad-b2c-oidc-angular
https://github.com/robisim74/angular-openid-connect-php/tree/angular-auth-oidc-client
https://github.com/damienbod/AspNet5IdentityServerAngularImplicitFlow
This npm package was created using the https://github.com/robisim74/angular-library-starter from Roberto Simonetti.
MIT
No vulnerabilities found.
Reason
no binaries found in the repo
Reason
license file detected
Details
Reason
0 commit(s) and 0 issue activity found in the last 90 days -- score normalized to 0
Reason
no SAST tool detected
Details
Reason
Found 0/30 approved changesets -- score normalized to 0
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
security policy file not detected
Details
Reason
project is not fuzzed
Details
Reason
branch protection not enabled on development/release branches
Details
Reason
124 existing vulnerabilities detected
Details
Score
Last Scanned on 2025-07-07
The Open Source Security Foundation is a cross-industry collaboration to improve the security of open source software (OSS). The Scorecard provides security health metrics for open source projects.
Learn More