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

jwt-psk

v1.0.2

Published

A simple library to allow authentication between services, using jwt signed with pre-shared keys

Downloads

760

Readme

Pre-shared JWT key authentication

A simple library that allows authentication by JWT signed with pre-shared key.

Synopsis

Library is intended to be used in an environment where several services are sending requests to one another. This requests are performed by services themselves or on behalf of some other entity.

Each service that make requests is assumed to be identified by name and to have an unique secret key. Each endpoint requests are send to is assumed to also have some name.

This library is used to issue and verify Json Web Tokens to authenticate services.

Token issuer specifies claims to identify itself, endpoint this token is intended for, and, optionally, subject the token is issued on behalf of. Standard JWT claims iss, aud and sub are used for that purpose. Payload is then signed by issuer's secret key.

To verify the token, endpoint finds a pre-shared key for the issuer specified in an iss claim, and checks the signature. aud claim is checked to match the endpoint name. Request is then processed as if it was made by entity specified in sub claim or in iss claim, if no sub is present.

Pre-shared keys are stored per issuer and algorithm, allowing issuer to sign tokens using different keys and algorithms

Usage

Library provides general purpose classes for usage with any applications and specific classes to use with Nest.js framework

General purpose classes

Following snippet shows how to use this library as express middleware framework to verify authentication tokens

import { AuthServiceBase, readToken } from "jwt-psk";
import express from "express";

const audience = [ "this.server.name", "alt.server.name" ];
const authConfig = {
  "doge-the-jwt-issuer": {
     "HS256": "WOW!such_Secret"
  }
};
const app = express();
const authService = new AuthServiceBase(authConfig, audience);

app.use((req, res, next) => {
  try { 
    authService.authenticate(readToken(req.headers.authorization));
  } catch (e) {
    res.return(403);
    return;
  }
  next();
});

To issue token, compatible with that server code:

import { createPSKToken } from "jwt-psk";

fetch("https://example.com/service", {
  headers: {
    "Authorization": `Bearer ${createPSKToken("doge-the-jwt-issuer", "WOW!such_Secret", "example.com")}`
  }
}).then(resp => processResponse(resp));

Nest server

Library provides middleware to assert that incoming request has proper auth header with JWT token signed by the key that belongs to on of known issuers, and audience claim matches one that is required by this server.

The following snippet shows configuration with static values.

import { MiddlewareConsumer, Module, NestModule } from "@nestjs/common";
import { AuthModule, PSKAuthMiddleware } from "jwt-psk/nest";

@Module({
  import: [
    AuthModule.configure({
      audience: [ "this.server.name", "alt.server.name" ],
      authConfig: {
        "doge-the-jwt-issuer": {
           "HS256": "WOW!such_Secret"
        }
      }
    })
  ]
})
export class AppModule implements NestModule  {
  configure(consumer: MiddlewareConsumer): void {
    consumer
      .apply(PSKAuthMiddleware)
      .forRoutes("*");
  }
}

The following snippet shows configuration with values obtained from configuration

import { MiddlewareConsumer, Module, NestModule } from "@nestjs/common";
import { AuthModule, PSKAuthMiddleware } from "jwt-psk/nest";
import { ConfigModule, ConfigService } from "./config";

@Module({
  import: [
    AuthModule.configureAsync({
      imports: [ConfigModule],
      inject: [ConfigService],
      useFactory: (config: ConfigService) => ({
        audience: config.serviceGlobalAudience,
        authConfig: config.preSharedKeys
      })
    })
  ]
})
export class AppModule implements NestModule  {
  configure(consumer: MiddlewareConsumer): void {
    consumer
      .apply(PSKAuthMiddleware)
      .forRoutes("*");
  }
}