Replies: 5 comments 6 replies
-
import Vapor
import JWT
import MongoKitten
public final class JWTMiddleware: Middleware {
public init() {}
public func respond(to request: Request, chainingTo next: Responder) -> EventLoopFuture<Response> {
guard let token = request.headers.bearerAuthorization?.token.utf8 else {
return request.eventLoop.makeFailedFuture(
Abort(.unauthorized, reason: "Missing authorization bearer header")
)
}
do {
request.payload = try request.jwt.verify(Array(token), as: Payload.self)
} catch let JWTError.claimVerificationFailure(name: name, reason: reason) {
request.logger.error("JWT Verification Failure: \(name) \(reason)")
return request.eventLoop.makeFailedFuture(JWTError.claimVerificationFailure(name: name, reason: reason))
} catch let error {
return request.eventLoop.makeFailedFuture(
Abort(.unauthorized, reason: "You are not authorized this token \(error)")
)
}
return next.respond(to: request)
}
}
extension AnyHashable {
static let payload: String = "jwt_payload"
}
extension Request {
var loggedIn: Bool {
return self.storage[PayloadKey.self] != nil ? true : false
}
var payload: Payload {
get { self.storage[PayloadKey.self]! } // should not use it
set { self.storage[PayloadKey.self] = newValue }
}
} |
Beta Was this translation helpful? Give feedback.
-
my routes
try app.group("v1") { api in
let events = api.grouped("events")
let eventsAuth = events.grouped(JWTMiddleware())
try eventsAuth.register(collection: EventController() )
}
// inside controller i use like this
if request.loggedIn == false { throw Abort(.unauthorized) } but for vapor-router no option |
Beta Was this translation helpful? Give feedback.
-
Hi @saroar! Since this is a question and not a bug report, I'm going to convert this to a discussion where more eyes might see it. If there is a deficiency in the library we'd definitely take a PR to correct it, though! |
Beta Was this translation helpful? Give feedback.
-
I really just loving it and enjoy how awesome it just working but when I send header from client I have to get it in my server and check it this is what we have discuss on discord with @0xTim |
Beta Was this translation helpful? Give feedback.
-
What a coincidence, I'm just in the process of converting our routing to use the parser printer and I'm also running into the issue that I've got one route wrapped in auth middlewares: app.group(User.TokenAuthenticator(), User.guardMiddleware()) { protected in
protected.on(.POST, SiteURL.api(.versions(.key, .builds)).pathComponents,
use: API.BuildController.create)
}
app.mount(SiteRoute.router, use: SiteRoute.handler) API. I suppose one way could be a custom |
Beta Was this translation helpful? Give feedback.
-
how do i can use it ? is there any option?
Beta Was this translation helpful? Give feedback.
All reactions