yavsc/src/Yavsc.Org/Controllers/Administration/ClientController.cs

297 lines
10 KiB
C#
Raw Normal View History

2025-08-24 16:07:53 +01:00
using IdentityServer8.EntityFramework.DbContexts;
using IdentityServer8.EntityFramework.Entities;
2026-03-09 02:07:09 +00:00
using IdentityServer8.EntityFramework.Stores;
2025-08-24 16:07:53 +01:00
using Microsoft.AspNetCore.Authorization;
2023-03-19 17:57:55 +00:00
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;
2026-03-16 23:16:12 +00:00
using Microsoft.Extensions.Options;
2018-05-04 13:56:22 +02:00
using Yavsc.Models;
using Yavsc.Models.Auth;
2026-03-16 23:16:12 +00:00
using Yavsc.Server.Helpers;
2018-05-04 13:56:22 +02:00
namespace Yavsc.Controllers
{
2025-08-24 16:07:53 +01:00
[Authorize("AdministratorOnly")]
yavsc-org: OAuth2 client admin editor overhaul — per-collection pages + missing fields The OAuth2 client editor at /Client/Edit/{id} previously exposed 8 fields out of ~30 scalars and 10 collections on the IdentityServer8 Client entity. Editing the collections (RedirectUris, Scopes, Grant Types, Cors Origins, IdP Restrictions, Claims, Properties, Secrets) was either impossible or jammed into a single broken text input that bound against an IEnumerable<string> property. Restructure into per-collection subpages, each with its own list/add/remove flow: - RedirectUris /Client/EditRedirectUris/{id} - PostLogoutRedirectUris /Client/EditPostLogoutRedirectUris/{id} - Scopes /Client/EditScopes/{id} - GrantTypes /Client/EditGrantTypes/{id} - CorsOrigins /Client/EditCorsOrigins/{id} - IdPRestrictions /Client/EditIdPRestrictions/{id} - Claims /Client/EditClaims/{id} - Properties /Client/EditProperties/{id} - Secrets /Client/EditSecrets/{id} Implementation: - New partial class ClientController.Collections.cs with one GET/Add/Remove trio per collection. Add/Remove dispatch through generic helpers that handle the EF row + ClientId check. - Shared _EditableStringList.cshtml partial consumed by the six single-string-field collection pages. Uses reflection to pull the value field and the row Id off the entity — avoids six nearly-identical table+form copies. - Claims / Properties / Secrets each have their own view because they carry 2+ fields (Type+Value, Key+Value, or Type+Value+Description+Expiration). - Main Edit.cshtml enriched: ClientId/Id hidden, all scalar fields split into fieldsets (Core, Security, Logout, Tokens, Device flow, Tokens extra), nav links to the 9 subpages with current row counts as badges. - ClientController.Edit(int) GET now loads the client with all navigations via LoadClientAsync so the Edit.cshtml nav badges render real counts. Field-correctness notes (verified by disassembling HigginsSoft IdentityServer8.EntityFramework.Entities.Client 8.0.5-preview-net9): - The property is PairWiseSubjectSalt, not PairwiseSubjectSalt (capital W on 'Wise'). - CibaLifetime and PollingInterval do NOT exist on Client in this IdentityServer8 version — those properties were a guess. The Device flow fieldset contains DeviceCodeLifetime + UserCodeType instead. - AllowedIdentityTokenSigningAlgorithms and AllowAccessTokensViaBrowser were missing from the original form and are now exposed. - ConsentLifetime and UserSsoLifetime are int? (nullable); the form binds them as plain int fields which accept empty strings. Security: - All new actions stay under [Authorize('AdministratorOnly')]. - Each Add/Remove takes an explicit id (Client.Id) and the row's ClientId is checked on the server before any delete; a rowId from another client returns NotFound. Docs: - doc/dev-tracking/client-editor-overhaul.md — inventory, status, follow-up ideas (confirmation prompts, validation, MVC tests).
2026-06-21 16:53:34 +01:00
public partial class ClientController : Controller
2018-05-04 13:56:22 +02:00
{
2026-03-16 23:16:12 +00:00
private readonly ApplicationDbContext dbContext;
2026-03-09 02:07:09 +00:00
private readonly ClientStore clientStore;
2026-03-16 23:16:12 +00:00
private readonly SiteSettings siteSettings;
2018-05-04 13:56:22 +02:00
2026-03-16 23:16:12 +00:00
public ClientController(
ApplicationDbContext dbContext,
ClientStore clientStore, IOptions<SiteSettings> siteSettingsOptions
2026-03-09 02:07:09 +00:00
)
2018-05-04 13:56:22 +02:00
{
2026-03-16 23:16:12 +00:00
this.dbContext = dbContext;
2026-03-09 02:07:09 +00:00
this.clientStore = clientStore;
2026-03-16 23:16:12 +00:00
this.siteSettings = siteSettingsOptions.Value;
2018-05-04 13:56:22 +02:00
}
// GET: Client
public async Task<IActionResult> Index()
{
2026-03-16 23:16:12 +00:00
return View(await dbContext.Clients.Include(c => c.AllowedGrantTypes)
2026-03-09 02:07:09 +00:00
.Include(c => c.RedirectUris).ToListAsync());
2018-05-04 13:56:22 +02:00
}
// GET: Client/Details/5
2026-03-09 02:07:09 +00:00
public async Task<IActionResult> Details(int id)
2018-05-04 13:56:22 +02:00
{
2026-03-16 23:16:12 +00:00
Client client = await dbContext.Clients.Include(
2025-08-24 16:07:53 +01:00
c => c.ClientSecrets
2026-03-09 02:07:09 +00:00
).Include(c => c.AllowedGrantTypes)
.Include(c => c.RedirectUris)
.Include(c=>c.ClientSecrets)
.Include(c=>c.AllowedCorsOrigins)
.Include(c=>c.AllowedScopes)
.Include(c=>c.IdentityProviderRestrictions)
.Include(c=>c.PostLogoutRedirectUris)
.SingleAsync(m => m.Id == id);
2018-05-04 13:56:22 +02:00
if (client == null)
{
2023-03-19 17:57:55 +00:00
return NotFound();
2018-05-04 13:56:22 +02:00
}
return View(client);
}
// GET: Client/Create
public IActionResult Create()
{
SetAppTypesInputValues();
return View();
}
// POST: Client/Create
[HttpPost]
[ValidateAntiForgeryToken]
2026-03-16 23:16:12 +00:00
2018-05-04 13:56:22 +02:00
public async Task<IActionResult> Create(Client client)
{
if (ModelState.IsValid)
{
2026-03-09 02:07:09 +00:00
var model = await clientStore.FindClientByIdAsync(client.ClientId);
if (model != null)
{
ModelState.AddModelError("ClientId", "existent");
return BadRequest(ModelState);
}
2026-03-16 23:16:12 +00:00
dbContext.Clients.Add(client);
await dbContext.SaveChangesAsync(User.GetUserId());
dbContext.ClientRedirectUris.Add(new ClientRedirectUri
2026-03-09 02:07:09 +00:00
{
2026-03-16 23:16:12 +00:00
ClientId = client.Id,
Split Site:Audience into Site:ExternalUrl + Site:CorsAllowedOrigins The Site:Audience setting was conflating two distinct concepts: an OAuth JWT audience (a single resource identifier) and a CORS allow-list (an array of origins). Collapsing them caused several latent bugs: - OAuth/JWT validation expected a single string while CORS WithOrigins accepts an array. - Password-reset callback URLs and OAuth client RedirectUri/Origin were being built from what was meant to be an audience identifier, not a base URL. - Yavsc.Org's main CORS policy was hardcoded to '*', with no way to restrict it without code changes. Changes: - SiteSettings.Audience (string) replaced with CorsAllowedOrigins (IList<string>). - OAuth JWT Authority still reads Site:Authority; Audience now reads Site:ExternalUrl (Org only; Api/Blogs use ValidateAudience=false). - MailSender and AccountController build reset-callback URLs from Site:ExternalUrl. - ClientController uses Site:ExternalUrl for OAuth RedirectUri/Origin defaults on newly created clients. - Yavsc.Api and Yavsc.Blogs now read CORS origins from Site:CorsAllowedOrigins instead of hardcoded URLs. Add shared AddYavscCors / AddYavscJwtBearer extension methods in Yavsc.Server/Helpers/ServiceExtensions.cs to enforce a single configuration contract across all runtime services (Api, Blogs, Org). Fails closed when CorsAllowedOrigins is empty; fails fast at startup when Site:Authority is missing. Remove obsolete ConfigurationHelpers.GetAudience (no remaining callers). Local appsettings-*.json files (which carry deployment-specific values and are gitignored) must be updated to add Site:CorsAllowedOrigins.
2026-06-19 13:15:21 +01:00
RedirectUri = siteSettings.ExternalUrl
2026-03-16 23:16:12 +00:00
});
dbContext.ClientCorsOrigins.Add(new ClientCorsOrigin
{
ClientId = client.Id,
Split Site:Audience into Site:ExternalUrl + Site:CorsAllowedOrigins The Site:Audience setting was conflating two distinct concepts: an OAuth JWT audience (a single resource identifier) and a CORS allow-list (an array of origins). Collapsing them caused several latent bugs: - OAuth/JWT validation expected a single string while CORS WithOrigins accepts an array. - Password-reset callback URLs and OAuth client RedirectUri/Origin were being built from what was meant to be an audience identifier, not a base URL. - Yavsc.Org's main CORS policy was hardcoded to '*', with no way to restrict it without code changes. Changes: - SiteSettings.Audience (string) replaced with CorsAllowedOrigins (IList<string>). - OAuth JWT Authority still reads Site:Authority; Audience now reads Site:ExternalUrl (Org only; Api/Blogs use ValidateAudience=false). - MailSender and AccountController build reset-callback URLs from Site:ExternalUrl. - ClientController uses Site:ExternalUrl for OAuth RedirectUri/Origin defaults on newly created clients. - Yavsc.Api and Yavsc.Blogs now read CORS origins from Site:CorsAllowedOrigins instead of hardcoded URLs. Add shared AddYavscCors / AddYavscJwtBearer extension methods in Yavsc.Server/Helpers/ServiceExtensions.cs to enforce a single configuration contract across all runtime services (Api, Blogs, Org). Fails closed when CorsAllowedOrigins is empty; fails fast at startup when Site:Authority is missing. Remove obsolete ConfigurationHelpers.GetAudience (no remaining callers). Local appsettings-*.json files (which carry deployment-specific values and are gitignored) must be updated to add Site:CorsAllowedOrigins.
2026-06-19 13:15:21 +01:00
Origin = siteSettings.ExternalUrl
2026-03-16 23:16:12 +00:00
});
foreach (String credType in new String[] { "code", "client_credentials", "password" })
{
dbContext.ClientGrantTypes.Add(new ClientGrantType
2026-03-09 02:07:09 +00:00
{
2026-03-16 23:16:12 +00:00
ClientId = client.Id,
GrantType = credType
});
2026-03-09 02:07:09 +00:00
}
2026-03-16 23:16:12 +00:00
foreach (String scope in new String[] { "openid", "profile" })
{
dbContext.ClientScopes.Add(new ClientScope
{
ClientId = client.Id,
Scope = scope
});
}
await dbContext.SaveChangesAsync(User.GetUserId());
2026-03-09 02:07:09 +00:00
2018-05-04 13:56:22 +02:00
return RedirectToAction("Index");
}
SetAppTypesInputValues();
return View(client);
}
2026-03-09 02:07:09 +00:00
2018-05-04 13:56:22 +02:00
private void SetAppTypesInputValues()
{
2025-08-24 16:07:53 +01:00
IEnumerable<SelectListItem> types = new SelectListItem[] {
2018-05-04 13:56:22 +02:00
new SelectListItem {
Text = ApplicationTypes.JavaScript.ToString(),
Value = ((int) ApplicationTypes.JavaScript).ToString() },
new SelectListItem {
Text = ApplicationTypes.NativeConfidential.ToString(),
2025-08-24 16:07:53 +01:00
Value = ((int) ApplicationTypes.NativeConfidential).ToString()
2018-05-04 13:56:22 +02:00
}
};
2026-06-04 12:13:37 +01:00
ViewBag.AccessTokenType = types;
2018-05-04 13:56:22 +02:00
}
// GET: Client/Edit/5
2026-03-09 02:07:09 +00:00
public async Task<IActionResult> Edit(int id)
2018-05-04 13:56:22 +02:00
{
yavsc-org: OAuth2 client admin editor overhaul — per-collection pages + missing fields The OAuth2 client editor at /Client/Edit/{id} previously exposed 8 fields out of ~30 scalars and 10 collections on the IdentityServer8 Client entity. Editing the collections (RedirectUris, Scopes, Grant Types, Cors Origins, IdP Restrictions, Claims, Properties, Secrets) was either impossible or jammed into a single broken text input that bound against an IEnumerable<string> property. Restructure into per-collection subpages, each with its own list/add/remove flow: - RedirectUris /Client/EditRedirectUris/{id} - PostLogoutRedirectUris /Client/EditPostLogoutRedirectUris/{id} - Scopes /Client/EditScopes/{id} - GrantTypes /Client/EditGrantTypes/{id} - CorsOrigins /Client/EditCorsOrigins/{id} - IdPRestrictions /Client/EditIdPRestrictions/{id} - Claims /Client/EditClaims/{id} - Properties /Client/EditProperties/{id} - Secrets /Client/EditSecrets/{id} Implementation: - New partial class ClientController.Collections.cs with one GET/Add/Remove trio per collection. Add/Remove dispatch through generic helpers that handle the EF row + ClientId check. - Shared _EditableStringList.cshtml partial consumed by the six single-string-field collection pages. Uses reflection to pull the value field and the row Id off the entity — avoids six nearly-identical table+form copies. - Claims / Properties / Secrets each have their own view because they carry 2+ fields (Type+Value, Key+Value, or Type+Value+Description+Expiration). - Main Edit.cshtml enriched: ClientId/Id hidden, all scalar fields split into fieldsets (Core, Security, Logout, Tokens, Device flow, Tokens extra), nav links to the 9 subpages with current row counts as badges. - ClientController.Edit(int) GET now loads the client with all navigations via LoadClientAsync so the Edit.cshtml nav badges render real counts. Field-correctness notes (verified by disassembling HigginsSoft IdentityServer8.EntityFramework.Entities.Client 8.0.5-preview-net9): - The property is PairWiseSubjectSalt, not PairwiseSubjectSalt (capital W on 'Wise'). - CibaLifetime and PollingInterval do NOT exist on Client in this IdentityServer8 version — those properties were a guess. The Device flow fieldset contains DeviceCodeLifetime + UserCodeType instead. - AllowedIdentityTokenSigningAlgorithms and AllowAccessTokensViaBrowser were missing from the original form and are now exposed. - ConsentLifetime and UserSsoLifetime are int? (nullable); the form binds them as plain int fields which accept empty strings. Security: - All new actions stay under [Authorize('AdministratorOnly')]. - Each Add/Remove takes an explicit id (Client.Id) and the row's ClientId is checked on the server before any delete; a rowId from another client returns NotFound. Docs: - doc/dev-tracking/client-editor-overhaul.md — inventory, status, follow-up ideas (confirmation prompts, validation, MVC tests).
2026-06-21 16:53:34 +01:00
Client? client = await LoadClientAsync(id);
if (client is null)
2018-05-04 13:56:22 +02:00
{
2023-03-19 17:57:55 +00:00
return NotFound();
2018-05-04 13:56:22 +02:00
}
SetAppTypesInputValues();
return View(client);
}
// POST: Client/Edit/5
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(Client client)
{
if (ModelState.IsValid)
{
2026-03-09 02:07:09 +00:00
if (client.ClientSecrets != null)
{
foreach (var secret in client.ClientSecrets)
{
2026-03-16 23:16:12 +00:00
dbContext.Update(secret);
2026-03-09 02:07:09 +00:00
}
}
2026-03-16 23:16:12 +00:00
dbContext.Update(client);
await dbContext.SaveChangesAsync();
2018-05-04 13:56:22 +02:00
return RedirectToAction("Index");
}
return View(client);
}
// GET: Client/Delete/5
[ActionName("Delete")]
2026-03-09 02:07:09 +00:00
public async Task<IActionResult> Delete(int id)
2018-05-04 13:56:22 +02:00
{
2026-03-16 23:16:12 +00:00
Client client = await dbContext.Clients.SingleOrDefaultAsync(m => m.Id == id);
2018-05-04 13:56:22 +02:00
if (client == null)
{
2023-03-19 17:57:55 +00:00
return NotFound();
2018-05-04 13:56:22 +02:00
}
return View(client);
}
// POST: Client/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
2026-03-09 02:07:09 +00:00
public async Task<IActionResult> DeleteConfirmed(int id)
2018-05-04 13:56:22 +02:00
{
2026-03-16 23:16:12 +00:00
Client client = await dbContext.Clients
2026-03-09 02:07:09 +00:00
.Include(client => client.ClientSecrets)
.SingleAsync(m => m.Id == id);
2026-03-16 23:16:12 +00:00
dbContext.Clients.Remove(client);
await dbContext.SaveChangesAsync();
2018-05-04 13:56:22 +02:00
return RedirectToAction("Index");
}
2026-06-19 01:36:08 +01:00
// GET: Client/RegenerateSecret/5
[ActionName("RegenerateSecret")]
public async Task<IActionResult> RegenerateSecretGet(int id)
{
Client client = await dbContext.Clients
.Include(c => c.ClientSecrets)
.SingleOrDefaultAsync(m => m.Id == id);
if (client == null)
{
return NotFound();
}
return View("RegenerateSecret", client);
}
// POST: Client/RegenerateSecret/5
[HttpPost, ActionName("RegenerateSecret")]
[ValidateAntiForgeryToken]
public async Task<IActionResult> RegenerateSecretConfirmed(int id)
{
Client client = await dbContext.Clients
.Include(c => c.ClientSecrets)
.SingleOrDefaultAsync(m => m.Id == id);
if (client == null)
{
return NotFound();
}
// Generate a fresh secret in clear text. We display it to the admin
// once, then IdentityServer will hash it on SaveChanges.
var newSecret = GenerateRawClientSecret();
var now = DateTime.UtcNow;
var expiration = now.AddDays(90);
// Replace: drop existing secrets and add the freshly generated one.
if (client.ClientSecrets != null && client.ClientSecrets.Count > 0)
{
dbContext.ClientSecrets.RemoveRange(client.ClientSecrets);
}
client.ClientSecrets = new List<ClientSecret>
{
new ClientSecret
{
ClientId = client.Id,
Client = client,
Type = "SharedSecret",
Value = newSecret,
Description = $"Regenerated on {now:yyyy-MM-dd HH:mm:ss} UTC",
Created = now,
Expiration = expiration
}
};
dbContext.Update(client);
await dbContext.SaveChangesAsync(User.GetUserId());
// Flash the secret through TempData so the next request can render
// it exactly once, then it is gone forever (IdentityServer stores
// it hashed).
TempData["NewClientSecret"] = newSecret;
TempData["NewClientSecretExpiresAt"] = expiration.ToString("u");
TempData["NewClientSecretClientName"] = client.ClientName ?? client.ClientId;
return RedirectToAction("ShowSecret", new { id = client.Id });
}
// GET: Client/ShowSecret/5
public IActionResult ShowSecret(int id)
{
var secret = TempData["NewClientSecret"] as string;
if (string.IsNullOrEmpty(secret))
{
// The one-shot window is closed. Refuse to render anything
// sensitive and bounce back to the details page.
return RedirectToAction("Details", new { id });
}
// TempData.Keep would persist to the next request; we deliberately
// do NOT keep it so the value cannot be replayed.
ViewBag.NewClientSecret = secret;
ViewBag.NewClientSecretExpiresAt = TempData["NewClientSecretExpiresAt"] as string;
ViewBag.NewClientSecretClientName = TempData["NewClientSecretClientName"] as string;
ViewBag.ClientId = id;
return View();
}
private static string GenerateRawClientSecret()
{
// 32 bytes => 43 url-safe base64 chars without padding. Enough entropy
// for a client secret; readable enough to copy/paste once.
var bytes = new byte[32];
System.Security.Cryptography.RandomNumberGenerator.Fill(bytes);
return Convert.ToBase64String(bytes)
.TrimEnd('=')
.Replace('+', '-')
.Replace('/', '_');
}
2018-05-04 13:56:22 +02:00
}
}