using System.Security.Claims;
using System.Text.Encodings.Web;
using Microsoft.AspNetCore.Authentication;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
namespace Books.Api.Tests.Infrastructure;
///
/// Test authentication handler that auto-authenticates all requests.
/// Used in integration tests to simulate an authenticated user.
///
public class TestAuthenticationHandler : AuthenticationHandler
{
public const string TestScheme = "TestScheme";
public const string TestUserId = "test-user-001";
public const string TestUserEmail = "test@example.com";
public const string TestUserName = "Test User";
public TestAuthenticationHandler(
IOptionsMonitor options,
ILoggerFactory logger,
UrlEncoder encoder)
: base(options, logger, encoder)
{
}
protected override Task HandleAuthenticateAsync()
{
var claims = new[]
{
new Claim(ClaimTypes.NameIdentifier, TestUserId),
new Claim(ClaimTypes.Email, TestUserEmail),
new Claim(ClaimTypes.Name, TestUserName),
new Claim(ClaimTypes.Role, "user"),
};
var identity = new ClaimsIdentity(claims, TestScheme);
var principal = new ClaimsPrincipal(identity);
var ticket = new AuthenticationTicket(principal, TestScheme);
return Task.FromResult(AuthenticateResult.Success(ticket));
}
}