npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@travetto/auth-rest

v4.0.7

Published

Rest authentication integration support for the Travetto framework

Downloads

321

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 TravettoRequest object. The auth functionality is exposed on the request as the property auth.

Code: Structure of auth property on the request

export interface TravettoRequest {
    /**
     * 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 TravettoRequest and TravettoResponse, 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 { AppError } from '@travetto/base';
import { 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 AppError('Invalid credentials', 'authentication');
    }
  }
}

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 TravettoRequest.auth.