TypeSafeHTTPBasic

public protocol TypeSafeHTTPBasic : TypeSafeCredentials

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:

public struct MyHTTPBasic: TypeSafeHTTPBasic {

   public var id: String

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

   public static let realm = "Login message"

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

struct User: Codable {
   let name: String
}

router.get("/protected") { (authedUser: MyHTTPBasic, respondWith: (User?, RequestError?) -> Void) in
   let user = User(name: authedUser.id)
   respondWith(user, nil)
}
  • realm Default implementation

    The realm for which these credentials are valid (defaults to “User”)

    Default Implementation

    The realm for which these credentials are valid (defaults to “User”)

    Declaration

    Swift

    static var realm: String { get }
  • The function that takes a username, a password and a callback which accepts a TypeSafeHTTPBasic instance on success or nil on failure.

    Declaration

    Swift

    static func verifyPassword(username: String, password: String, callback: @escaping (Self?) -> Void)
  • provider Extension method

    The name of the authentication provider (defaults to “HTTPBasic”)

    Declaration

    Swift

    public var provider: String { get }
  • Authenticate incoming request using HTTP Basic authentication.

    Declaration

    Swift

    public static func authenticate(request: RouterRequest, response: RouterResponse, onSuccess: @escaping (Self) -> Void, onFailure: @escaping (HTTPStatusCode?, [String : String]?) -> Void, onSkip: @escaping (HTTPStatusCode?, [String : String]?) -> Void)

    Parameters

    request

    The RouterRequest object used to get information about the request.

    response

    The RouterResponse object used to respond to the request.

    onSuccess

    The closure to invoke in the case of successful authentication.

    onFailure

    The closure to invoke in the case of an authentication failure.

    onSkip

    The closure to invoke when the plugin doesn’t recognize the authentication data in the request.