Supabase

How to implement custom JWT claims with Supabase authentication?

Discover the process of adding custom JWT claims in Supabase authentication. For better security? Absolutely. For a tailored user experience! This guide breaks it down step-by-step.

Developer profile skeleton
a developer thinking

Overview

Adding custom JWT claims with Supabase authentication lets you pack extra info into the token's payload. This can be handy for setting up roles, permissions, or other specific details for your app. To do this, you'll usually tap into Supabase's server-side tools like the API or database triggers to slide those custom claims into the JWT. Grasping JWT structure basics, Supabase's auth system, and securely managing tokens is crucial here. This guide will lead you through the steps and key points to add custom claims effectively.

Get a Free No-Code Consultation
Meet with Will, CEO at Bootstrapped to get a Free No-Code Consultation
Book a Call
Will Hawkins
CEO at Bootstrapped

How to implement custom JWT claims with Supabase authentication?

Step 1: Set Up a Supabase Project

First things first, head over to Supabase and either sign up or log in. Once you're in, create a new project. Don't forget to save the URL and API keys they give you. You'll need those later.

Step 2: Configure JWT Secret

Next, go to the "Settings" tab of your new Supabase project. Then, find the "API" section. Here, you'll see the "JWT Secret." Make a note of this value because you'll need it to verify and decode the JWTs.

Step 3: Add a Custom Claim

To add custom claims to your JWT, you'll need to tweak the authentication logic of your app. This is usually done on the backend. If you're using Node.js, it might look something like this:

const jwt = require('jsonwebtoken');

// Assume supabaseKey and supabaseSecret are your Supabase project key and secret
const supabaseKey = process.env.SUPABASE_KEY;
const supabaseSecret = process.env.SUPABASE_JWT_SECRET;

// Function to sign a JWT with custom claims
function signJWT(payload) {
    const customClaims = {
        // Add your custom claims here
        'https://myapp.com/jwt/claims': {
            'role': 'admin',
            'user_id': payload.id
        }
    };
    return jwt.sign(customClaims, supabaseSecret);
}

// Example usage
const userPayload = { id: '1234', email: '[email protected]' };
const token = signJWT(userPayload);
console.log('Generated JWT:', token);

Step 4: Update Client-Side Authentication

Once you've got the token with the custom claims, pass it to the client-side of your app. Use this token when making requests to Supabase.

// Example of setting the token in Supabase client
const supabase = createClient(SUPABASE_URL, SUPABASE_KEY, {
    headers: {
        Authorization: `Bearer ${token}`
    }
});

Step 5: Verify Custom Claims in Supabase Functions

When you need to access these custom claims in Supabase's server-side functions, use the same JWT library to verify and decode the token. For example, using Node.js:

const jwt = require('jsonwebtoken');

function verifyJWT(token) {
    try {
        const decoded = jwt.verify(token, supabaseSecret);
        console.log('Decoded JWT:', decoded);
        return decoded;
    } catch (err) {
        console.error('JWT verification failed:', err);
        return null;
    }
}

Use this function to decode the JWT and access the custom claims within any server-side logic, middleware, or Supabase functions.

Step 6: Configure Supabase Policies

In the Supabase dashboard, go to "Table Editor" and select the table for which you want to set up Row Level Security (RLS) policies. Enable RLS and define policies using SQL to utilize the custom claims.

For example, to leverage the custom role claim:

-- Enable RLS on the table
ALTER TABLE your_table ENABLE ROW LEVEL SECURITY;

-- Create a policy that uses the custom claim
CREATE POLICY "users_can_view_their_data"
ON your_table
FOR SELECT
USING (
    auth.jwt() ->> 'role' = 'admin'
);

This SQL query checks if the role in the JWT is admin for allowing select operations on your_table.

By following these steps, custom JWT claims can be effectively implemented and utilized in Supabase authentication flows.

Explore more Supabase tutorials

Complete Guide to Supabase: Tutorials, Tips, and Best Practices

Explore our Supabase tutorials directory - an essential resource for learning how to create, deploy and manage robust server-side applications with ease and efficiency.

Why are companies choosing Bootstrapped?

40-60%

Faster with no-code

Nocode tools allow us to develop and deploy your new application 40-60% faster than regular app development methods.

90 days

From idea to MVP

Save time, money, and energy with an optimized hiring process. Access a pool of experts who are sourced, vetted, and matched to meet your precise requirements.

1 283 apps

built by our developers

With the Bootstrapped platform, managing projects and developers has never been easier.

hero graphic

Our capabilities

Bootstrapped offers a comprehensive suite of capabilities tailored for startups. Our expertise spans web and mobile app development, utilizing the latest technologies to ensure high performance and scalability. The team excels in creating intuitive user interfaces and seamless user experiences. We employ agile methodologies for flexible and efficient project management, ensuring timely delivery and adaptability to changing requirements. Additionally, Bootstrapped provides continuous support and maintenance, helping startups grow and evolve their digital products. Our services are designed to be affordable and high-quality, making them an ideal partner for new ventures.

Engineered for you

1

Fast Development: Bootstrapped specializes in helping startup founders build web and mobile apps quickly, ensuring a fast go-to-market strategy.

2

Tailored Solutions: The company offers customized app development, adapting to specific business needs and goals, which ensures your app stands out in the competitive market.

3

Expert Team: With a team of experienced developers and designers, Bootstrapped ensures high-quality, reliable, and scalable app solutions.

4

Affordable Pricing: Ideal for startups, Bootstrapped offers cost-effective development services without compromising on quality.

5

Supportive Partnership: Beyond development, Bootstrapped provides ongoing support and consultation, fostering long-term success for your startup.

6

Agile Methodology: Utilizing agile development practices, Bootstrapped ensures flexibility, iterative progress, and swift adaptation to changes, enhancing project success.

Yes, if you can dream it, we can build it.