Skip to content

Commit

Permalink
Merge pull request #2944 from OpenNeuroOrg/feat/api-header-auth
Browse files Browse the repository at this point in the history
fix(server): Allow authorization bearer token header for API access
  • Loading branch information
nellh authored Nov 19, 2023
2 parents d239e8d + c218202 commit a49b7af
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 2 deletions.
Original file line number Diff line number Diff line change
@@ -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")
Expand All @@ -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)
})
})
})
11 changes: 10 additions & 1 deletion packages/openneuro-server/src/libs/authentication/jwt.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down

0 comments on commit a49b7af

Please sign in to comment.