Git Product home page Git Product logo

auth0-solid-start's Introduction

Auth0 Solid Start (SSR compatible)

Publish

This is a fully functional library to add Auth0 OAuth Authentication to a Solid-Start App.

You'll need to sign up and create an Auth0 Application to use this library. The credentials are stored in an .env file (see .env.example).

This work is inspired by

How it works

This library is intended to be used on root level of your Solid-Start App. It provides an authentication context for the entire App. Users/passwords etc. are all stored in Auth0, we use the Universal Login Experience to authenticate users and get a code, which we can exchange for an access_token. The access_token is a valid JWT token and can be used to authenticate requests to your API / GraphQL /etc.

The callback URL is set to /auth/callback, so you need to create an API route in src/routes/auth/callback.js/ts. The code can be found below.

flowchart
    A[Browser] --> B[Initial Render/SSR]
    B{Valid Session Cookie exists?} --> |Yes| C
    C[Set Signals & Render App]
    B --> |No| D[Redirect to Auth0 Universal Login]
    D --> E[Callback to `/auth/callback` with `code` & `state`]
    E --> F[Exchange `code` for `access_token`]
    F --> G[Get User Info with access_token]
    G --> H[Set Signals & Session Cookie]
    H --> C[Render App]

Loading

Multi Tenant Mode

Multi Tenant Mode can be used with Auth0 Organizations. You'll have to pass an organization object into the Auth0 context with an id. We recommend using the same schema as Auth0.

Set VITE_AUTH0_REWRITE_REDIRECT=true in .env

Usage

Environment Variables

See .env.example

  • VITE_AUTH0_REWRITE_REDIRECT requires the Auth0 Organization setup
  • VITE_AUTH0_OFFLINE_ACCESS requires the Auth0 API to be configured with offline access
  • VITE_AUTH0_LOGOUT_URL the logout url (a server-side route, ie http://localhost:8080/auth/logout)

vite.config.ts/js

There's an issue with vite throwing process is undefined errors when the session is loaded on the client. To fix this, add the following to your vite.config.ts/js:

define: {
    'process.env': process.env
  },

root.jsx / .tsx

In root.tsx to enforce authentication on all pages:

import { Show, Suspense } from 'solid-js'
import { isServer } from 'solid-js/web'
import { ErrorBoundary, FileRoutes, Routes } from 'solid-start'
import { Auth0, useAuth0 } from '@zentered/auth0-solid-start'

const GraphQLProvider = () => {} // let's assume you want to authenticate graphql requests with your JWT

function Login(props) {
  return (
    <div>
      <p>Sign in</p>
      <div>
        <div>
          <a onClick={() => props.auth0.authorize()} type="button">
            Log In
          </a>
        </div>
      </div>
    </div>
  )
}

function SiteRequiresAuth(props) {
  const auth0 = useAuth0()

  if (!auth0.isAuthenticated() && !isServer) {
    auth0.login()
  }

  return (
    <>
      <Show when={auth0.isInitialized()}>
        <Show when={auth0.isAuthenticated()} fallback={<Login auth0={auth0} />}>
          <Show when={auth0.accessToken()}>
            <GraphQLProvider auth0={auth0}>{props.children}</GraphQLProvider>
          </Show>
        </Show>
      </Show>
    </>
  )
}

export default function Root() {
  return (
    // ...
    <Suspense>
      <ErrorBoundary>
        <Auth0
          domain={import.meta.env.VITE_AUTH0_DOMAIN}
          clientId={import.meta.env.VITE_AUTH0_CLIENT_ID}
          audience={import.meta.env.VITE_AUTH0_AUDIENCE}
          redirectUri={import.meta.env.VITE_AUTH0_REDIRECT_URI}
          logoutUrl={`${import.meta.env.VITE_BASE_URL}/auth/logout`}
          // organization={organization} // uncomment if you use auth0 organizations
        >
          <SiteRequiresAuth>
            <Routes>
              <FileRoutes />
            </Routes>
          </SiteRequiresAuth>
        </Auth0>
      </ErrorBoundary>
    </Suspense>
    // ...
  )
}

With Organization Invitation

If you use Auth0 Organizations, you can pass through the invitation, organization and organization_name query params to the Auth0 Universal Login Experience. This will load the sign-up instead of the login form:

// root.jsx/tsx
const [searchParams] = useSearchParams()

if (searchParams.invitation) {
  auth0.setInvitation(
    searchParams.invitation,
    searchParams.organization,
    searchParams.organization_name
  )
}

Logout

The logout happens in 3 steps:

  1. User clicks "Sign out" and starts the process
  2. logout function on the Auth0 Provider is triggered that generates an auth0 logout url
  3. Auth0 redirects back to the "logout url" which clears the session.

There are two parts: the logout function in the auth0 provider and the "api" route (ie /auth/logout), see below.

In any component/page where you want the "Sign out" link:

import { useAuth0 } from '@zentered/auth0-solid-start'
import { Link } from '@solidjs/router'

export default function Component() {
  const auth0 = useAuth0()
  const [, logout] = createRouteAction(async () => {
    await auth0.logout()
  })

  <Link
    href="#"
    class={`button`}
    onClick={() => logout()}
  >
    Sign Out
  </Link>
}

API

Callback

routes/auth/callback.js|ts:

import fn from '@zentered/auth0-solid-start/api/callback'

export async function GET({ request }) {
  return fn(request)
}

Logout API

routes/auth/logout.js|ts:

import fn from '@zentered/auth0-solid-start/api/logout'

export function GET({ request }) {
  return fn(request)
}

Development

You can fork/clone this repository and link it into your working project with pnpm link:

cd auth0-solid-start
pnpm link

cd ../your-project
pnpm link @zentered/auth0-solid-start ../../auth0-solid-start

Instead of using the npm version you're now working with a local copy. Changes in the auth0-solid-start folder should restart the app.

auth0-solid-start's People

Contributors

birkskyum avatar dependabot[bot] avatar jan-san avatar mariosimou avatar patrickheneise avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

auth0-solid-start's Issues

The automated release is failing 🚨

🚨 The automated release from the main branch failed. 🚨

I recommend you give this issue a high priority, so other packages depending on you can benefit from your bug fixes and new features again.

You can find below the list of errors reported by semantic-release. Each one of them has to be resolved in order to automatically publish your package. I’m sure you can fix this 💪.

Errors are usually caused by a misconfiguration or an authentication problem. With each error reported below you will find explanation and guidance to help you to resolve it.

Once all the errors are resolved, semantic-release will release your package the next time you push a commit to the main branch. You can also manually restart the failed CI job that runs semantic-release.

If you are not sure how to resolve this, here are some links that can help you:

If those don’t help, or if this issue is reporting something you think isn’t right, you can always ask the humans behind semantic-release.


No npm token specified.

An npm token must be created and set in the NPM_TOKEN environment variable on your CI environment.

Please make sure to create an npm token and to set it in the NPM_TOKEN environment variable on your CI environment. The token must allow to publish to the registry https://registry.npmjs.org/.


Good luck with your project ✨

Your semantic-release bot 📦🚀

Redirect to Login

When the access token expires, we should automatically redirect to a Login page.

Typescript Compatibility

I would love to see some compatibility with Typescript in this package. Some of it would just be adding packages like "@types/auth0-js" to the package.

Add Logout

I am trying to use this package in my development, but there are several parts of this that aren't documented here how they are meant to be used. Some of them are very important, such as how do you setup the user logging out? Anyway, some better documentation, or an example would be helpful and appreciated.
Thank you.

Refresh Token

we should be able to fetch new access tokens with refresh tokens from Auth0.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.