Authenticating a User with a JSON Web Token (JWT)
Last edit: Jan 23, 2024
This guide will help you authenticate JSON requests with a JSON Web Token (JWT).
Requirements
To follow the steps in this tutorial, you should be familiar with the concept of pages, users, and Authorization Policies.
Steps
Authenticating a user with a JSON Web Token (JWT) is a three-step process:
Step 1: Fetch JSON Web Token (JWT) for a user
It can be done after user login, the token should usually be stored in the browser memory.
app/graphql/user_jwt_token.graphql
{
current_user{
jwt_token
}
}
Note
Every time you fetch the jwt_token
, the old token becomes inactive.
Step 2: Create a page with a policy that checks the JSON Web Token (JWT)
The Authorization Policy fetches the JSON Web Token (JWT) from the request header and sets the current user using this token.
app/graphql/jwt_login
mutation jwt_login($token: String!) {
jwt_decode_and_set_session(jwt_token: $token) {
email
first_name
last_name
jwt_token
id
}
}
app/authorization_policies/api_set_current_user.liquid
---
name: api_set_current_user
---
{% if context.headers.HTTP_AUTHORIZATION %}
{%- assign token = context.headers.HTTP_AUTHORIZATION | remove: "Bearer " -%}
{%- graphql g = 'jwt_login', token: token -%}
{% if g.jwt_decode_and_set_session %}
{%- assign current_user = g.jwt_decode_and_set_session %}
true
{% else %}
{% log g %}
false
{% endif %}
{% endif %}
app/views/pages/api/orders.json.liquid
---
slug: api/orders
layout: ''
authorization_policies:
- api_set_current_user
---
{ "orders": [{ "id": "1" }] }
Step 3: Send signed request
curl
curl -i -H "Content-Type: application/json" \
-H "Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoxNTg2MTB9.i23YVYeckeoNeYmO3UKpvWfAWek96YUx8S7k5VKrIcM" \
-XPOST https://example.staging.oregon.platform-os.com/api/orders.json
js fetch
fetch("https://example.staging.oregon.platform-os.com/api/orders.json", {
headers: {
Authorization: "Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoxNTg2MTB9.i23YVYeckeoNeYmO3UKpvWfAWek96YUx8S7k5VKrIcM",
"Content-Type": "application/json"
},
method: "POST"
})