diff --git a/packages/openneuro-server/src/libs/authentication/__tests__/jwt.spec.ts b/packages/openneuro-server/src/libs/authentication/__tests__/jwt.spec.ts index c62e3d9f5..eefb2746a 100644 --- a/packages/openneuro-server/src/libs/authentication/__tests__/jwt.spec.ts +++ b/packages/openneuro-server/src/libs/authentication/__tests__/jwt.spec.ts @@ -1,6 +1,6 @@ import { vi } from "vitest" import User from "../../../models/user" -import { addJWT } from "../jwt" +import { addJWT, jwtFromRequest } from "../jwt" vi.mock("ioredis") vi.mock("../../../config.ts") @@ -21,4 +21,39 @@ describe("jwt auth", () => { expect(obj).toHaveProperty("token") }) }) + describe("jwtFromRequest()", () => { + it("handles both cookie and authorization headers", () => { + const cookieToken = "1234" + const headersToken = "Bearer 5678" + const cookieRequest = { + cookies: { + accessToken: cookieToken, + }, + } + const headersRequest = { + headers: { + authorization: headersToken, + }, + } + expect(jwtFromRequest(cookieRequest)).toEqual(cookieToken) + expect(jwtFromRequest(headersRequest)).toEqual("5678") + }) + it("prefers authorization header when cookies are present", () => { + const req = { + cookies: { + accessToken: "1234", + }, + headers: { + authorization: "Bearer 5678", + }, + } + expect(jwtFromRequest(req)).toEqual("5678") + }) + it("returns null when authorization header is missing", () => { + const req = { + headers: {}, + } + expect(jwtFromRequest(req)).toEqual(null) + }) + }) }) diff --git a/packages/openneuro-server/src/libs/authentication/jwt.ts b/packages/openneuro-server/src/libs/authentication/jwt.ts index bd51beecd..066aedbd9 100644 --- a/packages/openneuro-server/src/libs/authentication/jwt.ts +++ b/packages/openneuro-server/src/libs/authentication/jwt.ts @@ -120,7 +120,16 @@ const requestNewAccessToken = (jwtProvider, refreshToken) => * @param {Object} req */ export const jwtFromRequest = (req) => { - if (req.cookies && req.cookies.accessToken) { + if (req.headers?.authorization) { + try { + return req.headers.authorization.substring( + 7, + req.headers.authorization.length, + ) + } catch (_err) { + return null + } + } else if (req.cookies && req.cookies.accessToken) { return req.cookies.accessToken } else { return null