A pluggable framework for validating user credentials in a Swift server using Kitura
Fetching latest commit…
Cannot retrieve the latest commit at this time.
Permalink
Type Name Latest commit message Commit time
Failed to load latest commit information.
.github Updated Travis and contributing / pull request templates Apr 29, 2016
Sources/Credentials MultiCredentials docs update (#71) Jul 25, 2018
Tests
docs
.gitignore
.gitmodules
.jazzy.yaml
.swift-version Update to Swift 4.2.1, test on Ubuntu 16.04 and 18.04 (#73) Nov 13, 2018
.travis.yml Update to Swift 4.2.1, test on Ubuntu 16.04 and 18.04 (#73) Nov 13, 2018
LICENSE.txt
Package.swift fix: update package.swift for typeSafeMiddleware (#65) Jun 5, 2018
README.md
docker-compose.yml

README.md

Kitura

Docs Build Status - Master macOS Linux Apache 2 Slack Status

Kitura-Credentials

A pluggable framework for validating user credentials in a Swift server using Kitura

Summary

Kitura-Credentials is an authentication middleware for Kitura. Kitura-Credentials recognizes that each application has unique authentication requirements. It allows individual authentication mechanisms to be packaged as plugins which it consumes.

Plugins can range from a simple password based authentication or delegated authentication using OAuth (via Facebook OAuth provider, etc.), or federated authentication using OpenID.

There are two main authentication schemes supported by Kitura-Credentials: redirecting and non-redirecting. Redirecting scheme is used for example in OAuth2 Authorization Code flow authentication, where the users, that are not logged in, are redirected to a login page. All other types of authentication are non-redirecting, i.e., unauthorized requests are rejected (usually with 401 Unauthorized HTTP status code). An example of non-redirecting authentication is delegated authentication using OAuth access token (also called bearer token) that was independently acquired (say by a mobile app or other client of the Kitura based backend).

Kitura-Credentials middleware checks if the request belongs to a session. If so and the user is logged in, it updates request's user profile and propagates the request. Otherwise, it loops through the non-redirecting plugins in the order they were registered until a matching plugin is found. The plugin either succeeds to authenticate the request (in that case user profile information is returned) or fails. If a matching plugin is found but it fails to authenticate the request, HTTP status code in the router response is set to Unauthorized (401), or to the code returned from the plugin along with HTTP headers, and the request is not propagated. If no matching plugin is found, in case the request belongs to a session and a redirecting plugin exists, the request is redirected. Otherwise, HTTP status code in the router response is set to Unauthorized (401), or to the first code returned from the plugins along with HTTP headers, and the request is not propagated. In case of successful authentication, request's user profile is set with user profile information received from the authenticating plugin.

In the scope of OAuth2 Authorization Code flow, authentication is performed by a specific plugin. Kitura-Credentials tries to login and authenticate the first request by calling the plugin and, if successful, stores the relevant data in the session for authentication of the further requests in that session. The plugin will not be called for other requests within the scope of the session.

Table of Contents

Swift version

The latest version of Kitura-Credentials requires Swift 4.0 or newer. You can download this version of the Swift binaries by following this link. Compatibility with other Swift versions is not guaranteed.

Example

Codable routing

Within Codable routes, you implement a single credentials plugin by defining a Swift type that conforms to the plugins implementation of TypeSafeCredentials. This can then be applied to a codable route by defining it in the route signiture:

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

To apply multiple authentication methods to a route, you define a type which conforms to TypeSafeMultiCredentials and add it to your codable route signiture. The type must define an array of TypeSafeCredentials types, that will be queried in order, to attempt to authenticate a user. It must also define an initialiser that creates an instance of self from an instance of the TypeSafeCredentials type.

If a user can authenticate with either HTTP basic or a token, and has defined the types BasicAuthedUser and TokenAuthedUser, then an implementation could be as follows:

public struct MultiAuthedUser : TypeSafeMultiCredentials {

    public let id: String
    public let provider: String

    public static var authenticationMethods: [TypeSafeCredentials.Type] = [BasicAuthedUser.self, TokenAuthedUser.self]

    public init(successfulAuth: TypeSafeCredentials) {
        self.id = successfulAuth.id
        self.provider = successfulAuth.provider
    }
}

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

Raw routing

For OAuth2 Authorization Code flow authentication example please see Kitura-Credentials-Sample.

The following is an example of token-based authentication using Facebook OAuth2 access tokens.This example authenticates post requests using CredentialsFacebookToken plugin.

First create an instance of Credentials and an instance of credentials plugin:

import Credentials
import CredentialsFacebook

let credentials = Credentials()
let fbCredentialsPlugin = CredentialsFacebookToken()

You can also set options (a dictionary of options passed to the plugin) either using the designated initializer or by setting them directly.

Now register the plugin:

credentials.register(fbCredentialsPlugin)

Kitura-Credentials framework is RouterMiddleware. To connect it to the desired path use one of the Router methods. After successful authentication request.userProfile will contain an instance of UserProfile with user profile information received from OAuth server using the plugin.

router.post("/collection/:new", middleware: credentials)
router.post("/collection/:new") {request, response, next in
   ...
   let profile = request.userProfile
   let userId = profile.id
   let userName = profile.displayName
   ...
   next()
}

List of plugins:

License

This library is licensed under Apache 2.0. Full license text is available in LICENSE.