Introducing Socket Firewall: Free, Proactive Protection for Your Software Supply Chain.Learn More
Socket
Book a DemoInstallSign in
Socket

@travetto/auth-rest

Package Overview
Dependencies
Maintainers
1
Versions
345
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@travetto/auth-rest

Rest authentication integration support for the Travetto framework

latest
Source
npmnpm
Version
5.1.0
Version published
Weekly downloads
35
337.5%
Maintainers
1
Weekly downloads
 
Created
Source

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:

  • 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';

/**
 * Represents the general shape of additional login context, usually across multiple calls
 */
export interface AuthenticatorState extends AnyMap { }

/**
 * Supports validation payload of type T into an authenticated principal
 *
 * @concrete ../internal/types#AuthenticatorTarget
 */
export interface Authenticator<T = unknown, C = unknown, P extends Principal = Principal> {
  /**
   * Retrieve the authenticator state for the given request
   */
  getState?(context?: C): Promise<AuthenticatorState | undefined> | AuthenticatorState | undefined;

  /**
   * 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, 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;

Keywords

authentication

FAQs

Package last updated on 26 Jan 2025

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts