sassoftware / postgrest-client

General purpose type-safe TypeScript client for PostgREST. Supports select, insert, update, upsert, delete queries with composite joins, resource embedding, full JSON column data handling and typing.
Apache License 2.0
10 stars 0 forks source link

Example using JWT authentication #7

Closed matimusss closed 1 month ago

matimusss commented 7 months ago

There isn't any example showing how to handle JWT auth / headers, am I right?

Shouldn't there be one, as postgREST typically uses this kind of auth?

Greetings, thanks for your work!

matimusss commented 7 months ago

Example,

type DB = { todos: PostgresTable<{ id: number; done: boolean; task: Text }, 'id'>;};

const pgClient = new PostgrestClient({ base: 'https://postgrest-2n44.onrender.com',});

const jwt = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJyb2xlIjoidG9kb191c2VyIn0.MbTpBHdNhsy0Cbi3rMhbzDai-0Y2bXVaHtD0g3VP-jk";

const headers = new Headers({ 'Authorization': Bearer ${jwt} });

const { rows2 } = await pgClient.post({ query: pgClient.query('todos'), data: { done: false, task:'todosfuncioan' }, headers: headers, });

bojan88 commented 6 months ago

There isn't any example showing how to handle JWT auth / headers, am I right? Shouldn't there be one, as postgREST typically uses this kind of auth?

Yes, you are right. I think that might be outside of the scope of this library, but I'm not sure about it. @kegjon do you have any opinions on this?

Thank you for the example. We identified 2 ways to provide JWT:

1. Passing headers to every request (your example)

const pgClient = new PostgrestClient<DB>({ base: 'https://example.com' });
const res = await pgClient.get({
  headers: new Headers({ Authorization: `Bearer ${jwtToken}` }),
  query: pgClient.query("my-table"),
});

2. Using Axios client

const axiosInstance = axios.create({ headers: { Authorization: `Bearer ${jwtToken}` } });
const pgClient = new PostgrestClient<DB>({
  base: 'https://example.com',
  axiosInstance,
});
...
const res = await pgClient.get({ query: pgClient.query("my-table") })
const res = await pgClient.post({ ... })

Hopefully it's obvious that you'll need to pass the header to every request for option 1., and just once for option 2. using Axios.

bojan88 commented 1 month ago

Closing since this is answered. We might decide to add an example in the future