Token (Authorization Bearer) authenication with a table holding the tokens.
GET /name HTTP/1.1
Authorization: Bearer foobar
Host: 0.0.0.0:8080
Connection: close
Content-Length: 0
The most common use case: authenication with a table holding the tokens.
users | tokens |
---|---|
id | id |
name | token |
user_id |
A basic Vapor Model type with a name using the "users" table.
import Vapor
class SomeUser: Model {
let name: String
// all sorts of model code
}
Basic Vapor Model representing the "tokens" table.
import Vapor
class SomeToken: Model {
// code for representing a token type with some "tokens" table
}
Conforming the user to TokenAuthenticatable
requires specifying the
token type.
Since both the token type and the user itself are entities, the authentication is automatically implemented using a Fluent join.
import Authentication
extension SomeUser: TokenAuthenticatable {
typealias TokenType = SomeToken
}
This makes it easier to access the user using just req.user()
import HTTP
import Authentication
extension Request {
func user() throws -> SomeUser {
return try auth.authenticated()
}
}
A TokenAuthenticationMiddleware
must be added to protected routes.
All requests that fail to authenticate will be rejected.
let drop = Droplet()
let authMiddleware = TokenAuthenticationMiddleware(SomeUser.self)
let authed = drop.grouped(authMiddleware)
authed.get("name") { req in
// return the users name
return try req.user().name
}
users | tokens |
---|---|
id | id |
name | foo |
user_id |
Should the key which contains the token on the tokens table ("token"
in the previous example)
be different, the protocol must be informed.
import Authentication
extension SomeUser: TokenAuthenticatable {
typealias TokenType = SomeToken
static let tokenKey = "foo"
}
users |
---|
id |
name |
To do custom authentication with the token, just set TokenType to self and implement the authenticate method.
extension SomeUser: TokenAuthenticatable {
typealias TokenType = Self
static func authenticate(_ token: Token) throws -> Self {
// some custom method for looking up the user
}
}
Let's see if I understand correctly:
Possible disadvantages:
Am I on the right track?