Skip to content

Commit

Permalink
Merge branch 'hotfix/refresh-token-expired'
Browse files Browse the repository at this point in the history
  • Loading branch information
randilfernando committed Dec 30, 2017
2 parents c236b3e + 9924efe commit 7cbff93
Show file tree
Hide file tree
Showing 4 changed files with 44 additions and 21 deletions.
22 changes: 18 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,15 @@ This library uses HttpClient to send http requests.

Click [here](https://embed.plnkr.co/qstWVYDhzfY4L4YF5Pxp?p=preview) to find a working demo.

## Available Functionality

1. Basic authentication (Login, logout, check status)
1. Http interceptor to append tokens
1. Can extend the authentication flow (via setAuth function)
1. Decode and get token value (This will decode the token and return the requested value)
1. User permissions to manage access
1. Refresh tokens workflow

## Add library to your project

```bash
Expand Down Expand Up @@ -45,9 +54,9 @@ export interface AuthConfig {
refreshTokenUrl?: string;
getPermissionUrl?: string;
permissionDataSet?: UserPermissions[];
tokenGetter: (tokenName: string) => Promise<string>;
tokenSetter: (tokenName: string, token: string) => Promise<any>;
tokenRemover: (tokenName: string) => Promise<any>;
tokenGetter?: (tokenName: string) => Promise<string>;
tokenSetter?: (tokenName: string, token: string) => Promise<any>;
tokenRemover?: (tokenName: string) => Promise<any>;
}
```

Expand Down Expand Up @@ -118,7 +127,12 @@ export const DEFAULT_ADDITIONAL_AUTH_CONFIG: AuthConfigAdditional = {
1. accessTokenExpiredResponseStatus - Response status when access token expired. (used to retry the response)
1. accessTokenExpiredErrorCode - You need to send error code inside the access token expired response. (used to retry the response)

>Note: Token interceptor will check error response for above conditions and retry the response.
>Note: Token interceptor will check error response for above conditions and retry the response. If refresh token not enabled user will logout
1. refreshTokenExpiredResponseStatus - Response status when refresh token expired
2. refreshTokenExpiredErrorCode - You need to send error code inside the refresh token expired response.

>Note: If a refresh token expired response received the user will logout.
1. accessTokenHeaderName - Header name use when appending access token in each request.
1. accessTokenPrefix - Prefix used when appending token (eg: Bearer {access-token})
Expand Down
5 changes: 3 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,12 @@
"name": "simple-angular-jwt-auth",
"description": "authentication package for angular 5 using HttpClientModule",
"author": "[email protected]",
"version": "0.0.8",
"version": "0.0.9",
"license": "MIT",
"scripts": {
"build": "ng-packagr -p ng-package.json",
"pack": "npm run build && cd ./dist && npm pack"
"pack": "npm run build && cd ./dist && npm pack",
"lint": "tslint --project ./"
},
"repository": {
"type": "git",
Expand Down
16 changes: 8 additions & 8 deletions src/modules/auth/providers/auth/auth.provider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,14 @@ export class AuthProvider {
}
}

public getValueInToken<T>(key: string): T {
if (this.accessToken) {
return <T>(TokenDecoderHelper.DecodeToken(this.accessToken)[key]);
} else {
return null;
}
}

private async setAccessToken(token: string, persist: boolean = true): Promise<boolean> {
const condition = token !== null && typeof token === 'string' && token.length > 0;

Expand All @@ -109,14 +117,6 @@ export class AuthProvider {
return condition;
}

public getValueInToken<T>(key: string): T {
if (this.accessToken) {
return <T>(TokenDecoderHelper.DecodeToken(this.accessToken)[key]);
} else {
return null;
}
}

private async getAuth(): Promise<Auth> {
if (!this.accessToken && this.authConfig.persistTokensEnabled) {
const accessTokenPromise = this.authConfig.tokenGetter(this.authConfig.accessTokenStorageKey);
Expand Down
22 changes: 15 additions & 7 deletions src/modules/auth/providers/token/token.interceptor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ import 'rxjs/add/operator/mergeMap';
import 'rxjs/add/observable/throw';

import {AuthProvider} from '../auth/auth.provider';
import {ApiError} from '../../types/api-error.type';
import {AuthConfig} from '../../types/auth-config.type';
import {AuthConfigAdditional} from '../../types/auth-config-additional.type';
import {AuthConfigProvider} from '../auth-config/auth-config.provider';
Expand All @@ -28,13 +27,22 @@ export class TokenInterceptor implements HttpInterceptor {
private handleError(error: HttpErrorResponse | any, request: HttpRequest<any>, next: HttpHandler) {
const errorBody = this.authConfig.convertToApiErrorType(error.error);

if (this.authConfig.refreshTokenEnabled && error.status === this.authConfig.accessTokenExpiredResponseStatus &&
const authProvider = this.injector.get(AuthProvider);

if (error.status === this.authConfig.accessTokenExpiredResponseStatus &&
errorBody.errorCode === this.authConfig.accessTokenExpiredErrorCode) {
const authProvider = this.injector.get(AuthProvider);
return Observable.fromPromise(authProvider.refresh()).mergeMap((status) => {
const authenticatedRequest = this.authenticate(request);
return next.handle(authenticatedRequest);
});

if (this.authConfig.refreshTokenEnabled) {
return Observable.fromPromise(authProvider.refresh()).mergeMap(() => {
const authenticatedRequest = this.authenticate(request);
return next.handle(authenticatedRequest);
});
} else {
authProvider.logOut();
}
} else if (error.status === this.authConfig.refreshTokenExpiredResponseStatus &&
errorBody.errorCode === this.authConfig.refreshTokenExpiredErrorCode) {
authProvider.logOut();
}

return Observable.throw(new Error(`${errorBody.errorMessage} error occurred. error code is ${errorBody.errorCode}`));
Expand Down

0 comments on commit 7cbff93

Please sign in to comment.