pgjwt: JSON Web Tokens
The pgjwt extension is deprecated in projects using Postgres 17. It continues to be supported in projects using Postgres 15, but will need to dropped before those projects are upgraded to Postgres 17. See the Upgrading to Postgres 17 notes for more information.
The pgjwt (Postgres JSON Web Token) extension allows you to create and parse JSON Web Tokens (JWTs) within a Postgres database. JWTs are commonly used for authentication and authorization in web applications and services.
Enable the extension
- Go to the Database page in the Dashboard.
- Click on Extensions in the sidebar.
- Search for
pgjwtand enable the extension.
API
sign(payload json, secret text, algorithm text default 'HSA256'): Signs a JWT containing payload with secret using algorithm.verify(token text, secret text, algorithm text default 'HSA256'): Decodes a JWT token that was signed with secret using algorithm.
Where:
payloadis an encrypted JWT represented as a string.secretis the private/secret passcode which is used to sign the JWT and verify its integrity.algorithmis the method used to sign the JWT using the secret.tokenis an encrypted JWT represented as a string.
Usage
Once the extension is installed, you can use its functions to create and parse JWTs. Here's an example of how you can use the sign function to create a JWT:
1select2 extensions.sign(3 payload := '{"sub":"1234567890","name":"John Doe","iat":1516239022}',4 secret := 'secret',5 algorithm := 'HS256'6 );The pgjwt_encode function returns a string that represents the JWT, which can then be safely transmitted between parties.
1sign2---------------------------------3 eyJhbGciOiJIUzI1NiIsInR5cCI6IkpX4 VCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiw5 ibmFtZSI6IkpvaG4gRG9lIiwiaWF0Ijo6 xNTE2MjM5MDIyfQ.XbPfbIHMI6arZ3Y97 22BhjWgQzWXcXNrz0ogtVhfEd2o8(1 row)To parse a JWT and extract its claims, you can use the verify function. Here's an example:
1select2 extensions.verify(3 token := 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJuYW1lIjoiRm9vIn0.Q8hKjuadCEhnCPuqIj9bfLhTh_9QSxshTRsA5Aq4IuM',4 secret := 'secret',5 algorithm := 'HS256'6 );Which returns the decoded contents and some associated metadata.
1header | payload | valid2-----------------------------+----------------+-------3 {"alg":"HS256","typ":"JWT"} | {"name":"Foo"} | t4(1 row)Resources
- Official
pgjwtdocumentation