Skip to content

Commit

Permalink
Merge pull request #6 from vapor/tn-payload-verify
Browse files Browse the repository at this point in the history
Fix Payload Verification
  • Loading branch information
tanner0101 authored Jan 7, 2020
2 parents 3dd3cff + ac5d6cc commit 01c623f
Show file tree
Hide file tree
Showing 3 changed files with 37 additions and 3 deletions.
10 changes: 9 additions & 1 deletion Sources/JWTKit/JWTSigner.swift
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,15 @@ public final class JWTSigner {
where Message: DataProtocol, Payload: JWTPayload
{
let parser = try JWTParser(token: token)
return try self.verify(parser: parser)
}

func verify<Payload>(parser: JWTParser) throws -> Payload
where Payload: JWTPayload
{
try parser.verify(using: self)
return try parser.payload(as: Payload.self)
let payload = try parser.payload(as: Payload.self)
try payload.verify(using: self)
return payload
}
}
3 changes: 1 addition & 2 deletions Sources/JWTKit/JWTSigners.swift
Original file line number Diff line number Diff line change
Expand Up @@ -84,8 +84,7 @@ public final class JWTSigners {
{
let parser = try JWTParser(token: token)
let header = try parser.header()
try parser.verify(using: self.require(kid: header.kid))
return try parser.payload(as: Payload.self)
return try self.require(kid: header.kid).verify(parser: parser)
}

public func sign<Payload>(
Expand Down
27 changes: 27 additions & 0 deletions Tests/JWTKitTests/JWTKitTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -230,6 +230,33 @@ class JWTKitTests: XCTestCase {
XCTAssertEqual(a.algorithm.name, "RS256")
XCTAssertEqual(b.algorithm.name, "RS512")
}

func testJWTPayloadVerification() throws {
struct NotBar: Error {
let foo: String
}
struct Payload: JWTPayload {
let foo: String
func verify(using signer: JWTSigner) throws {
guard self.foo == "bar" else {
throw NotBar(foo: self.foo)
}
}
}

let signer = try JWTSigner.es256(key: .generate())
do {
let token = try signer.sign(Payload(foo: "qux"))
_ = try signer.verify(token, as: Payload.self)
} catch let error as NotBar {
XCTAssertEqual(error.foo, "qux")
}
do {
let token = try signer.sign(Payload(foo: "bar"))
let payload = try signer.verify(token, as: Payload.self)
XCTAssertEqual(payload.foo, "bar")
}
}
}

struct TestPayload: JWTPayload, Equatable {
Expand Down

0 comments on commit 01c623f

Please sign in to comment.