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

oauth2-server-redwood

v0.3.13

Published

<h1 align="left">Welcome to Oauth2 Server Redwood πŸ‘‹</h1> <p align="left"> <a href="#" target="_blank"> <img alt="License: MIT" src="https://img.shields.io/badge/License-MIT-blue.svg" /> </a> </p>

Downloads

29

Readme

OAuth2 server with dynamic client registration and test API, built with OIDC-Provider for RedwoodJS

🚧 IN DEVELOPMENT 🚧

"Authority" means that you are providing authentication or authorization as a service for other apps. For example "Sign in with MyCompanyApp", as opposed to "Sign in with Google". If you're just looking to implement an OAuth2 client in your app, check out oauth2-client-redwood.

Demo ⏯️

Point your oauth2-client-redwood or passport.js app to the demo server:

https://oauth2-server-redwood.vercel.app/

Here is the available client config. Let me know if you want to add your own client to the demo server, or make a PR.

client_id: '123',
redirect_uris: [
            'https://jwt.io',
            'https://oauthdebugger.com/debug',
            'http://0.0.0.0:8910/redirect/oauth2_server_redwood',
            'https://oauth2-client-redwood-eta.vercel.app/redirect/node_oidc',
          ],

Usage

To add the OAuth2 server to your own app:

  1. Install the package and generate the jwks file needed to secure your server
yarn add oauth2-server-redwood serverless-http

# Generate jwks.js
npx oauth2-server-redwood

Place the output in api/src/lib/jwks.js. WARNING: consider using environment variables (example) or using encrypted environment variables before adding jwks to to git. Anyone with these keys will have full access to your app's API.

  1. Create a new api function oauth and add the following code:
yarn rw g function oauth
// api/src/functions/oauth.js
import oauth2Server from 'oauth2-server-redwood'
import serverless from 'serverless-http'

import jwks from 'src/lib/jwks'

import { db } from 'src/lib/db'

export const handler = serverless(
  oauth2Server(db, {
    SECURE_KEY: process.env.SECURE_KEY,
    ISSUER_URL: process.env.APP_DOMAIN,
    REDWOOD_API_URL: process.env.REDWOOD_API_URL ||
       `${process.env.APP_DOMAIN}/.redwood/functions`,
    INTROSPECTION_SECRET: process.env.INTROSPECTION_SECRET,
    jwks,
    // middlewares, // Optional, see src/functions/oauth/middlewares
    routes: { login: '/login', authorize: '/authorize' },
    config: {
      // Define your own OIDC-Provider config (https://github.com/panva/node-oidc-provider)
      clients: [
        {
          client_id: '123',
          redirect_uris: [
            'https://jwt.io',
            'https://oauthdebugger.com/debug',
            'http://0.0.0.0:8910/redirect/oauth2_server_redwood',
          ],
        },
      ],
    },
  })
)
  1. Copy the .env.example to .env and update the values

  2. Setup a local Nginx proxy. I've included oauth2-server-redwood.conf which removes the prefix and serves the endpoint from localhost/oauth instead of localhost/api/oauth.

HELP WANTED: Oidc-provider does not always adhere to the /api path prefix when setting cookie path (or maybe my implementation is incorrect). If you you can help remove the need for nginx, or improve this setup, please let me know!

If you need https locally, this is a good resource: https://www.howtogeek.com/devops/how-to-create-and-use-self-signed-ssl-on-nginx/, paired with setting NODE_TLS_REJECT_UNAUTHORIZED=0 in your .env file.

  1. Setup dbAuth and update the graphql schema. Copy the schema here or see oauth2-client-redwood.
yarn rw setup auth dbAuth
  1. Update how redirection works to properly send the user back to client app that initiated the OAuth2 request.
  • Copy the providers from web/providers "redirection" and "oAuthAuthority" to web/src/providers. Then update web/src/providers/index.js as shown:
import { OAuthAuthorityProvider} from "./oAuthAuthority"
import { RedirectionProvider } from './redirection'

const AllContextProviders = ({ children }) => {
  return (
    <>
      <OAuthProvider>
        <OAuthAuthorityProvider>
          <RedirectionProvider>{children}</RedirectionProvider>
        </OAuthAuthorityProvider>
      </OAuthProvider>
    </>
  )
  • Update oauth library api/src/lib/oauth with stateExtraData
export const oAuthUrl = async ( type, stateExtraData ) => {
  try {
    //...
    const state = uuidv4() + (stateExtraData ? `:${stateExtraData}` : '')
  • Update auth function api/src/functions.auth.js with stateExtraData
authHandler.signup = async () => {
    try {
      const { type, stateExtraData } = authHandler.params
      //...
      const { url } = await oAuthUrl(type, stateExtraData)
  • Add AuthorizePage.js to your web/src/pages folder, which allows the user to provide their consent.
  1. (Optional) Enable dynamic client registration
  • Copy the api/src/services/clients.js to your app
  • Copy ProfilePage.js and related components to your app to utilizie the client services

Test

To test the Oauth2 server, you can use https://oauthdebugger.com/

  • Authorize URI: http://localhost/oauth/auth
  • Client ID: 123
  • Scope: openid email profile
  • Use PKCE: true

Alternatively, you can test using a Redwood-only stack. Clone oauth2-client-redwood and update .env to point to your server:

OAUTH2_SERVER_REDWOOD_API_DOMAIN=http://localhost/oauth

Next, simulate an API request using the user's access token, create a request to http://localhost/api/v1/sanity-check using the access token from the client (eg. oauthdebugger or oauth2-client-redwood)

Config

To enable refresh tokens, add grant_type 'refresh_token' to the client.

NOTE: You should only enable refresh tokens for confidential clients. To do this, set token_endpoint_auth_method to client_secret_post

tokenEndpointAuthMethods: ['client_secret_post'],
clientDefaults: {
  grant_types: ['authorization_code', 'refresh_token'],
  token_endpoint_auth_method: 'client_secret_post',
  //...
},
scopes: ['openid', 'offline_access'],

Contributing πŸ’‘

To run this repo locally:

  • Clone the repo and follow steps 3 & 4 above to setup the .env and nginx proxy
  • Run yarn build:watch in /packages/oauth2-server
  • Run yarn rw dev to start the app

TODO

  • [x] Validate rw session tokens during login
  • [ ] Upgrade to latest oidc-provider (blocked by lack of support for "require")
  • [ ] Add dbAuth username/password option to make the demo simpler to understand
  • [ ] Show proper scopes for consent page
  • [ ] Improve the UI

Resources πŸ§‘β€πŸ’»

  • OAuth Server libraries: https://oauth.net/code/nodejs/
  • Similar tools https://github.com/panva/oauth4webapi/blob/main/examples/code.ts and https://github.com/panva/node-openid-client

Sponsors ❀️

Improve onboarding and payments in your games & web3 apps effortlessly with OAuth logins for wallets and debit card transactions. Create a Keyp account; it's free!

License πŸ“

Copyright Β© 2023 Nifty Chess, Inc. This project is MIT licensed.