3

I am attempting to build a Vue application that uses Supabase authentication. Inside one of the route guards in the router file, I implemented supabase.auth.getUser() in order to retrieve the user login status for a conditional that prevents next() from executing before the user is authenticated:

// Route guard for auth routes
router.beforeEach((to, from, next) => {
  // const user = supabase.auth.user();
  const { data: { user } } = await supabase.auth.getUser();

  if (to.matched.some((res) => res.meta.auth)) {
    if (user) {
      next();
      return;
    }
    next({ name: "Login" });
    return;
  }
  next();
});

However, when I implement supabase.auth.getUser() inside the router guard, I get the following error in the console before logging in: "invalid claim: missing sub claim". After logging in, the error goes away. If I remove the supabase.auth.getUser conditional from the route guard, the error also goes away. After some additional digging online and running my Supabase anon key in jwt.io, it appears that my key is missing sub claim in the payload. If this is preventing the key from being authenticated properly, how can I resolve it?

JS_is_awesome18
  • 1,587
  • 7
  • 23
  • 67
  • Please check this link. It might help. https://github.com/supabase-community/supabase-custom-claims – Vaysage Feb 03 '23 at 09:07

1 Answers1

4

You should be checking against the session rather than the user. The user will try to check against a JWT first which wouldn't exist at the time of checking since you're not logged in. Use getSession instead:

// Route guard for auth routes
router.beforeEach((to, from, next) => {
  // const user = supabase.auth.user();
  const { data: { session } } = await supabase.auth.getSession();

  if (to.matched.some((res) => res.meta.auth)) {
    if (session?.user) {
      next();
      return;
    }
    next({ name: "Login" });
    return;
  }
  next();
});
Andrew Smith
  • 1,224
  • 6
  • 9
  • Thanks. Yeah I actually figured that out after consulting with the Supabase admins. Now I see it in the docs: https://supabase.com/docs/reference/javascript/auth-getsession. I didn't see this before as I was looking under user management in the regular API docs, not the docs for the JavaScript client. Thanks nonetheless! I'll still up-vote this answer. – JS_is_awesome18 Feb 07 '23 at 16:22