gurkang
gurkang
CC#
Created by gurkang on 4/7/2023 in #help
❔ Handling Supabase auth with dotnet backend. Is this way wrong/not the dotnet way?
I'm authenticating users on the frontend using supabase auth. After successful authentication I get returned user data, jwt, and more. I then want communicate with some backend services, which I'm trying to write in dotnet. I include the token from FE in the request and then handle it with some middleware to handle this like so:
app.Use(async (context, next) =>
{
try
{
var token = context.Request.Headers["Authorization"].ToString();
if (string.IsNullOrWhiteSpace(token))
{
throw new AuthenticationException("Missing JWT");
}

var client = new HttpClient();
client.DefaultRequestHeaders.Add("Authorization", token);
var apiKey = builder.Configuration.GetValue<string>("apiKey");
client.DefaultRequestHeaders.Add("apikey", apiKey);
var res = await client.GetFromJsonAsync<UserFromSupabase>(
builder.Configuration.GetValue<string>("supabaseUrl"));

if (res == null)
{
throw new AuthenticationException("Invalid token");
}

;

if (res is { Aud: not null, Email: not null, Id: not null })
{
context.User = new ClaimsPrincipal(new ClaimsIdentity(new List<Claim>
{
new Claim("Email", res.Email),
new Claim("Id", res.Id),
new Claim("Aud", res.Aud)
}));
}

;
await next(context);
}
catch (System.Exception error)
{
context.Response.Clear();
context.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
await context.Response.WriteAsJsonAsync("Malformed or expired JWT");
}
});
app.Use(async (context, next) =>
{
try
{
var token = context.Request.Headers["Authorization"].ToString();
if (string.IsNullOrWhiteSpace(token))
{
throw new AuthenticationException("Missing JWT");
}

var client = new HttpClient();
client.DefaultRequestHeaders.Add("Authorization", token);
var apiKey = builder.Configuration.GetValue<string>("apiKey");
client.DefaultRequestHeaders.Add("apikey", apiKey);
var res = await client.GetFromJsonAsync<UserFromSupabase>(
builder.Configuration.GetValue<string>("supabaseUrl"));

if (res == null)
{
throw new AuthenticationException("Invalid token");
}

;

if (res is { Aud: not null, Email: not null, Id: not null })
{
context.User = new ClaimsPrincipal(new ClaimsIdentity(new List<Claim>
{
new Claim("Email", res.Email),
new Claim("Id", res.Id),
new Claim("Aud", res.Aud)
}));
}

;
await next(context);
}
catch (System.Exception error)
{
context.Response.Clear();
context.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
await context.Response.WriteAsJsonAsync("Malformed or expired JWT");
}
});
But from my experience when doing auth on .Net you're "supposed" to use the useAuthorisation/useAuthentication middleware that's provided by default in the .Net framework? Am I trying to force a very "not dotnet" style of coding onto the framework? Is there a better way to do this?
174 replies