Files
pos-system/microservices/services/order-service-net/tests/OrderService.FunctionalTests/TestAuthHandler.cs
Ho Ngoc Hai 76d75c753b Migrate
2026-05-23 18:37:02 +07:00

69 lines
2.4 KiB
C#

// EN: Custom authentication handler for functional tests.
// VI: Authentication handler tùy chỉnh cho functional tests.
using System.Security.Claims;
using System.Text.Encodings.Web;
using Microsoft.AspNetCore.Authentication;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
namespace OrderService.FunctionalTests;
/// <summary>
/// EN: Test authentication handler that creates a fake authenticated user with configurable claims.
/// VI: Authentication handler test tạo user authenticated giả với claims có thể cấu hình.
/// </summary>
public class TestAuthHandler : AuthenticationHandler<AuthenticationSchemeOptions>
{
/// <summary>
/// EN: Authentication scheme name used in tests.
/// VI: Tên scheme xác thực sử dụng trong tests.
/// </summary>
public const string SchemeName = "TestScheme";
/// <summary>
/// EN: Default test user ID.
/// VI: User ID test mặc định.
/// </summary>
public static readonly Guid TestUserId = Guid.Parse("11111111-1111-1111-1111-111111111111");
/// <summary>
/// EN: Default test merchant ID.
/// VI: Merchant ID test mặc định.
/// </summary>
public static readonly Guid TestMerchantId = Guid.Parse("22222222-2222-2222-2222-222222222222");
/// <summary>
/// EN: Default test shop ID.
/// VI: Shop ID test mặc định.
/// </summary>
public static readonly Guid TestShopId = Guid.Parse("33333333-3333-3333-3333-333333333333");
public TestAuthHandler(
IOptionsMonitor<AuthenticationSchemeOptions> options,
ILoggerFactory logger,
UrlEncoder encoder)
: base(options, logger, encoder)
{
}
protected override Task<AuthenticateResult> HandleAuthenticateAsync()
{
var claims = new[]
{
new Claim(ClaimTypes.NameIdentifier, TestUserId.ToString()),
new Claim("sub", TestUserId.ToString()),
new Claim("merchant_id", TestMerchantId.ToString()),
new Claim("shop_id", TestShopId.ToString()),
new Claim(ClaimTypes.Role, "admin"),
new Claim("role", "admin"),
};
var identity = new ClaimsIdentity(claims, SchemeName);
var principal = new ClaimsPrincipal(identity);
var ticket = new AuthenticationTicket(principal, SchemeName);
return Task.FromResult(AuthenticateResult.Success(ticket));
}
}