From f2c6321216fd4dcd043f087980896b4466cb039d Mon Sep 17 00:00:00 2001 From: Hammad Date: Tue, 24 Oct 2023 16:22:45 +0500 Subject: [PATCH] raises proper exception when token is invalid or empty --- CommonServer/Middleware/BearerTokenAuthorization.ts | 6 +++--- .../Tests/Middleware/BearerTokenAuthorization.test.ts | 6 +++--- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/CommonServer/Middleware/BearerTokenAuthorization.ts b/CommonServer/Middleware/BearerTokenAuthorization.ts index 9685ca5636..4091d88025 100644 --- a/CommonServer/Middleware/BearerTokenAuthorization.ts +++ b/CommonServer/Middleware/BearerTokenAuthorization.ts @@ -17,12 +17,12 @@ export default class BearerTokenAuthorization { try { req = req as OneUptimeRequest; - if (req.headers['authorization'] || req.headers['Authorization']) { + if (req.headers?.['authorization'] || req.headers?.['Authorization']) { let token: string | undefined | Array = req.headers['authorization'] || req.headers['Authorization']; + token = token?.toString().replace('Bearer ', ''); if (token) { - token = token.toString().replace('Bearer ', ''); const tokenData: JSONObject = JSONWebToken.decodeJsonPayload(token); @@ -33,7 +33,7 @@ export default class BearerTokenAuthorization { } } - throw new NotAuthorizedException('Invalid bearer token.'); + throw new NotAuthorizedException('Invalid bearer token, or bearer token not provided.'); } catch (err) { next(err); } diff --git a/CommonServer/Tests/Middleware/BearerTokenAuthorization.test.ts b/CommonServer/Tests/Middleware/BearerTokenAuthorization.test.ts index ec84cb0728..27aaa356d3 100644 --- a/CommonServer/Tests/Middleware/BearerTokenAuthorization.test.ts +++ b/CommonServer/Tests/Middleware/BearerTokenAuthorization.test.ts @@ -62,7 +62,7 @@ describe('BearerTokenAuthorization', () => { next ); expect(next.mock.calls[0][0]).toMatchInlineSnapshot( - `[Error: Invalid bearer token.]` + `[Error: Invalid bearer token, or bearer token not provided.]` ); }); it('calls next with exception if token is invalid', () => { @@ -80,7 +80,7 @@ describe('BearerTokenAuthorization', () => { next ); expect(next.mock.calls[0][0]).toMatchInlineSnapshot( - `[JsonWebTokenError: jwt must be provided]` + `[Error: Invalid bearer token, or bearer token not provided.]` ); }); it('calls next with exception if token header is not present', () => { @@ -95,7 +95,7 @@ describe('BearerTokenAuthorization', () => { next ); expect(next.mock.calls[0][0]).toMatchInlineSnapshot( - `[TypeError: Cannot read properties of undefined (reading 'authorization')]` + `[Error: Invalid bearer token, or bearer token not provided.]` ); }); });