supabase: "JWSError JWSInvalidSignature" Error on Self-hosted Supabase

Describe the bug

We’re self-hosting Supabase. I’m getting “JWS Invalid Signature” error on requests made through an admin client instance. Service key is valid, we are using that same key with the GoTrue library in our GO server.

To Reproduce

const supabaseAdmin = createClient(
	supabaseUrl,
	supabaseServiceKey,
	{
		auth: {
			autoRefreshToken: false,
			persistSession: false
		}
	}
)
const { data, error } = await supabaseAdmin.from("some_table").select("*").limit(50)

That results in this error:

{
  code: 'PGRST301',
  details: null,
  hint: null,
  message: 'JWSError JWSInvalidSignature'
}

Any idea why this happens? It wasn’t happening with the hosted version.

About this issue

  • Original URL
  • State: closed
  • Created 3 years ago
  • Comments: 24 (1 by maintainers)

Most upvoted comments

after 2 days of searching and try every solution i just used the jwt code from supabase and made my own script to create anon and secure role key:

` import { KJUR } from ‘jsrsasig’

const JWT_HEADER = { alg: ‘HS256’, typ: ‘JWT’ } const now = new Date() const today = new Date(now.getFullYear(), now.getMonth(), now.getDate()) const fiveYears = new Date(now.getFullYear() + 5, now.getMonth(), now.getDate())

const anonToken = ` { “role”: “anon”, “iss”: “supabase”, “iat”: ${Math.floor(today.valueOf() / 1000)}, “exp”: ${Math.floor(fiveYears.valueOf() / 1000)} } `.trim()

const serviceToken = ` { “role”: “service_role”, “iss”: “supabase”, “iat”: ${Math.floor(today.valueOf() / 1000)}, “exp”: ${Math.floor(fiveYears.valueOf() / 1000)} } `.trim()

const generateRandomString = (length) => { const CHARS = ‘ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789’ let result = ‘’ const MAX = Math.floor(256 / CHARS.length) * CHARS.length - 1 const randomUInt8Array = new Uint8Array(1) for (let i = 0; i < length; i++) { let randomNumber do { crypto.getRandomValues(randomUInt8Array) randomNumber = randomUInt8Array[0] } while (randomNumber > MAX) result += CHARS[randomNumber % CHARS.length] } return result }

const jwt_secret_key = generateRandomString(128); const anonTokenSigned = KJUR.jws.JWS.sign(null, JWT_HEADER, anonToken, jwt_secret_key); const serviceTokenSigned = KJUR.jws.JWS.sign(null, JWT_HEADER, serviceToken, jwt_secret_key); console.log(`JWT_SECRET=${jwt_secret_key}`); console.log(`ANON_KEY=${anonTokenSigned}`); console.log(`SERVICE_ROLE_KEY=${serviceTokenSigned}`); `

now everything works fine and i can just copy paste into .env file.

It look like this bug isn’t fixed, it was just happened on my self hosted instance… pretty weird…

SUPER annoying problem. Used the tool Supabase provided and kept getting this error over and over. Wracking my brain for hours trying to figure out the problem.

Had Claude 3.7 write a script to generate new keys, and it worked. Script is here:

const crypto = require('crypto');
const base64url = require('base64url');

function generateSupabaseKey(role, jwtSecret) {
  // Create the header
  const header = {
    alg: 'HS256',
    typ: 'JWT'
  };
  
  // Create the payload with required claims
  const now = Math.floor(Date.now() / 1000);
  const payload = {
    role: role,
    iss: "supabase",
    iat: now,
    exp: now + (60 * 60 * 24 * 365 * 5) // 5 years expiration
  };
  
  // Base64Url encode the header and payload
  const encodedHeader = base64url(JSON.stringify(header));
  const encodedPayload = base64url(JSON.stringify(payload));
  
  // Create the content to be signed
  const signatureContent = `${encodedHeader}.${encodedPayload}`;
  
  // Create the signature
  const signature = crypto
    .createHmac('sha256', jwtSecret)
    .update(signatureContent)
    .digest();
  
  // Base64Url encode the signature
  const encodedSignature = base64url(signature);
  
  // Combine to create the JWT token
  return `${signatureContent}.${encodedSignature}`;
}

// Example usage
const JWT_SECRET = process.env.SUPABASE_JWT_SECRET || 'your-jwt-secret-here';

const serviceRoleKey = generateSupabaseKey('service_role', JWT_SECRET);
const anonKey = generateSupabaseKey('anon', JWT_SECRET);

console.log('SERVICE_ROLE Key:');
console.log(serviceRoleKey);
console.log('\nANON Key:');
console.log(anonKey);

Run this beforehand: npm install crypto base64url And make sure the secret is set: export SUPABASE_JWT_SECRET='your-jwt-secret-here'

Then run this file: node generate-supabase-keys.js.

Solved the problem for me. Hope it helps someone else.

Experiencing similar effects here, running locally during development. CleanShot 2023-08-28 at 17 32 44@2x

I’ve changed the JWT secret to something long (128 characters) and with no special characters. The error disappeared. When we had the JWT same length to the one in the Supabase docs, we were getting the error.

This definitely looks like something that only happens on self-hosted. It wasn’t happening while we were using the hosted version (with same style and length JWT secret).