mirror of
https://github.com/supabase/supabase.git
synced 2026-07-02 10:44:33 +08:00
64 lines
2.6 KiB
Plaintext
64 lines
2.6 KiB
Plaintext
---
|
|
id: auth
|
|
title: Auth
|
|
description: Supabase Edge Functions and Auth.
|
|
---
|
|
|
|
Edge Functions work seamlessly with [Supabase Auth](/docs/guides/auth), allowing you to identify which user called your function.
|
|
|
|
When [invoking](/docs/reference/javascript/invoke) a function with one of the [client libraries](/docs/reference), the logged in user's JWT is automatically attached to the function call and becomes accessible within your function.
|
|
|
|
This is important, for example, to identify which customer's credit card should be charged. You can see this concept end-to-end in our [Stripe example app](https://github.com/supabase-community/expo-stripe-payments-with-supabase-functions).
|
|
|
|
## Auth Context & RLS
|
|
|
|
By creating a supabase client with the auth context from the function, you can do two things:
|
|
|
|
1. Get the user object.
|
|
2. Run queries in the context of the user with [Row Level Security (RLS)](/docs/guides/auth/row-level-security) policies enforced.
|
|
|
|
```js title="supabase/functions/select-from-table-with-auth-rls/index.ts"
|
|
import { serve } from 'https://deno.land/std@0.131.0/http/server.ts'
|
|
import { createClient } from 'https://esm.sh/@supabase/supabase-js@2.0.0-rc.12'
|
|
|
|
serve(async (req: Request) => {
|
|
try {
|
|
// Create a Supabase client with the Auth context of the logged in user.
|
|
const supabaseClient = createClient(
|
|
// Supabase API URL - env var exported by default.
|
|
Deno.env.get('SUPABASE_URL') ?? '',
|
|
// Supabase API ANON KEY - env var exported by default.
|
|
Deno.env.get('SUPABASE_ANON_KEY') ?? '',
|
|
// Create client with Auth context of the user that called the function.
|
|
// This way your row-level-security (RLS) policies are applied.
|
|
// highlight-next-line
|
|
{ global: { headers: { Authorization: req.headers.get('Authorization')! } } }
|
|
)
|
|
// Now we can get the session or user object
|
|
// highlight-start
|
|
const {
|
|
data: { user },
|
|
} = await supabaseClient.auth.getUser()
|
|
// highlight-end
|
|
|
|
// And we can run queries in the context of our authenticated user
|
|
// highlight-start
|
|
const { data, error } = await supabaseClient.from('users').select('*')
|
|
if (error) throw error
|
|
// highlight-end
|
|
|
|
return new Response(JSON.stringify({ user, data }), {
|
|
headers: { 'Content-Type': 'application/json' },
|
|
status: 200,
|
|
})
|
|
} catch (error) {
|
|
return new Response(JSON.stringify({ error: error.message }), {
|
|
headers: { 'Content-Type': 'application/json' },
|
|
status: 400,
|
|
})
|
|
}
|
|
})
|
|
```
|
|
|
|
See the [example on GitHub](https://github.com/supabase/supabase/blob/master/examples/edge-functions/supabase/functions/select-from-table-with-auth-rls/index.ts).
|