Getting token in middleware doesn't work with authorization header request
See original GitHub issueEnvironment
System: OS: macOS 11.6 CPU: (4) x64 Intel® Core™ i5-7360U CPU @ 2.30GHz Memory: 169.62 MB / 16.00 GB Shell: 3.2.57 - /bin/bash Binaries: Node: 16.13.0 - /usr/local/bin/node Yarn: 1.22.15 - ~/.yarn/bin/yarn npm: 8.1.0 - /usr/local/bin/npm Browsers: Brave Browser: 72.0.59.35 Chrome: 98.0.4758.102 Edge: 98.0.1108.56 Safari: 14.1.2 npmPackages: next: ^12.0.7 => 12.0.9 next-auth: ^4.2.1 => 4.2.1 react: 17.0.2 => 17.0.2
Reproduction URL
None
Describe the issue
When using just the authorization header, the getToken(req) method returns correctly in the server with NextApiRequest, but not in the middleware with NextRequest. When I dug through the code, it seems it’s because NextApiRequest authorization header is in the list, whereas getToken function is trying to split the authorization header by space, which shouldn’t work for this case.
How to reproduce
For any OAuth provider, get the raw token.
Use it from a REST client with the Authorization: Bearer <token> and send an API request.
In the middleware, try getToken({req}). It returns null, whereas in the actual API route code, it returns the token info correctly. Also, it works correctly when a user actually logs in in the browser and there’s cookies and other jazz from the browser.
The middleware code is very simple:
import { getToken } from "next-auth/jwt"
import { NextRequest, NextResponse } from "next/server"
export async function middleware(req: NextRequest) {
const token = await getToken({ req })
console.log("Middleware token", token)
NextResponse.next()
}
My API request is:
GET http://localhost:3000/api/<api_path> HTTP/1.1
Content-Type: application/json
Authorization: Bearer {{token}}
Expected behavior
I should get the token info in the middleware with just the auth header with bearer token (not only with browser session).
Issue Analytics
- State:
- Created 2 years ago
- Comments:27 (5 by maintainers)
Why is this closed? The original issue has not been resolved yet
Hmm thanks ! Buts still not working for me even with next@12.2.0 and the middleware in the root it keep asking for authentification
Update : I comfirm that downgrading to @12.2.0 make all working for now