From 0cea06119fe3502588ca30f7bc27b14c84ea80b4 Mon Sep 17 00:00:00 2001 From: Mihails Tumkins Date: Mon, 23 Oct 2017 10:26:23 +0300 Subject: [PATCH] add JWTError confirms to AbortError --- Sources/JWTProvider/JWTError+Status.swift | 40 +++++++++++++++++++ ...PayloadAuthenticationMiddlewareTests.swift | 20 ++++++++++ 2 files changed, 60 insertions(+) create mode 100644 Sources/JWTProvider/JWTError+Status.swift diff --git a/Sources/JWTProvider/JWTError+Status.swift b/Sources/JWTProvider/JWTError+Status.swift new file mode 100644 index 0000000..1df5ba1 --- /dev/null +++ b/Sources/JWTProvider/JWTError+Status.swift @@ -0,0 +1,40 @@ +import Vapor +import HTTP +import JWT + + +extension JWTError: AbortError { + public var status: Status { + switch self { + case .incorrectNumberOfSegments, + .incorrectPayloadForClaimVerification, + .missingAlgorithm, + .missingClaim, + .wrongAlgorithm, + .verificationFailedForClaim, + .signatureVerificationFailed: + return .unauthorized + default: + return .internalServerError + } + } +} + +extension JWTError: Debuggable { + public var reason: String { + return self.description + } + + public var identifier: String { + return self.description + } + + public var possibleCauses: [String] { + return [] + } + + public var suggestedFixes: [String] { + return [] + } +} + diff --git a/Tests/JWTProviderTests/PayloadAuthenticationMiddlewareTests.swift b/Tests/JWTProviderTests/PayloadAuthenticationMiddlewareTests.swift index 6ea5100..2e69930 100644 --- a/Tests/JWTProviderTests/PayloadAuthenticationMiddlewareTests.swift +++ b/Tests/JWTProviderTests/PayloadAuthenticationMiddlewareTests.swift @@ -4,6 +4,8 @@ import Vapor import Transport import HTTP import JWT +import AuthProvider + @testable import JWTProvider class PayloadAuthenticationMiddlewareTests: XCTestCase { @@ -14,6 +16,7 @@ class PayloadAuthenticationMiddlewareTests: XCTestCase { ("testAuthenticateWithIdentifiedToken", testAuthenticateWithIdentifiedToken), ("testAuthenticateWithIdentifiedTokenWithNoMatchingSigner", testAuthenticateWithIdentifiedTokenWithNoMatchingSigner), ("testAuthenticateWithJWKSURL", testAuthenticateWithJWKSURL), + ("testAuthenticateWithNonParsableToken", testAuthenticateWithNonParsableToken) ] func testAuthenticateWithLegacySigner() throws { @@ -106,6 +109,23 @@ class PayloadAuthenticationMiddlewareTests: XCTestCase { _ = try middleware.respond(to: request, chainingTo: MockResponder()) } + + + func testAuthenticateWithNonParsableToken() throws { + + let request = Request( + method: .get, + uri: "http://localhost/test", + headers: [HeaderKey.authorization: "Bearer nonparsablejwttoken"] + ) + + let signers = ["1234": Unsigned(), "5678": Unsigned()] + let middleware = PayloadAuthenticationMiddleware(signers) + + XCTAssertThrowsError(try middleware.respond(to: request, chainingTo: MockResponder()), "invalidCredentials") { error in + XCTAssertTrue((error as? JWTError)?.status == .unauthorized) + } + } } extension PayloadAuthenticationMiddlewareTests {