Skip to main content

Token Handler Service

Overview​

The TokenHandlerService is an Angular service that provides methods for managing authentication tokens. It is responsible for storing, retrieving, and refreshing tokens used for authentication in Angular applications. The TokenHandlerService simplifies token management and ensures that tokens are securely stored and handled.

Methods​

The TokenHandlerService provides the following methods for managing authentication tokens:

setStorage​

The setStorage method allows you to set a custom storage mechanism for tokens. By default, the TokenHandlerService uses localStorage to store tokens. This method allows you to override this default behavior and use a custom storage implementation.

Parameters​

ParametersTypeDescription
storageOAuthStorageThe custom storage implementation to use. It must implement the OAuthStorage interface.

Usage​

app.component.ts
import { TokenHandlerService, TokenResponse } from '@celerofinancas/oauth';
import { MyCustomStorage } from './my-custom-storage';

@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
constructor(private tokenHandler: TokenHandlerService) {}

public setStorage() {
this.tokenHandler.setStorage(new MyCustomStorage());
}
}

storeTokens​

The storeTokens method is responsible for saving authentication tokens into the defined storage (by default, localStorage). It stores the access, refresh, and ID tokens along with their respective expiration dates. This method also emits an event indicating that the tokens have been received.

Parameters​

ParametersTypeDescription
tokensTokensModelAn object containing the access, refresh, and ID tokens along with their expiration dates.

Usage​

app.component.ts
import { TokenHandlerService, TokenResponse } from '@celerofinancas/oauth';

@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
constructor(private tokenHandler: TokenHandlerService) {}

tokens: TokenResponse = {
access_token: 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...',
refresh_token: 'dGhpcyByZWZyZXNoIHRva2Vu...',
id_token: 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...',
expires_in: 3600,
refresh_expires_in: 7200,
};

public storeTokens(tokens: TokensModel) {
this.tokenHandler.storeTokens(tokens);
}
}

handleAutoRefresh​

The handleAutoRefresh method is responsible for managing the automatic refresh of authentication tokens. It returns an Observable that monitors token expiration events and attempts to renew the tokens automatically when necessary.

Parameters​

The handleAutoRefresh method does not require any parameters.

Usage​

app.component.ts

import { TokenHandlerService } from '@celerofinancas/oauth';

@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
constructor(private tokenHandler: TokenHandlerService) {}

public handleAutoRefresh() {
this.tokenHandler.handleAutoRefresh().subscribe();
}
}

stopAutomaticRefresh​

The stopAutomaticRefresh method is responsible for stopping the timers that manage the automatic refresh of authentication tokens. This method is useful when you want to stop the automatic refresh of tokens, for example, when logging out or when the application no longer needs to keep the tokens updated.

Parameters​

The stopAutomaticRefresh method does not require any parameters.

Usage​

app.component.ts
import { OAuthService } from '@celerofinancas/ui-oauth';

@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
constructor(private tokenHandlerService: TokenHandlerService) {}

public stopAutomaticRefresh(): void {
this.tokenHandlerService.stopAutomaticRefresh();
}
}

clearTokensFromStorage​

The clearTokensFromStorage method is responsible for removing all stored authentication tokens from the storage and emitting an event indicating that the tokens have been cleared.

Parameters​

The clearTokensFromStorage method does not require any parameters.

Usage​

app.component.ts
import { TokenHandlerService } from '@celerofinancas/oauth';

@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
constructor(private tokenHandler: TokenHandlerService) {}

public clearTokensFromStorage() {
this.tokenHandler.clearTokensFromStorage();
}
}

isIdTokenValid​

The isIdTokenValid method checks whether there is a valid id_token stored. It returns true if the id_token exists and has not expired, otherwise it returns false.

Parameters​

The isIdTokenValid method does not require any parameters.

Usage​

app.component.ts
import { TokenHandlerService } from '@celerofinancas/oauth';

@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
constructor(private tokenHandler: TokenHandlerService) {}

public isIdTokenValid() {
const isValid = this.tokenHandler.isIdTokenValid();
console.log('Is ID token valid?', isValid);
}
}

isRefreshTokenValid​

The isRefreshTokenValid method checks whether there is a valid refresh_token stored. It returns true if the refresh_token exists and has not expired, otherwise it returns false.

Parameters​

The isRefreshTokenValid method does not require any parameters.

Usage​

app.component.ts
import { TokenHandlerService } from '@celerofinancas/oauth';

@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
constructor(private tokenHandler: TokenHandlerService) {}

public isRefreshTokenValid() {
const isValid = this.tokenHandler.isRefreshTokenValid();
console.log('Is refresh token valid?', isValid);
}
}

refreshToken​

The refreshToken method is responsible for refreshing the token manually.

Parameters​

The refreshToken method does not require any parameters.

Usage​

app.component.ts
import { TokenHandlerService } from '@celerofinancas/oauth';

@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
constructor(private tokenHandler: TokenHandlerService) {}

public refreshToken() {
this.tokenHandler.refreshToken().subscribe((token) => {
// Handle the new token
});
}
}

accessToken​

The accessToken reference returns the access token stored in the storage.

Parameters​

The accessToken method does not require any parameters.

Usage​

app.component.ts
import { TokenHandlerService } from '@celerofinancas/oauth';

@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
constructor(private tokenHandler: TokenHandlerService) {}

public getAccessToken() {
const accessToken = this.tokenHandler.accessToken;
console.log('Access token:', accessToken);
}
}

idToken​

The idToken reference returns the id token stored in the storage.

Parameters​

The idToken method does not require any parameters.

Usage​

app.component.ts
import { TokenHandlerService } from '@celerofinancas/oauth';

@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
constructor(private tokenHandler: TokenHandlerService) {}

public getIdToken() {
const idToken = this.tokenHandler.idToken;
console.log('ID token:', idToken);
}
}

refreshTokenExpiration​

The refreshTokenExpiration reference returns the expiration date of the refresh_token as milliseconds since 1970.

Parameters​

The refreshTokenExpiration method does not require any parameters.

Usage​

app.component.ts
import { TokenHandlerService } from '@celerofinancas/oauth';

@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
constructor(private tokenHandler: TokenHandlerService) {}

public getRefreshTokenExpiration() {
const expiration = this.tokenHandler.refreshTokenExpiration;
console.log('Refresh token expiration:', expiration);
}
}

accessTokenExpiration​

The accessTokenExpiration reference returns the expiration date of the access_token as milliseconds since 1970.

Parameters​

The accessTokenExpiration method does not require any parameters.

Usage​

app.component.ts
import { TokenHandlerService } from '@celerofinancas/oauth';

@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
constructor(private tokenHandler: TokenHandlerService) {}

public getAccessTokenExpiration() {
const expiration = this.tokenHandler.accessTokenExpiration;
console.log('Access token expiration:', expiration);
}
}

isAccessTokenValid​

The isAccessTokenValid method checks whether there is a valid access_token stored. It returns true if the access_token exists and has not expired, otherwise it returns false.

Parameters​

The isAccessTokenValid method does not require any parameters.

Usage​

app.component.ts
import { TokenHandlerService } from '@celerofinancas/oauth';

@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
constructor(private tokenHandler: TokenHandlerService) {}

public isAccessTokenValid() {
const isValid = this.tokenHandler.isAccessTokenValid;
console.log('Is access token valid?', isValid);
}
}