简体   繁体   English

无法在服务器端注销用户(Next.js 和 Supabase)

[英]Cannot log out user on the server side (Next.js and Supabase)

How can I log out a user on the server side when using Supabase as the auth provider?使用 Supabase 作为身份验证提供程序时,如何在服务器端注销用户?

I thought the simplest and most obvious solution would be to just do that:我认为最简单和最明显的解决方案就是这样做:

export const getServerSideProps: GetServerSideProps = withPageAuth({
    redirectTo: '/auth/sign-in',
    authRequired: true,
    async getServerSideProps(ctx) {
        const session = await supabaseServerClient(ctx).auth.session();
        await supabaseServerClient(ctx).auth.api.signOut(session!.access_token); // There is a valid access token

        return {
            redirect: {
                permanent: false,
                destination: '/auth/sign-in',
            }
        }
    }
});

I believe this is also what the docs say, but when I do that the response from the signOut is:我相信这也是文档所说的,但是当我这样做时,signOut 的响应是:

{ error: null }

But it does not do anything.但它什么也没做。 After the redirects happen the onAuthStateChange on the client side triggers with TOKEN_REFRESH.重定向发生后,客户端上的 onAuthStateChange 会使用 TOKEN_REFRESH 触发。

There must be something I don't understand, but I don't know what that is.一定有什么我不明白的,但我不知道那是什么。

This will not work because the Supabase Auth Helpers you are using store the tokens inside of cookies for this domain.这将不起作用,因为您使用的 Supabase Auth Helpers 将令牌存储在该域的 cookie 中。 You will need to also delete the cookies in order for this to work.您还需要删除 cookie 才能使其正常工作。 Alternatively, you should be using the logout endpoint which takes care of all this for you.或者,您应该使用注销端点来为您处理所有这些。

import { supabaseClient, withPageAuth } from "@supabase/auth-helpers-nextjs";
import {
  setCookies,
  NextRequestAdapter,
  NextResponseAdapter,
} from "@supabase/auth-helpers-shared";

export const getServerSideProps = withPageAuth({
  redirectTo: "/",
  async getServerSideProps(ctx) {
    const session = supabaseClient.auth.session();
    await supabaseClient.auth.api.signOut(session.access_token);

    setCookies(
      new NextRequestAdapter(ctx.req),
      new NextResponseAdapter(ctx.res),
      ["access-token", "refresh-token", "provider-token"].map((key) => ({
        name: `sb-${key}`,
        value: "",
        maxAge: -1,
      }))
    );

    return {
      redirect: {
        destination: "/",
        permanent: false,
      },
    };
  },
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM