@travetto/auth-rest
v5.0.17
Published
Rest authentication integration support for the Travetto framework
Downloads
215
Maintainers
Readme
Rest Auth
Rest authentication integration support for the Travetto framework
Install: @travetto/auth-rest
npm install @travetto/auth-rest
# or
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:
- Security information management
- Patterns for auth framework integrations
- Route declaration
Security information management
When working with framework's authentication, the user information is exposed via the Request object. The auth functionality is exposed on the request as the property auth
.
Code: Structure of auth property on the request
export interface Request {
/**
* The authenticated principal
*/
auth?: Principal;
/**
* Any additional context for login
*/
[LoginContextⲐ]?: LoginContext;
}
This allows for any filters/middleware to access this information without deeper knowledge of the framework itself. Also, for performance benefits, the auth context can be stored in the user session as a means to minimize future lookups. If storing the entire principal in the session, it is best to keep the principal as small as possible.
When authenticating, with a multi-step process, it is useful to share information between steps. The loginContext
property is intended to be a location in which that information is persisted. Currently only passport support is included, when dealing with multi-step logins.
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 { Principal } from './principal';
/**
* Supports validation payload of type T into an authenticated principal
*
* @concrete ../internal/types#AuthenticatorTarget
*/
export interface Authenticator<T = unknown, P extends Principal = Principal, C = unknown> {
/**
* Allows for the authenticator to be initialized if needed
* @param ctx
*/
initialize?(ctx: C): Promise<void>;
/**
* Verify the payload, ensuring the payload is correctly identified.
*
* @returns Valid principal if authenticated
* @returns undefined if authentication is valid, but incomplete (multi-step)
* @throws AppError if authentication fails
*/
authenticate(payload: T, ctx?: 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
Like the AuthService, there are common auth patterns that most users will implement. The framework has codified these into decorators that a developer can pick up and use.
@Authenticate integrates with middleware that will authenticate the user as defined by the specified providers, or throw an error if authentication is unsuccessful.
Code: Using provider with routes
import { Controller, Get, Redirect, Request } from '@travetto/rest';
import { Authenticate, Authenticated, AuthService } from '@travetto/auth-rest';
import { FB_AUTH } from './facebook';
@Controller('/auth')
export class SampleAuth {
svc: AuthService;
@Get('/simple')
@Authenticate(FB_AUTH)
async simpleLogin() {
return new Redirect('/auth/self', 301);
}
@Get('/self')
@Authenticated()
async getSelf(req: Request) {
return req.auth;
}
@Get('/logout')
@Authenticated()
async logout(req: Request) {
await this.svc.logout(req);
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.