Skip to content

Commit

Permalink
null token is considered expired
Browse files Browse the repository at this point in the history
  • Loading branch information
un33k committed May 21, 2018
1 parent 58fea08 commit 78d5dfa
Show file tree
Hide file tree
Showing 4 changed files with 46 additions and 12 deletions.
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,9 @@
## 1.0.2

Bugfix:

- Empty or invalid token is considered expired

## 1.0.1

Enhancements:
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@nwx/jwt",
"version": "1.0.1",
"version": "1.0.2",
"repository": {
"type": "git",
"url": "git+https://github.com/neekware/nwx-jwt.git"
Expand Down
30 changes: 19 additions & 11 deletions pkgs/jwt/src/jwt.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,18 +40,26 @@ export class JwtService {
* @returns a payload object or null if decode fails
*/
getPayload(token: string): any {
const parts = token.split('.');
if (parts.length !== 3) {
this.log.error('JWT must have 3 parts');
} else {
try {
const decoded = Base64.decode(parts[1]);
const payload = JSON.parse(decoded);
return payload;
} catch (e) {
this.log.error('Cannot decode the token');
let parts = [];

try {
parts = token.split('.');
if (parts.length !== 3) {
throw Error('JWT must have 3 parts');
}
} catch (e) {
this.log.error(e.message);
return null;
}

try {
const decoded = Base64.decode(parts[1]);
const payload = JSON.parse(decoded);
return payload;
} catch (e) {
this.log.error('Cannot decode the token');
}

return null;
}

Expand All @@ -71,7 +79,7 @@ export class JwtService {
const expired = now > expiry + offset;
return expired;
}
return false;
return true;
}

/**
Expand Down
20 changes: 20 additions & 0 deletions pkgs/jwt/tst/jwt.service.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,26 @@ describe('JwtService', () => {
})
);

it(
'should verify expiry on a null token',
inject([JwtService], (service: JwtService) => {
const token = null;
const payload = service.getPayload(token);
const isExpired = service.isExpired(payload);
expect(isExpired).toBe(true);
})
);

it(
'should verify expiry on a token with missing parts',
inject([JwtService], (service: JwtService) => {
const token = 'part1.part2';
const payload = service.getPayload(token);
const isExpired = service.isExpired(payload);
expect(isExpired).toBe(true);
})
);

it(
'should verify refresh time on a valid token',
inject([JwtService], (service: JwtService) => {
Expand Down

0 comments on commit 78d5dfa

Please sign in to comment.