Handling authentication correctly is a key step in ensuring the security of your application in production. This is a very important component of any backend system. There are multiple ways to be authenticated but in this post I will focus on JWT authentication.
Ways to authenticate users for your application:
JWT based authentication
We assume you are familiar with what a JWT is. If you are new to JWT’s here is a guide we have put together explaining how JWT’s work in the context of front end GraphQL clients. It also covers the security aspects of using a JWT for authentication.
Here’s how JWT based authentication works:
Authorization
header.Validating the JWT Token in step 4. above requires a JWT secret. You can enable JWT mode by using the --jwt-secret
flag or HASURA_GRAPHQL_JWT_SECRET
environment variable while starting Hasura. The the value of the flag or environment variable must be a JSON object.
{ "type":"HS256", "key":"testtesttesttesttesttesttesttest", "claims_namespace":"hasura", "audience":"folautech-api", "issuer":"folautech-api" }
Note that key must be equal to or more than 32 characters.
JWT Payload
{ "iss" : "folautech-api", "jti" : "5c16f712-7ded-4479-9c90-266501b003d0-PfAdAIEeLz", "sub" : "3", "aud" : "folautech-meal-plan", "iat" : "2021-03-16T09:02:12.955Z", "exp" : "2021-03-16T10:42:12.955Z", "admin" : false, "name" : "Laulau Kaveinga", "hasura" : { "x-hasura-default-role" : "user", "x-hasura-user-id" : "3", "x-hasura-allowed-roles" : [ "user" ] } }
x-hasura-default-role
field : indicating the default role of that user i.e. the role that will be used in case x-hasura-role
header is not passed.x-hasura-allowed-roles
field : a list of allowed roles for the user i.e. acceptable values of the x-hasura-role
header. The x-hasura-default-role
specified should be a member of this list.x-hasura-user-id
field : id of the authenticated user which is used to authorized user to access database tables. x-hasura-custom
field : you can add custom hasura properties which can be used to query database