Retrieve jwt user info from id token (#7424)

Co-authored-by: Nelson Silva <nsilva@nuxeo.com>
This commit is contained in:
Eugenio Romano
2021-12-14 10:44:19 +01:00
committed by GitHub
parent ddcd97ca37
commit 1cbee53cdb
3 changed files with 48 additions and 10 deletions

View File

@@ -28,6 +28,7 @@ export class JwtHelperService {
static GIVEN_NAME = 'given_name';
static USER_EMAIL = 'email';
static USER_ACCESS_TOKEN = 'access_token';
static USER_ID_TOKEN = 'id_token';
static REALM_ACCESS = 'realm_access';
static RESOURCE_ACCESS = 'resource_access';
static USER_PREFERRED_USERNAME = 'preferred_username';
@@ -76,6 +77,15 @@ export class JwtHelperService {
return decodeURIComponent(escape(window.atob(output)));
}
/**
* Gets a named value from the user access or id token.
* @param key Key name of the field to retrieve
* @returns Value from the token
*/
getValueFromLocalToken<T>(key: string): T {
return this.getValueFromToken(this.getAccessToken(), key) || this.getValueFromToken(this.getIdToken(), key);
}
/**
* Gets a named value from the user access token.
* @param key Key name of the field to retrieve
@@ -93,16 +103,33 @@ export class JwtHelperService {
return this.storageService.getItem(JwtHelperService.USER_ACCESS_TOKEN);
}
/**
* Gets a named value from the user id token.
* @param key Key name of the field to retrieve
* @returns Value from the token
*/
getValueFromLocalIdToken<T>(key: string): T {
return this.getValueFromToken(this.getIdToken(), key);
}
/**
* Gets id token
* @returns id token
*/
getIdToken(): string {
return this.storageService.getItem(JwtHelperService.USER_ID_TOKEN);
}
/**
* Gets a named value from the user access token.
* @param accessToken your SSO access token where the value is encode
* @param key Key name of the field to retrieve
* @returns Value from the token
*/
getValueFromToken<T>(accessToken: string, key: string): T {
getValueFromToken<T>(token: string, key: string): T {
let value;
if (accessToken) {
const tokenPayload = this.decodeToken(accessToken);
if (token) {
const tokenPayload = this.decodeToken(token);
value = tokenPayload[key];
}
return <T> value;