Skip to content

Commit

Permalink
AP-5754 support for providing custom header name for auth prehandler
Browse files Browse the repository at this point in the history
  • Loading branch information
kjamrog committed Dec 4, 2024
1 parent fa93e78 commit fd16950
Show file tree
Hide file tree
Showing 2 changed files with 101 additions and 29 deletions.
124 changes: 96 additions & 28 deletions lib/route-utils/authPreHandlers.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,23 @@ describe('authPreHandlers', () => {
})
},
})

// Using custom header name
app.route({
method: 'GET',
url: '/developer',
preHandler: createStaticTokenAuthPreHandler(
SECRET_TOKEN,
(_req) => globalLogger,
'developer-token',
),
handler: (_req: FastifyRequest, res: FastifyReply) => {
res.status(200).send({
data: 'ok',
})
},
})

//For showing 4xx errors in pre handler throws error (instead of 500).
app.setErrorHandler(
createErrorHandler({
Expand All @@ -32,42 +49,93 @@ describe('authPreHandlers', () => {
await app.ready()
})

it('accepts request if secret token provided in request is valid', async () => {
const response = await app
.inject()
.get('/')
.headers({
authorization: `Bearer ${SECRET_TOKEN}`,
describe('default header name', () => {
it('accepts request if secret token provided in request is valid', async () => {
const response = await app
.inject()
.get('/')
.headers({
authorization: `Bearer ${SECRET_TOKEN}`,
})
.end()

expect(response.statusCode).toBe(200)
expect(response.json()).toEqual({
data: 'ok',
})
.end()
})

expect(response.statusCode).toBe(200)
expect(response.json()).toEqual({
data: 'ok',
it('rejects with 401 if no token', async () => {
const response = await app.inject().get('/').end()
expect(response.statusCode).toBe(401)
expect(response.json()).toEqual({
errorCode: 'AUTH_FAILED',
message: 'Authentication failed',
})
})
})

it('rejects with 401 if no token', async () => {
const response = await app.inject().get('/').end()
expect(response.statusCode).toBe(401)
expect(response.json()).toEqual({
errorCode: 'AUTH_FAILED',
message: 'Authentication failed',
it('rejects with 401 if invalid token', async () => {
const response = await app
.inject()
.get('/')
.headers({
authorization: 'bearer invalid_token',
})
.end()
expect(response.statusCode).toBe(401)
expect(response.json()).toEqual({
errorCode: 'AUTH_FAILED',
message: 'Authentication failed',
})
})
})

it('rejects with 401 if invalid token', async () => {
const response = await app
.inject()
.get('/')
.headers({
authorization: 'bearer invalid_token',
describe('custom header name', () => {
it('accepts request if token is valid', async () => {
const response = await app
.inject()
.get('/developer')
.headers({
'developer-token': `Bearer ${SECRET_TOKEN}`,
})
.end()

expect(response.statusCode).toBe(200)
expect(response.json()).toEqual({
data: 'ok',
})
})

it('rejects with 401 if token is not provided', async () => {
const response = await app
.inject()
.get('/developer')
.headers({
authorization: `Bearer ${SECRET_TOKEN}`, // Using default header name while custom one is specified
})
.end()

expect(response.statusCode).toBe(401)
expect(response.json()).toEqual({
errorCode: 'AUTH_FAILED',
message: 'Authentication failed',
})
})

it('rejects with 401 if token is invalid', async () => {
const response = await app
.inject()
.get('/developer')
.headers({
authorization: 'Bearer invalid-token',
})
.end()

expect(response.statusCode).toBe(401)
expect(response.json()).toEqual({
errorCode: 'AUTH_FAILED',
message: 'Authentication failed',
})
.end()
expect(response.statusCode).toBe(401)
expect(response.json()).toEqual({
errorCode: 'AUTH_FAILED',
message: 'Authentication failed',
})
})
})
6 changes: 5 additions & 1 deletion lib/route-utils/authPreHandlers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ const BEARER_PREFIX_LENGTH = BEARER_PREFIX.length
export function createStaticTokenAuthPreHandler(
configuredSecretToken: string,
loggerProvider: (req: FastifyRequest) => CommonLogger,
authHeaderName = 'authorization',
) {
return function preHandlerStaticTokenAuth(
req: FastifyRequest,
Expand All @@ -15,7 +16,10 @@ export function createStaticTokenAuthPreHandler(
) {
const logger: CommonLogger = loggerProvider(req)

const authHeader = req.headers.authorization
const authHeaderValue = req.headers[authHeaderName]
const authHeader =
!!authHeaderValue && Array.isArray(authHeaderValue) ? authHeaderValue[0] : authHeaderValue

if (!authHeader?.startsWith(BEARER_PREFIX)) {
logger.error('Token not present')
return done(new AuthFailedError())
Expand Down

0 comments on commit fd16950

Please sign in to comment.