Rest Auth
Rest authentication integration support for the Travetto framework
Install: @travetto/auth-rest
npm install @travetto/auth-rest
yarn add @travetto/auth-rest
This is a primary integration for the Authentication module. This is another level of scaffolding allowing for compatible authentication frameworks to integrate.
The integration with the RESTful API module touches multiple levels. Primarily:
- Patterns for auth framework integrations
- Route declaration
- Multi-Step Login
Patterns for Integration
Every external framework integration relies upon the Authenticator contract. This contract defines the boundaries between both frameworks and what is needed to pass between. As stated elsewhere, the goal is to be as flexible as possible, and so the contract is as minimal as possible:
Code: Structure for the Identity Source
import { AnyMap } from '@travetto/runtime';
import { Principal } from './principal';
export interface AuthenticatorState extends AnyMap { }
export interface Authenticator<T = unknown, C = unknown, P extends Principal = Principal> {
getState?(context?: C): Promise<AuthenticatorState | undefined> | AuthenticatorState | undefined;
authenticate(payload: T, context?: C): Promise<P | undefined> | P | undefined;
}
The only required method to be defined is the authenticate
method. This takes in a pre-principal payload and a filter context with a Request and Response, and is responsible for:
- Returning an Principal if authentication was successful
- Throwing an error if it failed
- Returning undefined if the authentication is multi-staged and has not completed yet
A sample auth provider would look like:
Code: Sample Identity Source
import { AuthenticationError, Authenticator } from '@travetto/auth';
type User = { username: string, password: string };
export class SimpleAuthenticator implements Authenticator<User> {
async authenticate({ username, password }: User) {
if (username === 'test' && password === 'test') {
return {
id: 'test',
source: 'simple',
permissions: [],
details: {
username: 'test'
}
};
} else {
throw new AuthenticationError('Invalid credentials');
}
}
}
The provider must be registered with a custom symbol to be used within the framework. At startup, all registered Authenticator's are collected and stored for reference at runtime, via symbol. For example:
Code: Potential Facebook provider
import { InjectableFactory } from '@travetto/di';
import { SimpleAuthenticator } from './source';
export const FB_AUTH = Symbol.for('auth-facebook');
export class AppConfig {
@InjectableFactory(FB_AUTH)
static facebookIdentity() {
return new SimpleAuthenticator();
}
}
The symbol FB_AUTH
is what will be used to reference providers at runtime. This was chosen, over class
references due to the fact that most providers will not be defined via a new class, but via an @InjectableFactory method.
Route Declaration
@Login integrates with middleware that will authenticate the user as defined by the specified providers, or throw an error if authentication is unsuccessful.
@Logout integrates with middleware that will automatically deauthenticate a user, throw an error if the user is unauthenticated.
Code: Using provider with routes
import { Controller, Get, Redirect, Request } from '@travetto/rest';
import { Login, Authenticated, Logout } from '@travetto/auth-rest';
import { FB_AUTH } from './facebook';
@Controller('/auth')
export class SampleAuth {
@Get('/simple')
@Login(FB_AUTH)
async simpleLogin() {
return new Redirect('/auth/self', 301);
}
@Get('/self')
@Authenticated()
async getSelf(req: Request) {
return req.auth;
}
@Get('/logout')
@Logout()
async logout() {
return new Redirect('/auth/self', 301);
}
}
@Authenticated and @Unauthenticated will simply enforce whether or not a user is logged in and throw the appropriate error messages as needed. Additionally, the Principal is accessible via @Context directly, without wiring in a request object, but is also accessible on the request object as Request.auth.
Multi-Step Login
When authenticating, with a multi-step process, it is useful to share information between steps. The authenticatorState
of AuthContext field is intended to be a location in which that information is persisted. Currently only passport support is included, when dealing with multi-step logins. This information can also be injected into a rest endpoint method, using the Authenticator type;