PostgREST / postgrest

REST API for any Postgres database
https://postgrest.org
MIT License
23.4k stars 1.03k forks source link

Invalidate JWT claims without `pre-request` #2841

Open steve-chavez opened 1 year ago

steve-chavez commented 1 year ago

Problem

Currently we document invalidating a JWT with a pre-request: https://postgrest.org/en/stable/tutorials/tut1.html#bonus-topic-immediate-revocation

However a pre-request is an extra function call for every request. This hurts performance.

Solution

Use the pre-config function for revoking JWTs. This function only runs at startup or reload time.

It could be like:

-- postgrest reads from an arbitrary table 
create or replace function postgrest.pre_config()
returns void as $$
  select
      set_config('pgrst.auth_jwt.invalidated_claims', 
        (select string_agg(val, ',') from my_bad_claims where date > 'yesterday'::timestamptz), true);
$$ language sql;

The user would have to do:

INSERT INTO my_bad_claims VALUES ('<JWT>');
NOTIFY pgrst, 'reload config'; -- this could be done automatically in a trigger

We would read the pgrst.auth_jwt.invalidated_claims setting and store it in the server. We can then invalidate JWTs based on that list.

steve-chavez commented 1 year ago

Since we would be basically caching data inside PostgREST with the above, I wonder if this could be a way to support sessions natively. This was attempted before with pre-request: https://github.com/monacoremo/postgrest-sessions-example/

Note that we don't depend on any table structure with pre-config. So in theory we could support any table that has users/passwords.

wolfgangwalther commented 11 months ago

This hurts performance.

You would need to invalidate a lot of tokens to make this a real problem, right?

With a sensibly low token expiry, this should not be a performance problem, imho. Did you have a specific case?