Maxime Gagné
Maxime Gagné

Reputation: 11

Supabase: Generate Custom Refresh Tokens

I implemented custom authentication for logging into a React app using Web3. Currently, I can authenticate by generating a custom JWT with the Supabase SDK in .NET, but the token is only valid for its lifespan. Supabase uses a refresh token to generate new tokens, but I'm unsure if it's possible to create a refresh token in this scenario. Does anyone have a solution for this?

Frontend:

const nonce = await requestNonce(address);
const combinedMessage = `${SIGN_IN_MESSAGE}${nonce}`;
const signature = await signer.signMessage(combinedMessage);
const authResponse = await getAuthToken(address, signature, SIGN_IN_MESSAGE);

if (authResponse?.token) {
  await supabase.auth.setSession({
    access_token: authResponse.token,
    refresh_token: authResponse.token,
   });

const session = await supabase.auth.getSession();

Backend (JWT generation):

using System;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using Microsoft.IdentityModel.Tokens;
using System.Text;

public class JwtGenerator
{
    public string GenerateToken(string userId, string secretKey, int expiryInMinutes)
    {
        var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(secretKey));
        var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256);

        // Include additional claims required by Supabase
        var claims = new[]
        {
            new Claim(JwtRegisteredClaimNames.Sub, userId),
            new Claim("role", "authenticated"),
            new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
            new Claim(JwtRegisteredClaimNames.Iat, DateTimeOffset.UtcNow.ToUnixTimeSeconds().ToString(), ClaimValueTypes.Integer64)
        };

        var token = new JwtSecurityToken(
            issuer: null,
            audience: "authenticated",
            claims: claims,
            expires: DateTime.UtcNow.AddMinutes(expiryInMinutes),
            signingCredentials: credentials
        );

        return new JwtSecurityTokenHandler().WriteToken(token);
    }
}

The problem is, while the access_token works as expected, I’m not sure how to create or use a proper refresh token with Supabase. Is there a way to generate a refresh token with Supabase, or should I implement my own refresh mechanism? How do I ensure a seamless session extension with this custom flow?

Any guidance or suggestions would be greatly appreciated!

Upvotes: 0

Views: 47

Answers (0)

Related Questions