This example shows how to implement Basic authentication yourself. It is based on the vapor-4 api template.
By using UserAuthenticator().middleware()
as a global middleware (added in configure.swift
), we will try to fetch a user for all requests.
I have added two ways of protecting routes:
a) using a protectedRoute with a GuardMiddleware()
for Todo-related endpoints (see routes.swift
)
b) using req.auth.has(User.self)
in UserController.swift
to protect single endpoints (as we dont want to protect the register user endpoint).
UserAuthenticator().middleware()
try to fetch a user for any given request and attach the fetched user to the request objectGuardMiddleware()
simply checks if aAuthenticatable
model is attached to the request and throws if not.
UserAuthenticator.swift
: Implements basic auth for our User, checking if theusername
matches ouremail
and thepassword
matches ourpasswordHash
UserController.swift
: Provides routes to create/get users.User.swift
: Our user model; conforms toAuthenticatable
routes.swift
: Added a protected route forTodo
related endpoints usingGuardMiddleware
.configure.swift
: Added theUserAuthenticator().middleware()
to the global middlewares.