Skip to content

Commit 7f176b3

Browse files
committed
Get JWT token from auth header in JWTStorageMiddleware
Intead of getting it from the request's private container, where it certainly won't exist at that point yet.
1 parent 1ec4691 commit 7f176b3

File tree

1 file changed

+17
-4
lines changed

1 file changed

+17
-4
lines changed

Sources/JWTMiddleware/JWTVerificationMiddleware.swift

Lines changed: 17 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -15,14 +15,27 @@ public final class JWTStorageMiddleware<Payload: JWTPayload>: Middleware {
1515
/// See `Middleware.respond(to:chainingTo:)`.
1616
public func respond(to request: Request, chainingTo next: Responder) throws -> Future<Response> {
1717

18-
// 1. Get the payload from the request
19-
// 2. Store the payload in the request
18+
// 1. Get the JWT from the request
19+
// 2. Verify the JWT
20+
// 3. Store the payload in the request
2021
// for easier access.
21-
// 3. Fire the next responder.
22+
// 4. Fire the next responder.
2223

23-
let payload: Payload = try request.payload()
24+
// Extract the token from the request. It is expected to
25+
// be in the `Authorization` header as a bearer: `Bearer ...`
26+
guard let token = request.http.headers.bearerAuthorization?.token else {
27+
throw Abort(.badRequest, reason: "'Authorization' header with bearer token is missing")
28+
}
2429

30+
// Get JWT service to verify the token with
31+
let jwt = try request.make(JWTService.self)
32+
let data = Data(token.utf8)
33+
34+
// Verify to token and store the payload in the request's private container.
35+
let payload = try JWT<Payload>(from: data, verifiedUsing: jwt.signer).payload
2536
try request.set("skelpo-payload", to: payload)
37+
38+
// Fire the next responder in the chain.
2639
return try next.respond(to: request)
2740
}
2841
}

0 commit comments

Comments
 (0)