JSON Web Tokens in Vapor, Part 4: Getting Info from the Payload

378 Views

In the last part of this series, we will cover how to get info from the payload of a JWT. It's fairly easy, so should be a short tutorial.

In TokenHelpers.swift, add the function:

    class func getEmail(fromPayloadOf token: String) throws -> String {
        do { let receivedJWT = try JWT(token: token)
            let payload = receivedJWT.payload
            return try payload.get("username")
        } catch { throw JWebTokenError.parsingPayload }
    }

This just initializes a JWT object from the token string, and then returns the email in the payload that we set earlier. To silence the error created by the throw.. statement, add the following to the JWebTokeError enum:

    ....
    case parsingPayload
    switch self {
      ...
      case .parsingPayload: return "Error parsing JWT payload"
    }

Next, in the TokenHelpers.swift file, but outside the class definition, add the following extension:

    extension Request {
      func token() -> String {
          if let token = self.headers["Authorization"]?.string {
              return token
          }
          return ""
       }
    }

Now, in your setupRoutes() function, add the following the the author.get("protected"... route:

    let token = request.token()
    let email = try TokenHelpers.getEmail(fromPayloadOf: token)
    return try JSON(node: ["email": email])

Here we simply get the email from the helper function, and return it.

That's all for the series on JSON Web Tokens in Vapor! Questions/comments welcome below.



Enjoy this article? Consider supporting VaporForums by following us on Twitter! Get the latest Vapor articles, tutorials, and news.