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

@curity/token-handler-js-assistant

v1.1.0

Published

Curity Token Handler JavaScript helper library

Downloads

18

Readme

token-handler-js-assistant

A helper library to help SPAs interact with the OAuth Agent in the Token Handler pattern.

Add to project

Add to your project using npm

npm install @curity/token-handler-js-assistant

How to use in your project

Import the Assistant into your project and initialize it using Configuration object.

import {OAuthAgentClient} from "@curity/token-handler-js-assistant";
const client = new OAuthAgentClient({oauthAgentBaseUrl: 'https://api.example.com/oauthagent/example'})

The Configuration object contains the following options:

  • oauthAgentBaseUrl - a URL with path to the token handler application created in the Curity Identity Server (this URL ends with a token handler application ID as defined in the Curity Identity Server configuration).

Using the initialized client

  1. Starting the user login
    const response = await this.oauthAgentClient.startLogin({
      extraAuthorizationParameters: {
        scope: "openid profile", 
        login_hint: "username",
        ui_locales: "en"
      }
    })
    location.href = response.authorizationUrl
  2. Finishing the user login
    const url = new URL(location.href)
    const response = await client.endLogin({ searchParams: url.searchParams })
    if (response.isLoggedIn) {
      // use id token claims to get username, e.g. response.idTokenClaims?.sub
    }

Note: The endLogin function should only be called with authorization response parameters (when the authorization server redirected user to the SPA after a successful user login). It's recommended to call onPageLoad() instead on every load of the SPA. This function makes a decision based the query string and either calls endLogin() or session().

  1. Handling page load

    const sessionResponse = await client.onPageLoad(location.href)
    if (sessionResponse.isLoggedIn) {
      // user is logged in
    } else {
      const response = await client.startLogin()
      // redirect the user to the authorization server
      location.href = response.authorizationUrl
    }
  2. Refreshing tokens

    await client.refresh()
  3. Retrieving ID token claims

    const sessionResponse = await client.session()
    // use session data
    if (session.isLoggedIn === true) {
      session.idTokenClaims?.sub
    }
  4. Logging out

    const logoutResponse = await client.logout()
    if (logoutResponse.logoutUrl) {
      // redirect user to the single logout url
      location.href = logoutResponse.logoutUrl;
    }
  5. Implementing preemptive refresh. session(), refresh(), endLogin() and onPageLoad() functions return accessTokenExpiresIn if the Authorization Server includes expires_in in token responses. This field contains number of seconds until an
    access token that is in the proxy cookie expires. This value can be used to preemptively refresh the access token. After calling onPageLoad() and refresh():

    // const response = await client.onPageLoad(location.href)
    // const response = await client.refresh()
    if (response.accessTokenExpiresIn != null) {
      const delay = Math.max(response.accessTokenExpiresIn - 2, 1)
      setTimeout(
        () => { client.refresh(); },
        delay * 1000
      );
    }

    Note: This is just a simplified example. The timeout has to be cleared properly (before every refresh, or before logout).

Cookie Security

  • SameSite=Strict cookies are sent to APIs, which cannot be sent from malicious sites
  • to ensure that only precise whitelisted origins can send cookies to APIs, a token-handler-version: 1 header is sent by this library on every request to the OAuth Agent. In cross-origin deployments this ensures that a CORS pre-flight request authorizes access. SPA developers may be required to send this header to token handler proxies as well (refer to the token handler proxy documentation for details).