Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(server): Allow authorization bearer token header for API access #2944

Merged
merged 1 commit into from
Nov 19, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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 @@
* @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