mirror of
https://github.com/CannedNet/CannedNet.git
synced 2026-10-25 15:09:23 -07:00
+61
-16
@@ -1,8 +1,9 @@
|
||||
using System.Security.Claims;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using CannedNet.Admin.Components;
|
||||
using CannedNet.Admin.Services;
|
||||
using Microsoft.AspNetCore.Authentication;
|
||||
using Microsoft.AspNetCore.Authentication.Cookies;
|
||||
|
||||
var builder = WebApplication.CreateBuilder(args);
|
||||
|
||||
@@ -23,22 +24,17 @@ builder.Services.AddAuthentication("AdminCookie")
|
||||
options.SlidingExpiration = true;
|
||||
});
|
||||
|
||||
builder.Services.AddAuthorization(options =>
|
||||
{
|
||||
options.AddPolicy("OwnerOnly", policy => policy.RequireClaim("role", "Owner"));
|
||||
});
|
||||
builder.Services.AddAuthorization();
|
||||
|
||||
builder.Services.AddSingleton<AdminAuthService>();
|
||||
var imagesBaseUrl = builder.Configuration.GetValue<string>("ImagesBaseUrl") ?? "http://localhost:5000/img";
|
||||
builder.Services.AddSingleton(new ImageUrlService(imagesBaseUrl));
|
||||
builder.Services.AddHttpContextAccessor();
|
||||
|
||||
|
||||
var serverUrl = builder.Configuration.GetValue<string>("ServerBaseUrl") ?? "http://localhost:5000";
|
||||
builder.Services.AddTransient<AdminApiKeyHandler>();
|
||||
builder.Services.AddTransient<JwtBearerHandler>();
|
||||
builder.Services.AddScoped(sp =>
|
||||
{
|
||||
var handler = sp.GetRequiredService<AdminApiKeyHandler>();
|
||||
var handler = sp.GetRequiredService<JwtBearerHandler>();
|
||||
handler.InnerHandler = new SocketsHttpHandler();
|
||||
return new HttpClient(handler) { BaseAddress = new Uri(serverUrl) };
|
||||
});
|
||||
@@ -47,7 +43,7 @@ var app = builder.Build();
|
||||
|
||||
// --- Admin Auth Endpoints ---
|
||||
|
||||
app.MapPost("/admin/login", async (HttpContext context, AdminAuthService authService) =>
|
||||
app.MapPost("/admin/login", async (HttpContext context) =>
|
||||
{
|
||||
var form = await context.Request.ReadFormAsync();
|
||||
var username = form["username"].FirstOrDefault() ?? "";
|
||||
@@ -59,20 +55,55 @@ app.MapPost("/admin/login", async (HttpContext context, AdminAuthService authSer
|
||||
return;
|
||||
}
|
||||
|
||||
var user = authService.GetByUsername(username);
|
||||
if (user == null || !authService.VerifyPassword(password, user.PasswordHash))
|
||||
var serverUrl = app.Services.GetRequiredService<IConfiguration>().GetValue<string>("ServerBaseUrl") ?? "http://localhost:5000";
|
||||
using var httpClient = new HttpClient { BaseAddress = new Uri(serverUrl) };
|
||||
var tokenResponse = await httpClient.PostAsync("/auth/connect/token", new FormUrlEncodedContent(new Dictionary<string, string>
|
||||
{
|
||||
["grant_type"] = "password",
|
||||
["username"] = username,
|
||||
["password"] = password
|
||||
}));
|
||||
|
||||
if (!tokenResponse.IsSuccessStatusCode)
|
||||
{
|
||||
context.Response.Redirect("/login?error=invalid");
|
||||
return;
|
||||
}
|
||||
|
||||
var claims = new[]
|
||||
var json = await tokenResponse.Content.ReadAsStringAsync();
|
||||
using var doc = System.Text.Json.JsonDocument.Parse(json);
|
||||
var accessToken = doc.RootElement.GetProperty("access_token").GetString();
|
||||
|
||||
if (string.IsNullOrEmpty(accessToken))
|
||||
{
|
||||
new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()),
|
||||
new Claim(ClaimTypes.Name, user.Username),
|
||||
new Claim("role", user.IsOwner ? "Owner" : "Admin")
|
||||
context.Response.Redirect("/login?error=invalid");
|
||||
return;
|
||||
}
|
||||
|
||||
var payloadJson = DecodeJwtPayload(accessToken);
|
||||
using var payload = JsonDocument.Parse(payloadJson);
|
||||
var accountId = payload.RootElement.TryGetProperty("sub", out var sub) ? sub.GetString() ?? "" : "";
|
||||
var role = "";
|
||||
if (payload.RootElement.TryGetProperty("role", out var r))
|
||||
{
|
||||
if (r.ValueKind == JsonValueKind.String)
|
||||
role = r.GetString() ?? "";
|
||||
else if (r.ValueKind == JsonValueKind.Array)
|
||||
role = string.Join(",", r.EnumerateArray().Select(x => x.GetString() ?? ""));
|
||||
}
|
||||
var name = payload.RootElement.TryGetProperty("platform_id", out var pid) ? pid.GetString() ?? username : username;
|
||||
|
||||
var claims = new List<Claim>
|
||||
{
|
||||
new(ClaimTypes.NameIdentifier, accountId),
|
||||
new(ClaimTypes.Name, name),
|
||||
new("access_token", accessToken)
|
||||
};
|
||||
|
||||
// Map JWT roles for admin app authorization
|
||||
if (role.Split(',', StringSplitOptions.RemoveEmptyEntries).Any(rr => rr == "developer" || rr == "admin"))
|
||||
claims.Add(new Claim(ClaimTypes.Role, "Admin"));
|
||||
|
||||
var identity = new ClaimsIdentity(claims, "AdminCookie");
|
||||
var principal = new ClaimsPrincipal(identity);
|
||||
|
||||
@@ -111,3 +142,17 @@ app.MapRazorComponents<App>()
|
||||
.AddInteractiveServerRenderMode();
|
||||
|
||||
app.Run();
|
||||
|
||||
static string DecodeJwtPayload(string jwt)
|
||||
{
|
||||
var parts = jwt.Split('.');
|
||||
if (parts.Length < 2) return "{}";
|
||||
var payload = parts[1];
|
||||
switch (payload.Length % 4)
|
||||
{
|
||||
case 2: payload += "=="; break;
|
||||
case 3: payload += "="; break;
|
||||
}
|
||||
var bytes = Convert.FromBase64String(payload);
|
||||
return Encoding.UTF8.GetString(bytes);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user