Supabase:RLS auth.uid() = user_id 在 Next.js 路由处理程序中为 false

问题描述 投票:0回答:1

我在 Next.js 应用程序中尝试通过路由处理程序获取数据时遇到问题。

我的数据库有一个用户表,其中包含一个名为

user_id
的 ID,它与经过身份验证的用户的 uid 相匹配,以及
aps_id
,我用它来调用第 3 方 API。

如果我没有在表上启用 RLS,当我对用户 ID 进行匹配时,我会按预期返回行。

如果我使用规则启用了 RLS

auth.uid() = user_id
,我不会返回任何行。

我的路由处理程序中有以下代码:

路线.ts

import { createRouteHandlerClient } from '@supabase/auth-helpers-nextjs';
import { cookies } from 'next/headers';
import { NextResponse } from 'next/server';

export async function GET() {
    try {
        const supabase = createRouteHandlerClient({ cookies });

        const { data: userData } = await supabase.from('users').select('aps_id').single();
        const apsId = userData?.aps_id;
        const {
            data: { user },
        } = await supabase.auth.getUser();

        console.log(user); // no user being returned?


        const res = await fetch(process.env.APS_API_URL + 'ClientEligibility/' + apsId, {
            method: 'GET',
            headers: {
                'Content-Type': 'application/json',
                'apiKey': process.env.APS_API_KEY || ''
            }
        });
    
        const data = await res.json();

        console.log(data); // this is null, but it should be returning a row?
    
        return NextResponse.json({ data });
    } catch(e) {
        console.error(e);

        return NextResponse.json({ error: e }, { status: 500 });
    }
}

似乎没有返回用户会话数据,所以我假设 RLS 策略中的 auth.uid() 也会导致 null。

在路由处理程序中获取用户会话还需要其他必要的步骤吗?

如果我没有在表上启用 RLS,当我对用户 ID 进行匹配时,我会按预期返回行。 如果我使用规则

auth.uid() = user_id
启用了 RLS,则不会返回任何行。

reactjs next.js routes handler supabase
1个回答
0
投票

Next.js 应用程序中的行级安全性 (RLS) 问题可以通过确保在访问 Supabase 数据库中的受保护资源之前获得完全授权来解决。您正在尝试在代码中从 Supabase 数据库获取数据。这意味着您必须确保用户已获得授权,并且身份验证令牌随请求一起提供给 Supabase。在访问路线之前,请确保您的用户已获得适当的授权。使用 Supabase 的身份验证库,您应该确定用户是否经过身份验证。向 Next.js 路由处理程序发送请求时,请在请求中包含身份验证令牌。

export async function GET({ request }) {
    try {
        // Check if the user is authenticated
        const user = await supabase.auth.api.getUserByCookie(request);

        if (!user) {
            // Handle unauthenticated user (e.g., return an error response)
            return NextResponse.error('Not authenticated', { status: 401 });
        }

        // Now that the user is authenticated, get the UID
        const uid = user.id;

        const supabase = createRouteHandlerClient({ cookies });

        const { data: userData } = await supabase
            .from('users')
            .select('aps_id')
            .eq('user_id', uid) // Filter by the authenticated user's UID
            .single();

        const apsId = userData?.aps_id;

        // Proceed with the rest of your code, including the fetch request to the API

        // ...

        return NextResponse.json({ data });
    } catch (e) {
        console.error(e);
        return NextResponse.json({ error: e }, { status: 500 });
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.