-
Notifications
You must be signed in to change notification settings - Fork 13
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
feat: TypeSafeHTTPBasic #49
Changes from 18 commits
af361c7
dc3a9c7
ac5b3e4
22dd1c9
afe4141
8db3211
da3b3f8
9a11e88
9bc969b
184d673
61f06d2
408fd04
437f97a
dfdd87d
9143deb
3af6f5d
a44d0c1
0fa0015
8123547
1438888
1132a35
8e9c956
ca6906e
55f1a80
a3fb68e
5752c55
384fbdc
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,130 @@ | ||
/** | ||
* Copyright IBM Corporation 2018 | ||
* | ||
* Licensed under the Apache License, Version 2.0 (the "License"); | ||
* you may not use this file except in compliance with the License. | ||
* You may obtain a copy of the License at | ||
* | ||
* http://www.apache.org/licenses/LICENSE-2.0 | ||
* | ||
* Unless required by applicable law or agreed to in writing, software | ||
* distributed under the License is distributed on an "AS IS" BASIS, | ||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
* See the License for the specific language governing permissions and | ||
* limitations under the License. | ||
**/ | ||
|
||
import Kitura | ||
import KituraNet | ||
import Credentials | ||
|
||
import Foundation | ||
|
||
/** | ||
A `TypeSafeCredentials` plugin for HTTP basic authentication. | ||
This protocol will be implemented by a Swift object defined by the user. | ||
The plugin must implement a `verifyPassword` function which takes a username and password as input | ||
and returns an instance of `Self` on success or `nil` on failure. | ||
This instance must contain the authentication `provider` (defaults to "HTTPBasic") and an `id`, uniquely identifying the user. | ||
The users object can then be used in TypeSafeMiddlware routes to authenticate with HTTP basic. | ||
### Usage Example: ### | ||
```swift | ||
public struct MyHTTPBasic: TypeSafeHTTPBasic { | ||
|
||
public var id: String | ||
|
||
static let users = ["John" : "12345", "Mary" : "qwerasdf"] | ||
|
||
public static let realm = "Login message" | ||
|
||
public static var verifyPassword: ((String, String, @escaping (MyHTTPBasic?) -> Void) -> Void) = | ||
{ userId, password, callback in | ||
if let storedPassword = users[userId], storedPassword == password { | ||
callback(MyHTTPBasic(id: userId)) | ||
} else { | ||
callback(nil) | ||
} | ||
} | ||
} | ||
|
||
struct User: Codable { | ||
let name: String | ||
} | ||
|
||
router.get("/authedFruits") { (authedUser: MyHTTPBasic, respondWith: (User?, RequestError?) -> Void) in | ||
let user = User(name: authedUser.id) | ||
respondWith(user, nil) | ||
} | ||
``` | ||
*/ | ||
public protocol TypeSafeHTTPBasic : TypeSafeCredentials { | ||
|
||
/// The realm for which these credentials are valid (defaults to "User") | ||
static var realm: String { get } | ||
|
||
/// The closure which takes a username and password and returns a TypeSafeHTTPBasic instance on success or nil on failure. | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Comment needs updating now that this is a function |
||
static var verifyPassword: ((String, String, @escaping (Self?) -> Void) -> Void) { get } | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This isn't very type-safe, did you consider replacing these Strings with something protocol-based? There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I think we should replace with something like static func verifyPassword(username: String, password, String, callback: @escaping (Self?) -> Void) -> Void Xcode will auto-complete this much nicer than the version where we define a closure signature, and apply the labels which indicates how to handle each argument. |
||
|
||
} | ||
|
||
extension TypeSafeHTTPBasic { | ||
|
||
/// The name of the authentication provider (defaults to "HTTPBasic") | ||
public var provider: String { | ||
return "HTTPBasic" | ||
} | ||
|
||
/// The realm for which these credentials are valid (defaults to "User") | ||
public static var realm: String { | ||
return "User" | ||
} | ||
|
||
/// Authenticate incoming request using HTTP Basic authentication. | ||
/// | ||
/// - Parameter request: The `RouterRequest` object used to get information | ||
/// about the request. | ||
/// - Parameter response: The `RouterResponse` object used to respond to the | ||
/// request. | ||
/// - Parameter onSuccess: The closure to invoke in the case of successful authentication. | ||
/// - Parameter onFailure: The closure to invoke in the case of an authentication failure. | ||
/// - Parameter onSkip: The closure to invoke when the plugin doesn't recognize the | ||
/// authentication data in the request. | ||
public static func authenticate(request: RouterRequest, response: RouterResponse, onSuccess: @escaping (Self) -> Void, onFailure: @escaping (HTTPStatusCode?, [String : String]?) -> Void, onSkip: @escaping (HTTPStatusCode?, [String : String]?) -> Void) { | ||
|
||
let userid: String | ||
let password: String | ||
if let requestUser = request.urlURL.user, let requestPassword = request.urlURL.password { | ||
userid = requestUser | ||
password = requestPassword | ||
} | ||
else { | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Please put the else on the previous line. |
||
guard let authorizationHeader = request.headers["Authorization"] else { | ||
return onSkip(.unauthorized, ["WWW-Authenticate" : "Basic realm=\"" + realm + "\""]) | ||
} | ||
|
||
let authorizationHeaderComponents = authorizationHeader.components(separatedBy: " ") | ||
guard authorizationHeaderComponents.count == 2, | ||
authorizationHeaderComponents[0] == "Basic", | ||
let decodedData = Data(base64Encoded: authorizationHeaderComponents[1], options: Data.Base64DecodingOptions(rawValue: 0)), | ||
let userAuthorization = String(data: decodedData, encoding: .utf8) else { | ||
return onSkip(.unauthorized, ["WWW-Authenticate" : "Basic realm=\"" + realm + "\""]) | ||
} | ||
let credentials = userAuthorization.components(separatedBy: ":") | ||
guard credentials.count >= 2 else { | ||
onFailure(.badRequest, nil) | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
|
||
return | ||
} | ||
userid = credentials[0] | ||
password = credentials[1] | ||
} | ||
|
||
verifyPassword(userid, password) { selfInstance in | ||
if let selfInstance = selfInstance { | ||
onSuccess(selfInstance) | ||
} | ||
else { | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Same comment. |
||
onFailure(.unauthorized, ["WWW-Authenticate" : "Basic realm=\"" + self.realm + "\""]) | ||
} | ||
} | ||
} | ||
} |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,129 @@ | ||
/** | ||
* Copyright IBM Corporation 2016 | ||
* | ||
* Licensed under the Apache License, Version 2.0 (the "License"); | ||
* you may not use this file except in compliance with the License. | ||
* You may obtain a copy of the License at | ||
* | ||
* http://www.apache.org/licenses/LICENSE-2.0 | ||
* | ||
* Unless required by applicable law or agreed to in writing, software | ||
* distributed under the License is distributed on an "AS IS" BASIS, | ||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
* See the License for the specific language governing permissions and | ||
* limitations under the License. | ||
**/ | ||
|
||
import Foundation | ||
import XCTest | ||
|
||
import Kitura | ||
import KituraNet | ||
import Credentials | ||
|
||
@testable import CredentialsHTTP | ||
|
||
class TestTypeSafeBasic : XCTestCase { | ||
|
||
static var allTests : [(String, (TestTypeSafeBasic) -> () throws -> Void)] { | ||
return [ | ||
("testTypeSafeNoCredentials", testTypeSafeNoCredentials), | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This array is missing some of the tests! There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Tests have been added and this file has been added to linux main |
||
] | ||
} | ||
|
||
override func setUp() { | ||
doSetUp() | ||
} | ||
|
||
override func tearDown() { | ||
doTearDown() | ||
} | ||
|
||
let host = "127.0.0.1" | ||
|
||
let router = TestTypeSafeBasic.setupTypeSafeRouter() | ||
|
||
func testTypeSafeNoCredentials() { | ||
performServerTest(router: router) { expectation in | ||
self.performRequest(method: "get", host: self.host, path: "/private/typesafebasic", callback: {response in | ||
XCTAssertNotNil(response, "ERROR!!! ClientRequest response object was nil") | ||
XCTAssertEqual(response?.statusCode, HTTPStatusCode.unauthorized, "HTTP Status code was \(String(describing: response?.statusCode))") | ||
XCTAssertEqual(response?.headers["WWW-Authenticate"]?.first, "Basic realm=\"test\"") | ||
expectation.fulfill() | ||
}) | ||
} | ||
} | ||
|
||
func testTypeSafeBadCredentials() { | ||
|
||
performServerTest(router: router) { expectation in | ||
self.performRequest(method: "get", path:"/private/typesafebasic", callback: {response in | ||
XCTAssertNotNil(response, "ERROR!!! ClientRequest response object was nil") | ||
XCTAssertEqual(response?.statusCode, HTTPStatusCode.unauthorized, "HTTP Status code was \(String(describing: response?.statusCode))") | ||
XCTAssertEqual(response?.headers["WWW-Authenticate"]?.first, "Basic realm=\"test\"") | ||
expectation.fulfill() | ||
}, headers: ["Authorization" : "Basic QWxhZGRpbjpPcGVuU2VzYW1l"]) | ||
} | ||
|
||
performServerTest(router: router) { expectation in | ||
self.performRequest(method: "get", path:"/private/typesafebasic", callback: {response in | ||
XCTAssertNotNil(response, "ERROR!!! ClientRequest response object was nil") | ||
XCTAssertEqual(response?.statusCode, HTTPStatusCode.unauthorized, "HTTP Status code was \(String(describing: response?.statusCode))") | ||
XCTAssertEqual(response?.headers["WWW-Authenticate"]?.first, "Basic realm=\"test\"") | ||
expectation.fulfill() | ||
}, headers: ["Authorization" : "Basic"]) | ||
} | ||
} | ||
|
||
func testTypeSafeBasic() { | ||
|
||
performServerTest(router: router) { expectation in | ||
self.performRequest(method: "get", path:"/private/typesafebasic", callback: {response in | ||
XCTAssertNotNil(response, "ERROR!!! ClientRequest response object was nil") | ||
XCTAssertEqual(response?.statusCode, HTTPStatusCode.OK, "HTTP Status code was \(String(describing: response?.statusCode))") | ||
do { | ||
let body = try response?.readString() | ||
XCTAssertEqual(body,"{\"name\":\"Mary\",\"provider\":\"HTTPBasic\"}") | ||
} | ||
catch{ | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Merge with previous line. |
||
XCTFail("No response body") | ||
} | ||
expectation.fulfill() | ||
}, headers: ["Authorization" : "Basic TWFyeTpxd2VyYXNkZg=="]) | ||
} | ||
} | ||
|
||
static func setupTypeSafeRouter() -> Router { | ||
let router = Router() | ||
|
||
router.get("/private/typesafebasic") { (authedUser: TestHTTPBasic, respondWith: (User?, RequestError?) -> Void) in | ||
let user = User(name: authedUser.id, provider: authedUser.provider) | ||
respondWith(user, nil) | ||
} | ||
|
||
return router | ||
} | ||
|
||
public struct TestHTTPBasic: TypeSafeHTTPBasic { | ||
|
||
public let id: String | ||
|
||
static let users = ["John" : "12345", "Mary" : "qwerasdf"] | ||
|
||
public static let realm = "test" | ||
|
||
public static var verifyPassword: ((String, String, @escaping (TestHTTPBasic?) -> Void) -> Void) = | ||
{ userId, password, callback in | ||
if let storedPassword = users[userId], storedPassword == password { | ||
callback(TestHTTPBasic(id: userId)) | ||
} else { | ||
callback(nil) | ||
} | ||
} | ||
} | ||
|
||
struct User: Codable { | ||
let name: String | ||
let provider: String | ||
} | ||
} |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Usage example needs updating now that this is a function