31 lines
1.2 KiB
C#
31 lines
1.2 KiB
C#
using System.Security.Claims;
|
|
using System.Text.Encodings.Web;
|
|
using Microsoft.AspNetCore.Authentication;
|
|
using Microsoft.Extensions.Logging;
|
|
using Microsoft.Extensions.Options;
|
|
|
|
namespace Dotnet.Samples.AspNetCore.WebApi.Tests.Utilities;
|
|
|
|
/// <summary>
|
|
/// A test authentication handler that automatically authenticates every request,
|
|
/// bypassing the real authentication scheme. Used in integration tests to exercise
|
|
/// endpoints protected with [Authorize] without requiring a real token.
|
|
/// </summary>
|
|
internal sealed class TestAuthHandler(
|
|
IOptionsMonitor<AuthenticationSchemeOptions> options,
|
|
ILoggerFactory logger,
|
|
UrlEncoder encoder
|
|
) : AuthenticationHandler<AuthenticationSchemeOptions>(options, logger, encoder)
|
|
{
|
|
public const string SchemeName = "Test";
|
|
|
|
protected override Task<AuthenticateResult> HandleAuthenticateAsync()
|
|
{
|
|
var claims = new[] { new Claim(ClaimTypes.Name, "TestUser") };
|
|
var identity = new ClaimsIdentity(claims, SchemeName);
|
|
var principal = new ClaimsPrincipal(identity);
|
|
var ticket = new AuthenticationTicket(principal, SchemeName);
|
|
return Task.FromResult(AuthenticateResult.Success(ticket));
|
|
}
|
|
}
|