0.3.13 ā€¢ Published 1 year ago

oauth2-server-redwood v0.3.13

Weekly downloads
-
License
MIT
Repository
github
Last release
1 year ago

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/

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

  • 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 šŸ§‘ā€šŸ’»

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.

0.3.13

1 year ago

0.3.12

1 year ago

0.3.11

1 year ago

0.3.10

1 year ago

0.3.0

1 year ago

0.2.0

1 year ago

0.3.6

1 year ago

0.3.8

1 year ago

0.3.2

1 year ago

0.3.1

1 year ago

0.3.4

1 year ago

0.2.1-alpha.0

1 year ago

0.1.2-alpha.1

1 year ago

0.3.3

1 year ago

0.1.2-alpha.0

1 year ago

0.1.1

1 year ago

0.1.0

1 year ago

0.0.3

1 year ago

0.0.2

1 year ago

0.0.1

1 year ago