fix(identity): corrige JWT role claims, password policy, et consistency
- JWT role claims: string.Join -> ClaimTypes.Role individuels (debloque [Authorize(Roles)])\n- Password policy: RequireUppercase=true, RequireNonAlphanumeric=true\n- JWT validation params extraits en methode partagee (anti-duplication)\n- Retours 401 uniformises avec body structure\n- Champ Langue ajoute dans le dialog d'edition utilisateur\n\nBuild: 0 errors, 0 warnings\nTests: 226/226 passed
This commit is contained in:
1 parent
af8c7aa037
commit
940e826865
6 files changed
+38
-33
No files matched your search
@@ -55,8 +55,8 @@ public static class DependencyInjection
|
||||
options.Password.RequiredLength = 12;
|
||||
options.Password.RequireDigit = true;
|
||||
options.Password.RequireLowercase = true;
|
||||
options.Password.RequireUppercase = false;
|
||||
options.Password.RequireNonAlphanumeric = false;
|
||||
options.Password.RequireUppercase = true;
|
||||
options.Password.RequireNonAlphanumeric = true;
|
||||
options.Lockout.MaxFailedAccessAttempts = 5;
|
||||
options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(15);
|
||||
})
|
||||
|
||||
@@ -42,9 +42,12 @@ public class JwtService : IJwtService
|
||||
new(JwtRegisteredClaimNames.Sub, user.Id.ToString()),
|
||||
new(JwtRegisteredClaimNames.Email, user.Email ?? ""),
|
||||
new(JwtRegisteredClaimNames.Name, user.DisplayName),
|
||||
new("role", string.Join(",", roles)),
|
||||
};
|
||||
|
||||
// Add individual role claims so [Authorize(Roles = "Admin")] works
|
||||
foreach (var role in roles)
|
||||
claims.Add(new Claim(ClaimTypes.Role, role));
|
||||
|
||||
foreach (var permission in permissions)
|
||||
{
|
||||
claims.Add(new Claim("permission", permission));
|
||||
|
||||
@@ -145,6 +145,10 @@ else
|
||||
Class="mb-4" Immediate="true" />
|
||||
<MudTextField @bind-Value="_editTheme" Label="Thème" Variant="Variant.Outlined"
|
||||
Class="mb-4" Immediate="true" HelperText="Light, Dark ou Auto" />
|
||||
<MudSelect @bind-Value="_editLanguage" Label="Langue" Variant="Variant.Outlined" Class="mb-4" Immediate="true">
|
||||
<MudSelectItem Value="@("fr")">Français</MudSelectItem>
|
||||
<MudSelectItem Value="@("en")">English</MudSelectItem>
|
||||
</MudSelect>
|
||||
|
||||
@* Section: Rôles (multi-sélection) *@
|
||||
<MudText Typo="Typo.subtitle1" Class="mb-2 mt-4">Rôles</MudText>
|
||||
@@ -268,6 +272,7 @@ else
|
||||
private bool _showEdit;
|
||||
private string _editDisplayName = "";
|
||||
private string _editTheme = "";
|
||||
private string _editLanguage = "fr";
|
||||
private bool _editRoleAdmin;
|
||||
private bool _editRoleSupervisor;
|
||||
private bool _editRoleViewer;
|
||||
@@ -334,6 +339,7 @@ else
|
||||
_editUser = user;
|
||||
_editDisplayName = user.DisplayName;
|
||||
_editTheme = user.Theme ?? "Auto";
|
||||
_editLanguage = user.Language;
|
||||
_editRoleAdmin = user.Roles?.Contains("Admin") == true;
|
||||
_editRoleSupervisor = user.Roles?.Contains("Supervisor") == true;
|
||||
_editRoleViewer = user.Roles?.Contains("Viewer") == true;
|
||||
@@ -369,7 +375,7 @@ else
|
||||
return;
|
||||
}
|
||||
|
||||
await Api.UpdateUserAsync(_editUser.Id, _editDisplayName, _editTheme, null);
|
||||
await Api.UpdateUserAsync(_editUser.Id, _editDisplayName, _editTheme, _editLanguage);
|
||||
await Api.AssignRolesAsync(_editUser.Id, selectedRoles);
|
||||
Snackbar.Add("Utilisateur mis à jour", Severity.Success);
|
||||
CloseEdit();
|
||||
|
||||
@@ -86,7 +86,7 @@ public class AuthController : ControllerBase
|
||||
{
|
||||
var userIdClaim = User.FindFirstValue(ClaimTypes.NameIdentifier);
|
||||
if (userIdClaim is null || !Guid.TryParse(userIdClaim, out var userId))
|
||||
return Unauthorized();
|
||||
return Unauthorized(new { error = "Invalid user identity" });
|
||||
|
||||
var result = await _authService.ChangePasswordAsync(
|
||||
userId, request.CurrentPassword, request.NewPassword, ct);
|
||||
@@ -120,7 +120,7 @@ public class AuthController : ControllerBase
|
||||
{
|
||||
var userIdClaim = User.FindFirstValue(ClaimTypes.NameIdentifier);
|
||||
if (userIdClaim is null || !Guid.TryParse(userIdClaim, out var userId))
|
||||
return Unauthorized();
|
||||
return Unauthorized(new { error = "Invalid user identity" });
|
||||
|
||||
await _authService.LogoutAsync(userId, request.RefreshToken, ct);
|
||||
return Ok();
|
||||
|
||||
@@ -41,7 +41,7 @@ public class UsersController : ControllerBase
|
||||
{
|
||||
var userIdClaim = User.FindFirstValue(ClaimTypes.NameIdentifier);
|
||||
if (userIdClaim is null || !Guid.TryParse(userIdClaim, out var userId))
|
||||
return Unauthorized();
|
||||
return Unauthorized(new { error = "Invalid user identity" });
|
||||
|
||||
var result = await _userService.GetByIdAsync(userId, ct);
|
||||
return result.IsSuccess
|
||||
@@ -60,7 +60,7 @@ public class UsersController : ControllerBase
|
||||
{
|
||||
var userIdClaim = User.FindFirstValue(ClaimTypes.NameIdentifier);
|
||||
if (userIdClaim is null || !Guid.TryParse(userIdClaim, out var userId))
|
||||
return Unauthorized();
|
||||
return Unauthorized(new { error = "Invalid user identity" });
|
||||
|
||||
var result = await _userService.UpdateAsync(userId, request, ct);
|
||||
return result.IsSuccess
|
||||
@@ -161,7 +161,7 @@ public class UsersController : ControllerBase
|
||||
{
|
||||
var userIdClaim = User.FindFirstValue(ClaimTypes.NameIdentifier);
|
||||
if (userIdClaim is null || !Guid.TryParse(userIdClaim, out var currentUserId))
|
||||
return Unauthorized();
|
||||
return Unauthorized(new { error = "Invalid user identity" });
|
||||
|
||||
var result = await _userService.DeleteAsync(id, currentUserId, ct);
|
||||
return result.IsSuccess
|
||||
|
||||
+20
-24
@@ -54,6 +54,20 @@ var jwtKey = builder.Configuration["Jwt:Key"]
|
||||
var jwtIssuer = builder.Configuration["Jwt:Issuer"] ?? Environment.GetEnvironmentVariable("JWT__ISSUER") ?? "heimdall";
|
||||
var jwtAudience = builder.Configuration["Jwt:Audience"] ?? Environment.GetEnvironmentVariable("JWT__AUDIENCE") ?? "heimdall-api";
|
||||
|
||||
// Shared JWT validation parameters — used by both AddJwtBearer and /_auth/signin.
|
||||
// Extracted to a single location to prevent configuration drift (single source of truth).
|
||||
static TokenValidationParameters GetJwtValidationParameters(string key, string issuer, string audience) => new()
|
||||
{
|
||||
ValidateIssuerSigningKey = true,
|
||||
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(key)),
|
||||
ValidateIssuer = true,
|
||||
ValidIssuer = issuer,
|
||||
ValidateAudience = true,
|
||||
ValidAudience = audience,
|
||||
ValidateLifetime = true,
|
||||
ClockSkew = TimeSpan.Zero
|
||||
};
|
||||
|
||||
builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
|
||||
.AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, options =>
|
||||
{
|
||||
@@ -69,17 +83,7 @@ builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationSc
|
||||
})
|
||||
.AddJwtBearer("JwtBearer", options =>
|
||||
{
|
||||
options.TokenValidationParameters = new TokenValidationParameters
|
||||
{
|
||||
ValidateIssuerSigningKey = true,
|
||||
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtKey)),
|
||||
ValidateIssuer = true,
|
||||
ValidIssuer = jwtIssuer,
|
||||
ValidateAudience = true,
|
||||
ValidAudience = jwtAudience,
|
||||
ValidateLifetime = true,
|
||||
ClockSkew = TimeSpan.Zero
|
||||
};
|
||||
options.TokenValidationParameters = GetJwtValidationParameters(jwtKey, jwtIssuer, jwtAudience);
|
||||
|
||||
// SignalR WebSocket transport sends JWT as access_token query parameter
|
||||
options.Events = new JwtBearerEvents
|
||||
@@ -297,22 +301,14 @@ app.MapPost("/_auth/signin", async (HttpContext httpContext, SignInRequest reque
|
||||
}
|
||||
|
||||
// Validate the JWT server-side — extract claims from the validated token, not from client
|
||||
// Uses the same GetJwtValidationParameters() as AddJwtBearer (single source of truth).
|
||||
try
|
||||
{
|
||||
var handler = new JwtSecurityTokenHandler();
|
||||
var validationParams = new TokenValidationParameters
|
||||
{
|
||||
ValidateIssuerSigningKey = true,
|
||||
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtKey)),
|
||||
ValidateIssuer = true,
|
||||
ValidIssuer = jwtIssuer,
|
||||
ValidateAudience = true,
|
||||
ValidAudience = jwtAudience,
|
||||
ValidateLifetime = true,
|
||||
ClockSkew = TimeSpan.Zero
|
||||
};
|
||||
|
||||
var principal = handler.ValidateToken(request.AccessToken, validationParams, out _);
|
||||
var principal = handler.ValidateToken(
|
||||
request.AccessToken,
|
||||
GetJwtValidationParameters(jwtKey, jwtIssuer, jwtAudience),
|
||||
out _);
|
||||
|
||||
// Extract claims from the validated JWT only
|
||||
var userId = principal.FindFirst(ClaimTypes.NameIdentifier)?.Value;
|
||||
|
||||
Reference in new issue
Block a user