chore: group .NET into backend/ and drop non-.NET test artifacts
- Move all .NET (6 projects, solution, Directory.*.props, nuget.config) into backend/ so the monorepo root can host non-.NET projects later - Remove throwaway test artifacts: player.html, pl.json - Trim dead Flutter rules from .gitignore Build from backend/Musify.slnx: 0 warnings, 0 errors.
This commit is contained in:
@@ -0,0 +1,39 @@
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
|
||||
namespace Musify.Api.Authentication;
|
||||
|
||||
public sealed class AuthenticationConfiguration
|
||||
{
|
||||
public const string SectionName = "Authentication";
|
||||
|
||||
[Required]
|
||||
[Url]
|
||||
public required string MetadataAddress { get; set; }
|
||||
|
||||
[Required]
|
||||
public required string IssuerAddress { get; set; }
|
||||
|
||||
[Required]
|
||||
public required string AudienceAddress { get; set; }
|
||||
|
||||
[Required]
|
||||
public required string ClientId { get; set; }
|
||||
|
||||
public string? ClientSecret { get; set; }
|
||||
|
||||
[Required]
|
||||
[Url]
|
||||
public required string AuthorizationEndpoint { get; set; }
|
||||
|
||||
[Required]
|
||||
[Url]
|
||||
public required string TokenEndpoint { get; set; }
|
||||
|
||||
[Required]
|
||||
[MinLength(1)]
|
||||
public required string[] Scopes { get; set; }
|
||||
|
||||
public string? ScalarRedirectUri { get; set; }
|
||||
|
||||
public bool RequireHttpsMetadata { get; set; } = true;
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
using Microsoft.AspNetCore.Authentication.JwtBearer;
|
||||
using Microsoft.Extensions.Options;
|
||||
|
||||
namespace Musify.Api.Authentication;
|
||||
|
||||
public static class AuthenticationExtensions
|
||||
{
|
||||
public static IServiceCollection AddAuthenticationConfiguration(
|
||||
this IServiceCollection services,
|
||||
IConfiguration configuration)
|
||||
{
|
||||
services
|
||||
.AddOptionsWithValidateOnStart<AuthenticationConfiguration>()
|
||||
.Bind(configuration.GetRequiredSection(AuthenticationConfiguration.SectionName))
|
||||
.ValidateDataAnnotations();
|
||||
|
||||
services.AddSingleton(serviceProvider =>
|
||||
serviceProvider.GetRequiredService<IOptions<AuthenticationConfiguration>>().Value);
|
||||
|
||||
services.AddScoped<JwtBearerEventsHandler>();
|
||||
services.ConfigureOptions<JwtBearerOptionsSetup>();
|
||||
|
||||
services
|
||||
.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
|
||||
.AddJwtBearer();
|
||||
|
||||
services.AddAuthorization();
|
||||
|
||||
return services;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
using System.Reflection;
|
||||
using System.Security.Claims;
|
||||
|
||||
namespace Musify.Api.Authentication;
|
||||
|
||||
public sealed class CurrentUser : IBindableFromHttpContext<CurrentUser>
|
||||
{
|
||||
private CurrentUser(ClaimsPrincipal principal)
|
||||
{
|
||||
Principal = principal;
|
||||
var isAuthenticated = principal.Identity?.IsAuthenticated;
|
||||
IsAuthenticated = isAuthenticated.HasValue && isAuthenticated.Value;
|
||||
|
||||
var rawId = principal.FindFirstValue(ClaimTypes.NameIdentifier);
|
||||
if (long.TryParse(rawId, out var id) && id != 0)
|
||||
Id = id;
|
||||
|
||||
Username = principal.FindFirstValue(ClaimTypes.Name);
|
||||
FirstName = principal.FindFirstValue(ClaimTypes.GivenName);
|
||||
LastName = principal.FindFirstValue(ClaimTypes.Surname);
|
||||
}
|
||||
|
||||
public ClaimsPrincipal Principal { get; }
|
||||
|
||||
public bool IsAuthenticated { get; }
|
||||
|
||||
public long? Id { get; }
|
||||
|
||||
public string? Username { get; }
|
||||
|
||||
public string? FirstName { get; }
|
||||
|
||||
public string? LastName { get; }
|
||||
|
||||
public long RequiredId => Id ?? throw new InvalidOperationException("User Id claim is missing or invalid.");
|
||||
|
||||
public bool HasClaim(string type) => Principal.HasClaim(c => c.Type == type);
|
||||
|
||||
public string? FindClaim(string type) => Principal.FindFirstValue(type);
|
||||
|
||||
public static ValueTask<CurrentUser?> BindAsync(HttpContext context, ParameterInfo parameter) =>
|
||||
ValueTask.FromResult<CurrentUser?>(new CurrentUser(context.User));
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
using Mediator;
|
||||
using Microsoft.AspNetCore.Authentication.JwtBearer;
|
||||
using Musify.Application.Users.Commands;
|
||||
using System.Security.Claims;
|
||||
|
||||
namespace Musify.Api.Authentication;
|
||||
|
||||
public sealed class JwtBearerEventsHandler(IMediator mediator, ILogger<JwtBearerEventsHandler> logger) : JwtBearerEvents
|
||||
{
|
||||
public override async Task TokenValidated(TokenValidatedContext tokenValidatedContext)
|
||||
{
|
||||
var principal = tokenValidatedContext.Principal!;
|
||||
|
||||
var rawId = principal.FindFirstValue(ClaimTypes.NameIdentifier);
|
||||
if (!long.TryParse(rawId, out var userId))
|
||||
{
|
||||
logger.LogWarning("Token subject '{Subject}' is not a numeric id; skipping user provisioning", rawId);
|
||||
return;
|
||||
}
|
||||
|
||||
var username = principal.FindFirstValue(ClaimTypes.Name)
|
||||
?? principal.FindFirstValue("preferred_username")
|
||||
?? principal.FindFirstValue(ClaimTypes.Email)
|
||||
?? rawId!;
|
||||
|
||||
var firstName = principal.FindFirstValue(ClaimTypes.GivenName);
|
||||
var lastName = principal.FindFirstValue(ClaimTypes.Surname);
|
||||
var profilePictureUrl = principal.FindFirstValue("picture");
|
||||
|
||||
try
|
||||
{
|
||||
await mediator.Send(
|
||||
new SyncUserCommand(userId, username, firstName, lastName, profilePictureUrl),
|
||||
tokenValidatedContext.HttpContext.RequestAborted);
|
||||
}
|
||||
catch (Exception exception)
|
||||
{
|
||||
logger.LogError(exception, "Failed to sync user {UserId} during token validation", userId);
|
||||
}
|
||||
}
|
||||
|
||||
public override Task AuthenticationFailed(AuthenticationFailedContext context)
|
||||
{
|
||||
logger.LogWarning(context.Exception, "JWT authentication failed");
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
public override Task Challenge(JwtBearerChallengeContext context)
|
||||
{
|
||||
if (context.AuthenticateFailure is not null)
|
||||
logger.LogWarning("JWT challenge: {Error} - {Description}", context.Error, context.ErrorDescription);
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
using Microsoft.AspNetCore.Authentication.JwtBearer;
|
||||
using Microsoft.Extensions.Options;
|
||||
using Microsoft.IdentityModel.Tokens;
|
||||
using System.Security.Claims;
|
||||
|
||||
namespace Musify.Api.Authentication;
|
||||
|
||||
public sealed class JwtBearerOptionsSetup(IOptions<AuthenticationConfiguration> options)
|
||||
: IConfigureNamedOptions<JwtBearerOptions>
|
||||
{
|
||||
private readonly AuthenticationConfiguration _configuration = options.Value;
|
||||
|
||||
public void Configure(string? name, JwtBearerOptions options)
|
||||
{
|
||||
if (name != JwtBearerDefaults.AuthenticationScheme)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
Configure(options);
|
||||
}
|
||||
|
||||
public void Configure(JwtBearerOptions options)
|
||||
{
|
||||
options.MetadataAddress = _configuration.MetadataAddress;
|
||||
options.RequireHttpsMetadata = _configuration.RequireHttpsMetadata;
|
||||
options.Audience = _configuration.AudienceAddress;
|
||||
options.TokenValidationParameters = new TokenValidationParameters
|
||||
{
|
||||
ValidIssuer = _configuration.IssuerAddress,
|
||||
ValidAudience = _configuration.AudienceAddress,
|
||||
RoleClaimType = ClaimTypes.Role,
|
||||
NameClaimType = ClaimTypes.Name,
|
||||
};
|
||||
options.EventsType = typeof(JwtBearerEventsHandler);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user