Git Product home page Git Product logo

Comments (9)

tanner0101 avatar tanner0101 commented on May 18, 2024 2

The idea for Vapor 4 is to create a vapor/jwt package that integrates JWTKit with Vapor. This hasn't been done yet, but should be fairly trivial. I'll leave this issue open to track that.

from jwt.

clayellis avatar clayellis commented on May 18, 2024

These are the pieces that @anthonycastelli shared with me (reposted here with his permission):

JWTMiddleware

import Foundation
import Vapor
import JWT

final class JWTMiddleware: Middleware, Service {
    func respond(to request: Request, chainingTo next: Responder) throws -> Future<Response> {
        guard let authorization = request.http.headers["Authorization"].first,
            let bearer = authorization.split(separator: " ").first,
            let token = authorization.split(separator: " ").last, bearer == "Bearer"
            else { throw Abort(.unauthorized, reason: "No Authorization Header") }
        
        let jwt: JWTService = try request.make()
        let payload = try JWT<JWTAuthPayload>(from: String(token), verifiedUsing: jwt.signer).payload
        guard let userId = UUID(uuidString: payload.userId) else { throw Abort(.unauthorized, reason: "Invalid User") }
        return request.newConnection(to: .psql)
            .flatMap(to: User?.self) { con in
                return try User.find(userId, on: con)
            }.flatMap(to: Response.self) {
                if let u = $0 {
                    try request.authenticate(u)
                }
                _ = try request.requireAuthenticated(User.self)
                return try next.respond(to: request)
        }
    }
}

JWTService

final class JWTService: Service {
    
    var signer: JWTSigner
    
    init(secret: String) throws {
        self.signer = JWTSigner.hs512(key: Data(secret.utf8))
    }
    
    func signUser<T: CanteenModel>(_ user: T, type: JWTAuthPayload.UserType) throws -> String {
        let expiration = ExpirationClaim(value: Date(timeIntervalSinceNow:(60 * 60 * 1))) // 60 minutes x 1 hour
        var jwt = JWT(payload:
            JWTAuthPayload(
                exp: expiration,
                userId: user.id?.uuidString ?? ""
            )
        )
        let data = try self.signer.sign(&jwt)
        return String(data: data, encoding: .utf8) ?? ""
    }
}

JWTAuthPayload

struct JWTAuthPayload: JWTPayload {
    enum CodingKeys: String, CodingKey {
        case exp
        case userId = "user_id"
    }
    
    var exp: ExpirationClaim
    var userId: String
    
    func verify() throws {
        try self.exp.verify()
    }
}

I think the forthcoming JWTAuthenticationMiddleware should leverage TokenAuthenticationMiddleware (which in turn leverages BearerAuthenticationMiddleware).

from jwt.

clayellis avatar clayellis commented on May 18, 2024

Another popular solution that could prove useful as a reference is @calebkleveter's JWTMiddleware.

from jwt.

tanner0101 avatar tanner0101 commented on May 18, 2024

This is related to my issue here: vapor/auth#53

from jwt.

valeriomazzeo avatar valeriomazzeo commented on May 18, 2024

This provides a similar functionality to the old vapor-community/jwt-provider: https://github.com/asensei/vapor-auth-jwt

from jwt.

nysander avatar nysander commented on May 18, 2024

Is here any progress to make it work?

from jwt.

clayellis avatar clayellis commented on May 18, 2024

Not that I'm aware of. @tanner0101 should we just close this out?

from jwt.

nysander avatar nysander commented on May 18, 2024

I like this idea to make it core feature

from jwt.

tanner0101 avatar tanner0101 commented on May 18, 2024

This package is now a JWTKit + Vapor integration.

from jwt.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.