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

web-oidc

v0.0.19

Published

An OpenID Connect client built using only Web APIs

Downloads

1,673

Readme

Web OIDC

An OpenID Connect client for web applications built completely using standard Web APIs.

Note: This package is a port of openid-client but only using standard Web APIs.

Warning: This package is still a work in progress and should not be used in production.

Installation

npm add web-oidc

Usage

You can use the Issuer.discover method to discover the OpenID Connect issuer configuration.

import { Issuer } from "web-oidc";

const issuer = await Issuer.discover("https://auth.company.tld");

The issuer value will be a Issuer instance where you can later call issuer.metadata to access the configuration of the issuer.

With the issuer ready, we can instantiate a Client.

import { Client } from "web-oidc";
let client = new Client(issuer, {
  client_id: "CLIENT_ID",
  client_secret: "CLIENT_SECRET",
  redirect_uri: "https://www.company.tld/auth/callback",
  response_type: "code id_token",
});

Additionally, we can create the client directly from the issuer.

import { Issuer } from "web-oidc";

const issuer = await Issuer.discover("https://auth.company.tld");

let client = issuer.client({
  client_id: "CLIENT_ID",
  client_secret: "CLIENT_SECRET",
  redirect_uri: "https://www.company.tld/auth/callback",
  response_type: "code id_token",
});

This will instantiate a client with the issuer's configuration.

With a Client instance, we can start handling the authentication flow.

// The `Generator.state()` method is a helper to generate a cryptographically
// secure random string
import { Generator } from "web-oidc";

let state = Generator.state(); // keep this in a cookie/session
let url = client.authorizationUrl({ state });

This will generate a URL that you can redirect the user to start the flow.

Once the user is back on your callback URL, you can use the Client#callbackParams and Client#oauthCallback methods to handle the request.

let params = await client.callbackParams(request);
let tokens = await client.oauthCallback(new URL(request.url), params, {
  state, // read this from where you stored it
  response_type: "code",
});

You can then use the Client#userinfo method to fetch the user's profile from the IdP.

let userinfo = await client.userinfo(tokens.access_token);

And if you're keeping the access and refresh tokens around, you can use the Client#refresh method to get a new access token when it expires.

let { accessToken, refreshToken, extraParams } = await client.refresh(
  tokens.refresh_token
);

Use with Remix Auth

If you're building a Remix application and using Remix Auth, this package exports a strategy you can use.

import { OIDCStrategy } from "web-oidc/remix";

authenticator.use(
  new OIDCStrategy(
    {
      issuer: "https://auth.company.tld",
      client_id: "CLIENT_ID",
      client_secret: "CLIENT_SECRET",
      redirect_uri: "https://www.company.tld/auth/callback",
      response_type: "code id_token",
    },
    async ({ profile, tokens }) => {
      return { profile, tokens };
    }
  )
);

The issuer can be a string or URL similar to Issuer.discover, it could also be a Issuer instance if you already have one.

You can then use this strategy in your routes.

export async function action({ request }: DataFunctionArgs) {
  return await authenticator.authenticate("oidc", request, {
    successRedirect: "/home",
    failureRedirect: "/login",
  });
}

If you plan to keep the tokens saved, you can save the strategy into a variable.

import { OIDCStrategy } from "web-oidc/remix";
import { Issuer } from "web-oidc";

let strategy = new OIDCStrategy<User>(
  {
    issuer: "https://auth.company.tld",
    client_id: "CLIENT_ID",
    client_secret: "CLIENT_SECRET",
    redirect_uri: "https://www.company.tld/auth/callback",
    response_type: "code id_token",
  },
  async ({ profile, tokens }) => {
    return { profile, tokens };
  }
);

authenticator.use(strategy);

Then, you can access the Issuer and Client instances with:

let issuer = await strategy.issuer;
let client = await strategy.client;

The return value of both is a promise because (unless you pass an Issuer instance to the strategy) the strategy needs to discover the issuer configuration dynamically first and this only happens the first time it's needed.

Use with Hono

If you're building a Hono application, this package exports a middleware you can use.

import { oidc } from "web-oidc/hono";

app = new Hono();

app.use(
  "*",
  oidc({
    issuer: "https://auth.company.tld",
    client_id: "CLIENT_ID",
    client_secret: "CLIENT_SECRET",
    redirect_uri: "https://www.company.tld/auth/callback",
    response_type: "code id_token",
    routes: {
      // You can customize the routes used to handle the login flow
      // These values are the default ones
      login: "/auth",
      callback: "/auth/callback",
    },
  })
);

// After a success login, this handler will be called, here you can redirect the
// user somewhere else
app.get("/auth/callback", (ctx) => {
  return ctx.redirect("/profile");
});

app.get("/", async (ctx) => {
  // Check if the user is authenticated
  let isAuthenticated = oidc.isAuthenticated(ctx);
  if (isAuthenticated) return ctx.redirect("/profile");
  return ctx.html("<h1>Hello Hono</h1>");
});

// Require authentication for this route, by default it will redirect to routes.login
app.get(
  "/profile",
  oidc.authenticate({ failureRedirect: "/" }),
  async (ctx) => {
    // Get the user info
    let user = await oidc.user(ctx);
    return ctx.html(`<h1>Hello ${user.name}</h1>`);
  }
);

You can also access the Issuer and Client instances with:

app.get("/route", async (ctx) => {
  let issuer = oidc.issuer(ctx);
  let client = oidc.client(ctx);
  // do something with them
});

Author