supabase / supabase-js

An isomorphic Javascript client for Supabase. Query your Supabase database, subscribe to realtime events, upload and download files, browse typescript examples, invoke postgres functions via rpc, invoke supabase edge functions, query pgvector.
https://supabase.com
MIT License
2.83k stars 219 forks source link

Nextjs14 with Supabase Auth - AuthApiError: invalid claim: missing sub claim #992

Open pdomala opened 1 month ago

pdomala commented 1 month ago

Bug report

Describe the bug

I am trying to setup Supabase authentication using Google Oauth provider. I am following the instructions details in the below link https://supabase.com/docs/guides/auth/server-side/nextjs

I created a login page with a button which calls supabase.auth.signInWithOAuth({ provider: 'google' }. I see the use being created in Supabase. But when I try to get the session using below code. I get the session as null and the console throws this error AuthApiError: invalid claim: missing sub claim

const supabase = createClient();
const { data: session, error } = await supabase.auth.getSession();
console.log(session);
console.log(error);
AuthApiError: invalid claim: missing sub claim
    at handleError (webpack-internal:///(rsc)/./node_modules/@supabase/gotrue-js/dist/module/lib/fetch.js:52:11)
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
    at async _handleRequest (webpack-internal:///(rsc)/./node_modules/@supabase/gotrue-js/dist/module/lib/fetch.js:89:9)
    at async _request (webpack-internal:///(rsc)/./node_modules/@supabase/gotrue-js/dist/module/lib/fetch.js:74:18)
    at async eval (webpack-internal:///(rsc)/./node_modules/@supabase/gotrue-js/dist/module/GoTrueClient.js:831:24)
    at async SupabaseAuthClient._useSession (webpack-internal:///(rsc)/./node_modules/@supabase/gotrue-js/dist/module/GoTrueClient.js:754:20)
    at async SupabaseAuthClient._getUser (webpack-internal:///(rsc)/./node_modules/@supabase/gotrue-js/dist/module/GoTrueClient.js:825:20)
    at async eval (webpack-internal:///(rsc)/./node_modules/@supabase/gotrue-js/dist/module/GoTrueClient.js:813:20)
    at async eval (webpack-internal:///(rsc)/./node_modules/@supabase/gotrue-js/dist/module/GoTrueClient.js:699:28) {
  __isAuthError: true,
  status: 401

To Reproduce

System information

pdomala commented 1 month ago

Adding my sample repo with Supabase where the error can be re-produced. https://github.com/pdomala/nextjs14-supabase-sample

nicolazj commented 1 month ago

I've got the same issue with linkedin provider. my code worked for a while , then stopped working..

nicolazj commented 1 month ago

@pdomala ok i figured out, you have to have a auth/callback/route to handle the code thingy

await supabase.auth.exchangeCodeForSession(code);

bigdenergy commented 1 month ago

@pdomala ok i figured out, you have to have a auth/callback/route to handle the code thingy

await supabase.auth.exchangeCodeForSession(code);

Can u send me sample code of your auth/callback/route.ts ?

Thank you!

rookledookle commented 3 weeks ago

Struggling with this too followed the docs to no avail

joris-delorme commented 2 weeks ago

I got the same issue...

ItaiAxelrad commented 2 weeks ago

Having the same issue. I set up everything according to the docs. The user is signed in successfully upon first sign up but once they log out they are unable to log back in. The error code is 403: invalid claim: missing sub claim.

aleskozelsky commented 2 weeks ago

Same here

Daniel-Alamezie commented 2 weeks ago

Authentication seems to be broken atm. My linkedIn auth provider was broken yesterday, a fix was put out for that this morning. But google Auth provider is broken too. getting this error data: { user: null }, error: AuthApiError: invalid claim: missing sub claim at handleError (webpack-internal:///(rsc)/./node_modules/@supabase/auth-js/dist/module/lib/fetch.js:62:11) at process.processTicksAndRejections (node:internal/process/task_queues:95:5) at async _handleRequest (webpack-internal:///(rsc)/./node_modules/@supabase/auth-js/dist/module/lib/fetch.js:116:9) at async _request (webpack-internal:///(rsc)/./node_modules/@supabase/auth-js/dist/module/lib/fetch.js:92:18) at async eval (webpack-internal:///(rsc)/./node_modules/@supabase/auth-js/dist/module/GoTrueClient.js:1064:24) at async SupabaseAuthClient._useSession (webpack-internal:///(rsc)/./node_modules/@supabase/auth-js/dist/module/GoTrueClient.js:949:20) at async SupabaseAuthClient._getUser (webpack-internal:///(rsc)/./node_modules/@supabase/auth-js/dist/module/GoTrueClient.js:1058:20) at async eval (webpack-internal:///(rsc)/./node_modules/@supabase/auth-js/dist/module/GoTrueClient.js:1041:20) at async eval (webpack-internal:///(rsc)/./node_modules/@supabase/auth-js/dist/module/GoTrueClient.js:897:28) { __isAuthError: true, status: 403, code: 'bad_jwt'

my callback route looks like this ` import { cookies } from 'next/headers' import { NextResponse } from 'next/server' import { type CookieOptions, createServerClient } from '@supabase/ssr'

export async function GET(request: Request) { const { searchParams, origin } = new URL(request.url) const code = searchParams.get('code') // if "next" is in param, use it as the redirect URL const next = searchParams.get('next') ?? '/' console.log('code:', code)

if (code) { const cookieStore = cookies() const supabase = createServerClient( process.env.NEXT_PUBLIC_SUPABASE_URL!, process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!, { cookies: { get(name: string) { return cookieStore.get(name)?.value }, set(name: string, value: string, options: CookieOptions) { cookieStore.set({ name, value, ...options }) }, remove(name: string, options: CookieOptions) { cookieStore.delete({ name, ...options }) }, }, } ) const { error } = await supabase.auth.exchangeCodeForSession(code) if (!error) { return NextResponse.redirect(${origin}/dashboard) } console.log(error); }

// return the user to an error page with instructions return NextResponse.redirect(${origin}/auth/auth-code-error) } async function signInWithGoogle() { const supabase = supabaseBrowser(); const { error } = await supabase.auth.signInWithOAuth({ provider: 'google', options: { queryParams: { access_type: 'offline', prompt: 'consent', }, redirectTo: ${window.location.origin}/auth/callback, } }); if (error) { console.error('Error signing in:', error); } } ` It sucessfully creates the user, but and logs in but when i try to fetch userId or session i run into the prescribed error

rookledookle commented 2 weeks ago

Kinda worried about using this in production now ..

On Tue, 16 Apr 2024, 2:02 am Daniel, @.***> wrote:

Authentication seems to be broken atm. My linkedIn auth provider was broken yesterday, a fix was put out for that this morning. But google Auth provider is broken too. getting this error data: { user: null }, error: AuthApiError: invalid claim: missing sub claim at handleError @./auth-js/dist/module/lib/fetch.js:62:11) at process.processTicksAndRejections (node:internal/process/task_queues:95:5) at async _handleRequest @./auth-js/dist/module/lib/fetch.js:116:9) at async _request @./auth-js/dist/module/lib/fetch.js:92:18) at async eval @./auth-js/dist/module/GoTrueClient.js:1064:24) at async SupabaseAuthClient._useSession @./auth-js/dist/module/GoTrueClient.js:949:20) at async SupabaseAuthClient._getUser @./auth-js/dist/module/GoTrueClient.js:1058:20) at async eval @./auth-js/dist/module/GoTrueClient.js:1041:20) at async eval @./auth-js/dist/module/GoTrueClient.js:897:28) { __isAuthError: true, status: 403, code: 'bad_jwt'

my callback route looks like this ` import { cookies } from 'next/headers' import { NextResponse } from 'next/server' import { type CookieOptions, createServerClient } from @.***/ssr'

export async function GET(request: Request) { const { searchParams, origin } = new URL(request.url) const code = searchParams.get('code') // if "next" is in param, use it as the redirect URL const next = searchParams.get('next') ?? '/' console.log('code:', code)

if (code) { const cookieStore = cookies() const supabase = createServerClient( process.env.NEXT_PUBLIC_SUPABASE_URL!, process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!, { cookies: { get(name: string) { return cookieStore.get(name)?.value }, set(name: string, value: string, options: CookieOptions) { cookieStore.set({ name, value, ...options }) }, remove(name: string, options: CookieOptions) { cookieStore.delete({ name, ...options }) }, }, } ) const { error } = await supabase.auth.exchangeCodeForSession(code) if (!error) { return NextResponse.redirect(${origin}/dashboard) } console.log(error); }

// return the user to an error page with instructions return NextResponse.redirect(${origin}/auth/auth-code-error) } async function signInWithGoogle() { const supabase = supabaseBrowser(); const { error } = await supabase.auth.signInWithOAuth({ provider: 'google', options: { queryParams: { access_type: 'offline', prompt: 'consent', }, redirectTo: ${window.location.origin}/auth/callback, } }); if (error) { console.error('Error signing in:', error); } } ` It sucessfully creates the user, but and logs in but when i try to fetch userId or session i run into the prescribed error

— Reply to this email directly, view it on GitHub https://github.com/supabase/supabase-js/issues/992#issuecomment-2057507689, or unsubscribe https://github.com/notifications/unsubscribe-auth/ACFZKU3K5VCTPYTMUA6D6P3Y5QI33AVCNFSM6AAAAABFG25D7CVHI2DSMVQWIX3LMV43OSLTON2WKQ3PNVWWK3TUHMZDANJXGUYDONRYHE . You are receiving this because you are subscribed to this thread.Message ID: @.***>

Daniel-Alamezie commented 2 weeks ago

Yeah, its slowing down my development process. The linkedIn one wasnt supabase's fault tbf, LinkedIn had release a breaking change without communicating it and that causes linkedIn auth to be broken. But the fix for that was merged this morning so it might take a while before that gets rolled out. But then my Google auth had also been broken.

rookledookle commented 2 weeks ago

After 3 days of non-stop debugging I found this: https://github.com/ElectricCodeGuy/SupabaseAuthWithSSR which was a god send I refactored all the code based off this and mixed in some code from the official docs and it seems to be working now, some tips I've gathered along the way, and what I did

other things I did along the way which I'm not sure contributed to me getting it working but adding here for completeness

here's my code for reference:

auth/callback/route.ts

import { createSupabaseServerClient } from "util/supabase/server";
import { NextResponse } from "next/server";

export async function GET(request: Request) {
  const { searchParams, origin } = new URL(request.url);

  const code = searchParams.get("code");

  // if "next" is in param, use it in the redirect URL
  const next = searchParams.get("next") ?? "/";

  if (code) {
    const supabase = createSupabaseServerClient();

    const { error } = await supabase.auth.exchangeCodeForSession(code);

    if (!error) {
      return NextResponse.redirect(`${origin}${next}`);
    }
  }

  // TODO: Create this page
  // return the user to an error page with instructions
  return NextResponse.redirect(`${origin}/auth/auth-error`);
}

middleware.ts

import { NextResponse, type NextRequest } from "next/server";
import { createSupabaseReqResClient } from "./util/supabase/server";

export async function middleware(request: NextRequest) {
  let response = NextResponse.next({
    request: {
      headers: request.headers,
    },
  });

  const supabase = createSupabaseReqResClient(request, response);

  const {
    data: { user },
  } = await supabase.auth.getUser();

  // protects the "/account" route and its sub-routes
  // redirect user to homepage
  if (!user && request.nextUrl.pathname.startsWith("/account")) {
    return NextResponse.redirect(new URL("/", request.url));
  }

  // protects the "/purchase" route and its sub-routes
  // redirect user to sign-in
  if (!user && request.nextUrl.pathname.startsWith("/purchase")) {
    return NextResponse.redirect(new URL("/", "sign-in"));
  }

  return response;
}

export const config = {
  matcher: [
    /*
     * Match all request paths except for the ones starting with:
     * - _next/static (static files)
     * - _next/image (image optimization files)
     * - favicon.ico (favicon file)
     * Feel free to modify this pattern to include more paths.
     */
    "/((?!_next/static|_next/image|favicon.ico|.*\\.(?:svg|png|jpg|jpeg|gif|webp)$).*)",
  ],
};

util/supabase/server.ts

import { type NextRequest, type NextResponse } from "next/server";
import { cookies } from "next/headers";
import { getCookie, setCookie } from "cookies-next";
import { createServerClient, type CookieOptions } from "@supabase/ssr";

// server component can only get cookies and not set them, hence the "component" check
export function createSupabaseServerClient(component: boolean = false) {
  return createServerClient(
    process.env.NEXT_PUBLIC_SUPABASE_URL!,
    process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!,
    {
      cookies: {
        get(name: string) {
          return cookies().get(name)?.value;
        },
        set(name: string, value: string, options: CookieOptions) {
          if (component) return;
          cookies().set(name, value, options);
        },
        remove(name: string, options: CookieOptions) {
          if (component) return;
          cookies().set(name, "", options);
        },
      },
    }
  );
}

export function createSupabaseServerComponentClient() {
  return createSupabaseServerClient(true);
}

export function createSupabaseReqResClient(
  req: NextRequest,
  res: NextResponse
) {
  return createServerClient(
    process.env.NEXT_PUBLIC_SUPABASE_URL!,
    process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!,
    {
      cookies: {
        get(name: string) {
          return getCookie(name, { req, res });
        },
        set(name: string, value: string, options: CookieOptions) {
          setCookie(name, value, { req, res, ...options });
        },
        remove(name: string, options: CookieOptions) {
          setCookie(name, "", { req, res, ...options });
        },
      },
    }
  );
}

util/supabase/client.ts

import { createBrowserClient } from "@supabase/ssr";

export function createSupabaseBrowserClient() {
  return createBrowserClient(
    process.env.NEXT_PUBLIC_SUPABASE_URL!,
    process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!
  );
}

Google auth button component

"use client";

import React, { useState } from "react";
import Button from "components/Buttons/Button";
import LoadingIcon from "components/Loading/LoadingIcon";
import { useSearchParams } from "next/navigation";

import { createSupabaseBrowserClient } from "util/supabase/client";

function AuthGoogle(props) {
  const [pending, setPending] = useState(null);
  const searchParams = useSearchParams();
  const next = searchParams.get("next") ?? "/";
  const supabase = createSupabaseBrowserClient();

  const onSigninWithGoogle = async () => {
    await supabase.auth.signInWithOAuth({
      provider: "google",
      options: {
        redirectTo: `${location.origin}/auth/callback?next=${next}`,
      },
    });
  };

  return (
    <div className="flex flex-col justify-items-center">
      <Button
        variant="primary"
        size="lg"
        disabled={pending === provider}
        onClick={() => {
          onSigninWithGoogle();
        }}
        startIcon={
          pending !== provider && (
            <img
              src="https://uploads.divjoy.com/icon-google.svg"
              alt="Google"
              className="w-5 h-5"
            />
          )
        }>
        {pending === provider && <LoadingIcon className="w-6" />}

        {pending !== provider && <>Continue with Google</>}
      </Button>
    </div>
  );
}

export default AuthGoogle;

May also be worth noting that when I created a SB client for my service_role key, I did it this way

import { createClient } from "@supabase/supabase-js"; // Note: this does not use @supabase/ssr unlike functions in /util/supabase

const supabase = createClient(
  process.env.SUPABASE_URL,
  process.env.SUPABASE_SERVICE_ROLE_SECRET, // Note: this should never be exposed to the client!
  {
    auth: {
      // these options are outlined in the docs: https://supabase.com/docs/reference/javascript/admin-api
      autoRefreshToken: false,
      persistSession: false,
    },
    db: { schema: "public" },
  }
);

not using the @supabase/ssr package

P.S. Am just a junior dev so apologies in advance if any of this isn't sound advice

rookledookle commented 2 weeks ago

Authentication seems to be broken atm. My linkedIn auth provider was broken yesterday, a fix was put out for that this morning. But google Auth provider is broken too. getting this error data: { user: null }, error: AuthApiError: invalid claim: missing sub claim at handleError (webpack-internal:///(rsc)/./node_modules/@supabase/auth-js/dist/module/lib/fetch.js:62:11) at process.processTicksAndRejections (node:internal/process/task_queues:95:5) at async _handleRequest (webpack-internal:///(rsc)/./node_modules/@supabase/auth-js/dist/module/lib/fetch.js:116:9) at async _request (webpack-internal:///(rsc)/./node_modules/@supabase/auth-js/dist/module/lib/fetch.js:92:18) at async eval (webpack-internal:///(rsc)/./node_modules/@supabase/auth-js/dist/module/GoTrueClient.js:1064:24) at async SupabaseAuthClient._useSession (webpack-internal:///(rsc)/./node_modules/@supabase/auth-js/dist/module/GoTrueClient.js:949:20) at async SupabaseAuthClient._getUser (webpack-internal:///(rsc)/./node_modules/@supabase/auth-js/dist/module/GoTrueClient.js:1058:20) at async eval (webpack-internal:///(rsc)/./node_modules/@supabase/auth-js/dist/module/GoTrueClient.js:1041:20) at async eval (webpack-internal:///(rsc)/./node_modules/@supabase/auth-js/dist/module/GoTrueClient.js:897:28) { __isAuthError: true, status: 403, code: 'bad_jwt'

my callback route looks like this ` import { cookies } from 'next/headers' import { NextResponse } from 'next/server' import { type CookieOptions, createServerClient } from '@supabase/ssr'

export async function GET(request: Request) { const { searchParams, origin } = new URL(request.url) const code = searchParams.get('code') // if "next" is in param, use it as the redirect URL const next = searchParams.get('next') ?? '/' console.log('code:', code)

if (code) { const cookieStore = cookies() const supabase = createServerClient( process.env.NEXT_PUBLIC_SUPABASE_URL!, process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!, { cookies: { get(name: string) { return cookieStore.get(name)?.value }, set(name: string, value: string, options: CookieOptions) { cookieStore.set({ name, value, ...options }) }, remove(name: string, options: CookieOptions) { cookieStore.delete({ name, ...options }) }, }, } ) const { error } = await supabase.auth.exchangeCodeForSession(code) if (!error) { return NextResponse.redirect(${origin}/dashboard) } console.log(error); }

// return the user to an error page with instructions return NextResponse.redirect(${origin}/auth/auth-code-error) } ` async function signInWithGoogle() { const supabase = supabaseBrowser(); const { error } = await supabase.auth.signInWithOAuth({ provider: 'google', options: { queryParams: { access_type: 'offline', prompt: 'consent', }, redirectTo:${window.location.origin}/auth/callback, } }); if (error) { console.error('Error signing in:', error); } } It sucessfully creates the user, but and logs in but when i try to fetch userId or session i run into the prescribed error

I may be wrong but I don't think you're supposed to use NEXT_PUBLIC_XXX env vars on the server side!

Daniel-Alamezie commented 2 weeks ago

Oh, they just env variable no? they should just work. I use them other places in the code and they work fine for their function

rookledookle commented 2 weeks ago

Yeah but the next public prefix means it's for client side use! To be safe I believe we shouldn't use that on the server you can create the same vars but without that prefix.

On Tue, 16 Apr 2024, 2:26 am Daniel, @.***> wrote:

Oh, they just env variable no? they should just work. I use them other places in the code and they work fine for their function

— Reply to this email directly, view it on GitHub https://github.com/supabase/supabase-js/issues/992#issuecomment-2057548232, or unsubscribe https://github.com/notifications/unsubscribe-auth/ACFZKU6Y6PXDV47SEXMMKVLY5QLUBAVCNFSM6AAAAABFG25D7CVHI2DSMVQWIX3LMV43OSLTON2WKQ3PNVWWK3TUHMZDANJXGU2DQMRTGI . You are receiving this because you are subscribed to this thread.Message ID: @.***>

Daniel-Alamezie commented 2 weeks ago

Ah right, i'll do some refactoring and give that a go.. So just to confirm you have google OAuth working currently correct?

rookledookle commented 2 weeks ago

Yep! Working with the above code

On Tue, 16 Apr 2024, 2:29 am Daniel, @.***> wrote:

Ah right, i'll do some refactoring and give that a go.. So just to confirm you have google OAuth working currently correct?

— Reply to this email directly, view it on GitHub https://github.com/supabase/supabase-js/issues/992#issuecomment-2057553975, or unsubscribe https://github.com/notifications/unsubscribe-auth/ACFZKU2KLGURZ6XHNFHHQO3Y5QMBTAVCNFSM6AAAAABFG25D7CVHI2DSMVQWIX3LMV43OSLTON2WKQ3PNVWWK3TUHMZDANJXGU2TGOJXGU . You are receiving this because you are subscribed to this thread.Message ID: @.***>

Daniel-Alamezie commented 2 weeks ago

Hmm my issue isnt that the authentication and account creation doesnt work, That works fine. The issue i am getting is that, after the code has been extract and an exchange token is set. I cant seem to get a user when I try to query the auth.getUser(). If that makes sense

Daniel-Alamezie commented 2 weeks ago

Like i can see the user data after the account creation in the db, but when i try querying i dont get anything back. And its not a rls issue ive checked

vasyaqwe commented 2 weeks ago

Facing the same error, but it only happens if I call supabase.auth.getUser() in an API route handler. If called in a server component, no errors.

fabiokandrade commented 2 weeks ago

Facing the same error, but it only happens if I call supabase.auth.getUser() in an API route handler. If called in a server component, no errors.

same here!

Daniel-Alamezie commented 2 weeks ago

Facing the same error, but it only happens if I call supabase.auth.getUser() in an API route handler. If called in a server component, no errors.

Yeah i got around fixing this by making a supavase client that uses supabase url and supabase secret Key. Not anon key, this allows you to use the client in api route

mxmzb commented 2 weeks ago

It actually works fine. I guess you're all mixing up the server and client side supabase clients at some point.

The two resources that you need are these (combine these snippets):

  1. https://supabase.com/docs/guides/auth/server-side/oauth-with-pkce-flow-for-ssr?queryGroups=environment&environment=server
  2. https://supabase.com/docs/guides/auth/server-side/nextjs

If you want to make it work on the server side, most everything touching supabase should be server client.

A few more tips on the side:

mhdevfr commented 1 week ago

I have the same Issue with NUXT 3

ERPG commented 6 days ago

This is happening for me as well when calling a request to a route handler from a server component.