Skip to content
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

Merged
merged 27 commits into from
Jun 5, 2018
Merged
Show file tree
Hide file tree
Changes from 16 commits
Commits
Show all changes
27 commits
Select commit Hold shift + click to select a range
af361c7
point at private repo
Andrew-Lees11 Apr 23, 2018
dc3a9c7
update package
Andrew-Lees11 Apr 24, 2018
ac5b3e4
Implement UserHTTPBasic prototype
djones6 Apr 25, 2018
22dd1c9
Fixes for demo
djones6 May 16, 2018
afe4141
change to pluginName
Andrew-Lees11 May 23, 2018
8db3211
Merge branch 'typeSafeMiddleware' of github.ibm.com:Andrew-Lees11/Kit…
Andrew-Lees11 May 23, 2018
da3b3f8
point at correct credentials
Andrew-Lees11 May 31, 2018
9a11e88
added TypeSafeHTTPBasic protocol
Andrew-Lees11 Jun 1, 2018
9bc969b
use Self in protocol
Andrew-Lees11 Jun 1, 2018
184d673
removed inProgress
Andrew-Lees11 Jun 1, 2018
61f06d2
removed auth redecleration
Andrew-Lees11 Jun 1, 2018
408fd04
added jazzy docs
Andrew-Lees11 Jun 1, 2018
437f97a
added back changed line
Andrew-Lees11 Jun 1, 2018
dfdd87d
docs on different lines
Andrew-Lees11 Jun 1, 2018
9143deb
pass to skip
Andrew-Lees11 Jun 1, 2018
3af6f5d
added codable routes example to readme
Andrew-Lees11 Jun 1, 2018
a44d0c1
remove public from readme
Andrew-Lees11 Jun 4, 2018
0fa0015
added tests
Andrew-Lees11 Jun 4, 2018
8123547
refactoring and adding to alltests
Andrew-Lees11 Jun 4, 2018
1438888
added tests to linux main
Andrew-Lees11 Jun 4, 2018
1132a35
fixed test
Andrew-Lees11 Jun 4, 2018
8e9c956
added equatable func
Andrew-Lees11 Jun 4, 2018
ca6906e
made verify passwor function
Andrew-Lees11 Jun 4, 2018
55f1a80
made tests use function
Andrew-Lees11 Jun 4, 2018
a3fb68e
update docs for verify func
Andrew-Lees11 Jun 4, 2018
5752c55
fix typo
Andrew-Lees11 Jun 4, 2018
384fbdc
point at cred 2.2
Andrew-Lees11 Jun 5, 2018
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 36 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,42 @@ CredentialsHTTPDigest initialization is similar to CredentialsHTTPBasic. In addi

## Example

### Codable routing

First create a struct or final class that conforms to `TypeSafeHTTPBasic`,
adding any instance variables which you will initialise in verifyPassword:

```swift
import CredentialsHTTP

public struct MyBasicAuth: TypeSafeHTTPBasic {

public let id: String

public static let users = ["John" : "12345", "Mary" : "qwerasdf"]
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Probably make this private!


public static var verifyPassword: ((String, String, @escaping (MyBasicAuth?) -> Void) -> Void) =
{ userId, password, callback in
if let storedPassword = users[userId], storedPassword == password {
callback(MyBasicAuth(id: userId))
} else {
callback(nil)
}
}

}
```

Add authentication to routes by adding your `TypeSafeHTTPBasic` object, as a `TypeSafeMiddleware`, to your codable routes:

```swift
router.get("/authedFruits") { (userProfile: MyBasicAuth, respondWith: (MyBasicAuth?, RequestError?) -> Void) in
print("authenticated \(userProfile.id) using \(userProfile.provider)")
respondWith(userProfile, nil)
}
```

### Raw routing
This example shows how to use this plugin to authenticate requests with HTTP Basic authentication. HTTP Digest authentication is similar.
<br>

Expand Down
130 changes: 130 additions & 0 deletions Sources/CredentialsHTTP/TypeSafeHTTPBasic.swift
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

public static let users = ["John" : "12345", "Mary" : "qwerasdf"]

public static let realm = "Login message"

public static var verifyPassword: ((String, String, @escaping (MyHTTPBasic?) -> Void) -> Void) =
Copy link
Contributor

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

{ 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.
Copy link
Contributor

Choose a reason for hiding this comment

The 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 }
Copy link
Collaborator

Choose a reason for hiding this comment

The 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?

Copy link
Contributor

Choose a reason for hiding this comment

The 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 {
Copy link
Collaborator

Choose a reason for hiding this comment

The 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)
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

return onFailure...

return
}
userid = credentials[0]
password = credentials[1]
}

verifyPassword(userid, password) { selfInstance in
if let selfInstance = selfInstance {
onSuccess(selfInstance)
}
else {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same comment.

onFailure(.unauthorized, ["WWW-Authenticate" : "Basic realm=\"" + self.realm + "\""])
}
}
}
}