Using Supabase to authenticate ASP.NET web application #47
Unanswered
rossirpaulo
asked this question in
Q&A
Replies: 1 comment
-
https://www.rodyvansambeek.com/blog/using-supabase-auth-with-dotnet Using and validating Supabase Auth tokens in Dotnet backend. The client will first need to fetch token from supabase using the js library or with following http request: const myHeaders = new Headers();
myHeaders.append("apikey", "Anon-Key");
myHeaders.append("Content-Type", "application/json");
const raw = JSON.stringify({
"email": "EMAIL",
"password": "PASSWORD"
});
const requestOptions = {
method: "POST",
headers: myHeaders,
body: raw,
redirect: "follow"
};
fetch("https://Supabase-project-id.supabase.co/auth/v1/token?grant_type=password", requestOptions)
.then((response) => response.text())
.then((result) => console.log(result))
.catch((error) => console.error(error)); Then the backend verifies the token using following code var builder = WebApplication.CreateBuilder(args);
var supabaseSettings = new SupabaseSettings();
builder.Configuration.GetRequiredSection("Supabase").Bind(supabaseSettings);
// Configure JWT Bearer authentication for Supabase
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidIssuers = supabaseSettings.ValidIssuers ?? new string[] { },
ValidateAudience = true,
ValidAudiences = supabaseSettings.ValidAudiences ?? new string[] { },
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(supabaseSettings.JwtSignatureSecret ?? string.Empty)),
ValidateLifetime = true
};
});
builder.Services.AddAuthorization();
builder.Services.AddAuthorization();
var app = builder.Build();
app.UseAuthentication();
app.UseAuthorization();
app.MapGet("/me", (System.Security.Claims.ClaimsPrincipal user) =>
{
if (!user.Identity?.IsAuthenticated ?? true)
{
return Results.Unauthorized();
}
// Extract user info from claims
var userId = user.FindFirst("sub")?.Value ??
user.FindFirst("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier")?.Value;
var email = user.FindFirst("email")?.Value ??
user.FindFirst("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress")?.Value;
var name = user.FindFirst("user_metadata")?.Value;
string? fullName = null;
if (name != null)
{
try
{
var userMetadata = System.Text.Json.JsonDocument.Parse(name);
if (userMetadata.RootElement.TryGetProperty("full_name", out var fullNameProp))
{
fullName = fullNameProp.GetString();
}
}
catch { /* ignore parse errors */ }
}
return Results.Ok(new
{
id = userId,
email,
name = fullName,
claims = user.Claims.Select(c => new { c.Type, c.Value })
});
}).RequireAuthorization();
app.Run();
internal class SupabaseSettings
{
public string? url { get; set; }
public string? AnonKey { get; set; }
public string? ServiceKey { get; set; }
// your jwt-secret from supabase at settings -> Data api -> JWT secret"
public string? JwtSignatureSecret { get; set; }
public string[]? ValidAudiences { get; set; }
public string[]? ValidIssuers { get; set; }
} |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
Is there a code example someone could provide showcasing how to authenticate users within the ASP.NET domain?
Beta Was this translation helpful? Give feedback.
All reactions