Research
Security News
Quasar RAT Disguised as an npm Package for Detecting Vulnerabilities in Ethereum Smart Contracts
Socket researchers uncover a malicious npm package posing as a tool for detecting vulnerabilities in Etherium smart contracts.
angular-oauth2-oidc
Advanced tools
The angular-oauth2-oidc package is an Angular library that provides support for OAuth 2 and OpenID Connect (OIDC) authentication. It allows developers to easily integrate secure authentication and authorization into their Angular applications.
OAuth2 and OIDC Authentication
This feature allows you to configure and initiate OAuth2 and OIDC authentication in your Angular application. The code sample demonstrates how to set up the OAuthService with the necessary configuration and initiate the login process.
import { OAuthService, AuthConfig } from 'angular-oauth2-oidc';
const authConfig: AuthConfig = {
issuer: 'https://your-identity-server',
redirectUri: window.location.origin + '/index.html',
clientId: 'your-client-id',
scope: 'openid profile email',
responseType: 'code'
};
oauthService.configure(authConfig);
oauthService.loadDiscoveryDocumentAndTryLogin();
Token Management
This feature provides methods to manage tokens, including retrieving access and ID tokens, and refreshing tokens. The code sample shows how to get the access token, ID token, and refresh the token using the OAuthService.
import { OAuthService } from 'angular-oauth2-oidc';
// Get access token
const accessToken = oauthService.getAccessToken();
// Get ID token
const idToken = oauthService.getIdToken();
// Refresh token
oauthService.refreshToken();
User Profile Information
This feature allows you to retrieve user profile information from the ID token. The code sample demonstrates how to get the identity claims and log them to the console.
import { OAuthService } from 'angular-oauth2-oidc';
// Get user profile information
const claims = oauthService.getIdentityClaims();
if (claims) {
console.log(claims);
}
The oidc-client package is a JavaScript library for managing OpenID Connect (OIDC) and OAuth2 authentication. It is framework-agnostic and can be used with any JavaScript framework, including Angular. Compared to angular-oauth2-oidc, oidc-client provides more flexibility but requires more manual setup and integration.
The angular-auth-oidc-client package is another Angular library for implementing OAuth2 and OIDC authentication. It offers similar functionalities to angular-oauth2-oidc, such as token management and user profile retrieval. However, it has a different API and configuration approach, which some developers might find more intuitive or easier to use.
The auth0-angular package is an Angular SDK for integrating Auth0 authentication and authorization services. It provides a seamless way to implement OAuth2 and OIDC authentication with Auth0 as the identity provider. Compared to angular-oauth2-oidc, auth0-angular is specifically designed for use with Auth0 and offers additional features like user management and analytics.
Support for OAuth 2 and OpenId Connect (OIDC) in Angular.
Sources and Sample: https://github.com/manfredsteyer/angular-oauth2-oidc
Source Code Documentation https://manfredsteyer.github.io/angular-oauth2-oidc/angular-oauth2-oidc/docs/
Successfully tested with the Angular 2 and 4 and its Router, PathLocationStrategy as well as HashLocationStrategy and CommonJS-Bundling via webpack. At server side we've used IdentityServer (.NET/ .NET Core) and Redhat's Keycloak (Java).
events
.token_expires
can be used togehter with a silent refresh to automatically refresh a token when/ before it expires (see also property timeoutFactor
).oidc
defaults to true
.oidc
to false
. Otherwise, the validation of the user profile will fail!sessionStorage
is used. To use localStorage
call method setStoragerequireHttps
, e. g. for local testing.strictDiscoveryDocumentValidation
.You can use the OIDC-Sample-Server mentioned in the samples for Testing. It assumes, that your Web-App runns on http://localhost:8080.
Username/Password: max/geheim
clientIds:
redirectUris:
import { OAuthModule } from 'angular-oauth2-oidc';
[...]
@NgModule({
imports: [
[...]
HttpModule,
OAuthModule.forRoot()
],
declarations: [
AppComponent,
HomeComponent,
[...]
],
bootstrap: [
AppComponent
]
})
export class AppModule {
}
This section shows how to use the implicit flow, which is redirecting the user to the auth-server for the login.
To configure the library you just have to set some properties on startup. For this, the following sample uses the constructor of the AppComponent which is called before routing kicks in.
@Component({ ... })
export class AppComponent {
constructor(private oauthService: OAuthService) {
// URL of the SPA to redirect the user to after login
this.oauthService.redirectUri = window.location.origin + "/index.html";
// The SPA's id. The SPA is registerd with this id at the auth-server
this.oauthService.clientId = "spa-demo";
// set the scope for the permissions the client should request
// The first three are defined by OIDC. The 4th is a usecase-specific one
this.oauthService.scope = "openid profile email voucher";
// The name of the auth-server that has to be mentioned within the token
this.oauthService.issuer = "https://steyer-identity-server.azurewebsites.net/identity";
// Load Discovery Document and then try to login the user
this.oauthService.loadDiscoveryDocument().then(() => {
// This method just tries to parse the token(s) within the url when
// the auth-server redirects the user back to the web-app
// It dosn't send the user the the login page
this.oauthService.tryLogin();
});
}
}
When you don't have a discovery document, you have to configure more properties manually:
@Component({ ... })
export class AppComponent {
constructor(private oauthService: OAuthService) {
// Login-Url
this.oauthService.loginUrl = "https://steyer-identity-server.azurewebsites.net/identity/connect/authorize"; //Id-Provider?
// URL of the SPA to redirect the user to after login
this.oauthService.redirectUri = window.location.origin + "/index.html";
// The SPA's id. Register SPA with this id at the auth-server
this.oauthService.clientId = "spa-demo";
// set the scope for the permissions the client should request
this.oauthService.scope = "openid profile email voucher";
// Use setStorage to use sessionStorage or another implementation of the TS-type Storage
// instead of localStorage
this.oauthService.setStorage(sessionStorage);
// To also enable single-sign-out set the url for your auth-server's logout-endpoint here
this.oauthService.logoutUrl = "https://steyer-identity-server.azurewebsites.net/identity/connect/endsession";
// This method just tries to parse the token(s) within the url when
// the auth-server redirects the user back to the web-app
// It dosn't send the user the the login page
this.oauthService.tryLogin();
}
}
import { Component } from '@angular/core';
import { OAuthService } from 'angular-oauth2-oidc';
@Component({
templateUrl: "app/home.html"
})
export class HomeComponent {
constructor(private oAuthService: OAuthService) {
}
public login() {
this.oAuthService.initImplicitFlow();
}
public logoff() {
this.oAuthService.logOut();
}
public get name() {
let claims = this.oAuthService.getIdentityClaims();
if (!claims) return null;
return claims.given_name;
}
}
<h1 *ngIf="!name">
Hallo
</h1>
<h1 *ngIf="name">
Hallo, {{name}}
</h1>
<button class="btn btn-default" (click)="login()">
Login
</button>
<button class="btn btn-default" (click)="logoff()">
Logout
</button>
<div>
Username/Passwort zum Testen: max/geheim
</div>
You can hook in an implementation of the interface TokenValidator
to validate the signature of the received id_token and its at_hash property. This packages provides two implementations:
The former one validates the signature against public keys received via the discovery document (property jwks) and the later one skips the validation on client side.
import { JwksValidationHandler } from 'angular-oauth2-oidc';
[...]
this.oauthService.tokenValidationHandler = new JwksValidationHandler();
In cases where no ValidationHandler is defined, you receive a warning on the console. This means that the library wants you to explicitly decide on this.
Pass this Header to the used method of the Http
-Service within an Instance of the class Headers
:
var headers = new Headers({
"Authorization": "Bearer " + this.oauthService.getAccessToken()
});
To refresh your tokens when using implicit flow you can use a silent refresh. This is a well-known solution that compensates the fact that implicit flow does not allow for issuing a refresh token. It uses a hidden iframe to get another token from the auth-server. When the user is there still logged in (by using a cookie) it will respond without user interaction and provide new tokens.
To use this approach, setup a redirect uri for the silent refresh:
this.oauthService.silentRefreshRedirectUri = window.location.origin + "/silent-refresh.html";
Please keep in mind that this uri has to be configured at the auth-server too.
This file is loaded into the hidden iframe after getting new tokens. Its only task is to send the received tokens to the main application:
<html>
<body>
<script>
parent.postMessage(location.hash, location.origin);
</script>
</body>
</html>
Please make sure that this file is copied to your output directory by your build task. When using the CLI you can define it as an asset for this. For this, you have to add the following line to the file .angular-cli.json
:
"assets": [
[...],
"silent-refresh.html"
],
To perform a silent refresh, just call the following method:
this
.oauthService
.silentRefresh()
.then(info => console.debug('refresh ok', info))
.catch(err => console.error('refresh error', err));
When there is an error in the iframe that prevents the communication with the main application, silentRefresh will give you a timeout. To configure the timespan for this, you can set the property siletRefreshTimeout
(msec). The default value is 20.000 (20 seconds).
To automatically refresh a token when/ some time before it expires, you can make use of the event token_expires
:
this
.oauthService
.events
.filter(e => e.type == 'token_expires')
.subscribe(e => {
this.oauthService.silentRefresh();
});
By default, this event is fired after 75% of the token's life time is over. You can adjust this factor by setting the property timeoutFactor
to a value between 0 and 1. For instance, 0.5 means, that the event is fired after half of the life time is over and 0.33 triggers the event after a third.
There is a callback onTokenReceived
, that is called after a successful login. In this case, the lib received the access_token as
well as the id_token, if it was requested. If there is an id_token, the lib validated it.
this.oauthService.tryLogin({
onTokenReceived: context => {
//
// Output just for purpose of demonstration
// Don't try this at home ... ;-)
//
console.debug("logged in");
console.debug(context);
}
});
When calling initImplicitFlow
, you can pass an optional state which could be the requested url:
this.oauthService.initImplicitFlow('http://www.myurl.com/x/y/z');
After login succeeded, you can read this state:
this.oauthService.tryLogin({
onTokenReceived: (info) => {
console.debug('state', info.state);
}
})
You can set the property customQueryParams
to a hash with custom parameter that are transmitted when starting implicit flow.
this.oauthService.customQueryParams = {
'tenant': '4711',
'otherParam': 'someValue'
};
If you are leveraging the LocationStrategy
which the Router is using by default, you can skip this section.
When using the HashStrategy
for Routing, the Router will override the received hash fragment with the tokens when it performs it initial navigation. This prevents the library from reading them. To avoid this, disable initial navigation when setting up the routes for your root module:
export let AppRouterModule = RouterModule.forRoot(APP_ROUTES, {
useHash: true,
initialNavigation: false
});
After tryLogin did its job, you can manually perform the initial navigation:
this.oauthService.tryLogin().then(_ => {
this.router.navigate(['/']);
})
Another solution is the use a redirect uri that already contains the initial route. In this case the router will not override it. An example for such a redirect uri is
http://localhost:8080/#/home
this.oauthService.events.subscribe(e => {
console.debug('oauth/oidc event', e);
})
This section shows how to use the password flow, which demands the user to directly enter his or her password into the client.
To configure the library you just have to set some properties on startup. For this, the following sample uses the constructor of the AppComponent which is called before routing kicks in.
Please not, that this configuation is quite similar to the one for the implcit flow.
@Component({ ... })
export class AppComponent {
constructor(private oauthService: OAuthService) {
// The SPA's id. Register SPA with this id at the auth-server
this.oauthService.clientId = "demo-resource-owner";
// set the scope for the permissions the client should request
// The auth-server used here only returns a refresh token (see below), when the scope offline_access is requested
this.oauthService.scope = "openid profile email voucher offline_access";
// Use setStorage to use sessionStorage or another implementation of the TS-type Storage
// instead of localStorage
this.oauthService.setStorage(sessionStorage);
// Set a dummy secret
// Please note that the auth-server used here demand the client to transmit a client secret, although
// the standard explicitly cites that the password flow can also be used without it. Using a client secret
// does not make sense for a SPA that runs in the browser. That's why the property is called dummyClientSecret
// Using such a dummy secreat is as safe as using no secret.
this.oauthService.dummyClientSecret = "geheim";
// Load Discovery Document and then try to login the user
let url = 'https://steyer-identity-server.azurewebsites.net/identity/.well-known/openid-configuration';
this.oauthService.loadDiscoveryDocument(url).then(() => {
// Do what ever you want here
});
}
}
In cases where you don't have an OIDC based discovery document you have to configure some more properties manually:
@Component({ ... })
export class AppComponent {
constructor(private oauthService: OAuthService) {
// Login-Url
this.oauthService.tokenEndpoint = "https://steyer-identity-server.azurewebsites.net/identity/connect/token";
// Url with user info endpoint
// This endpont is described by OIDC and provides data about the loggin user
// This sample uses it, because we don't get an id_token when we use the password flow
// If you don't want this lib to fetch data about the user (e. g. id, name, email) you can skip this line
this.oauthService.userinfoEndpoint = "https://steyer-identity-server.azurewebsites.net/identity/connect/userinfo";
// The SPA's id. Register SPA with this id at the auth-server
this.oauthService.clientId = "demo-resource-owner";
// set the scope for the permissions the client should request
this.oauthService.scope = "openid profile email voucher offline_access";
// Set a dummy secret
// Please note that the auth-server used here demand the client to transmit a client secret, although
// the standard explicitly cites that the password flow can also be used without it. Using a client secret
// does not make sense for a SPA that runs in the browser. That's why the property is called dummyClientSecret
// Using such a dummy secreat is as safe as using no secret.
this.oauthService.dummyClientSecret = "geheim";
}
}
this.oauthService.fetchTokenUsingPasswordFlow('max', 'geheim').then((resp) => {
// Loading data about the user
return this.oauthService.loadUserProfile();
}).then(() => {
// Using the loaded user data
let claims = this.oAuthService.getIdentityClaims();
if (claims) console.debug('given_name', claims.given_name);
})
There is also a short form for fetching the token and loading the user profile:
this.oauthService.fetchTokenUsingPasswordFlowAndLoadUserProfile('max', 'geheim').then(() => {
let claims = this.oAuthService.getIdentityClaims();
if (claims) console.debug('given_name', claims.given_name);
});
Using the password flow you MIGHT get a refresh token (which isn't the case with the implicit flow by design!). You can use this token later to get a new access token, e. g. after it expired.
this.oauthService.refreshToken().then(() => {
console.debug('ok');
})
FAQs
Support for OAuth 2(.1) and OpenId Connect (OIDC) in Angular
The npm package angular-oauth2-oidc receives a total of 145,438 weekly downloads. As such, angular-oauth2-oidc popularity was classified as popular.
We found that angular-oauth2-oidc demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 0 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Research
Security News
Socket researchers uncover a malicious npm package posing as a tool for detecting vulnerabilities in Etherium smart contracts.
Security News
Research
A supply chain attack on Rspack's npm packages injected cryptomining malware, potentially impacting thousands of developers.
Research
Security News
Socket researchers discovered a malware campaign on npm delivering the Skuld infostealer via typosquatted packages, exposing sensitive data.