使用 Supabase 作为身份验证提供程序时,如何在服务器端注销用户?
我认为最简单、最明显的解决方案就是这样做:
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',
}
}
}
});
我相信这也是文档所说的,但是当我这样做时,signOut 的响应是:
{ error: null }
但它没有做任何事情。重定向发生后,客户端上的 onAuthStateChange 会通过 TOKEN_REFRESH 触发。
肯定有什么地方我不明白,但我不知道那是什么。
最佳答案
这将不起作用,因为您使用的 Supabase Auth Helpers 会将 token 存储在该域的 cookie 中。您还需要删除 cookie 才能使其正常工作。或者,您应该使用注销端点,它会为您处理所有这些事情。
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,
},
};
},
});
关于javascript - 无法在服务器端注销用户(Next.js 和 Supabase),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72972086/