65 lines
2.0 KiB
C#
65 lines
2.0 KiB
C#
using System.Security.Claims;
|
||
using System.Text.Encodings.Web;
|
||
using Microsoft.AspNetCore.Authentication;
|
||
using Microsoft.Extensions.Logging;
|
||
using Microsoft.Extensions.Options;
|
||
|
||
namespace XiangYi.Api.Tests.AppApi;
|
||
|
||
/// <summary>
|
||
/// 测试用认证处理器
|
||
/// </summary>
|
||
public class TestAuthHandler : AuthenticationHandler<AuthenticationSchemeOptions>
|
||
{
|
||
public const string AuthenticationScheme = "TestScheme";
|
||
public const string TestUserId = "1";
|
||
|
||
public TestAuthHandler(
|
||
IOptionsMonitor<AuthenticationSchemeOptions> options,
|
||
ILoggerFactory logger,
|
||
UrlEncoder encoder)
|
||
: base(options, logger, encoder)
|
||
{
|
||
}
|
||
|
||
protected override Task<AuthenticateResult> HandleAuthenticateAsync()
|
||
{
|
||
// 检查是否有Authorization头
|
||
if (!Request.Headers.ContainsKey("Authorization"))
|
||
{
|
||
return Task.FromResult(AuthenticateResult.NoResult());
|
||
}
|
||
|
||
var authHeader = Request.Headers["Authorization"].ToString();
|
||
if (string.IsNullOrEmpty(authHeader) || !authHeader.StartsWith("Bearer "))
|
||
{
|
||
return Task.FromResult(AuthenticateResult.Fail("Invalid Authorization header"));
|
||
}
|
||
|
||
var token = authHeader.Substring("Bearer ".Length).Trim();
|
||
if (string.IsNullOrEmpty(token))
|
||
{
|
||
return Task.FromResult(AuthenticateResult.Fail("No token provided"));
|
||
}
|
||
|
||
// 从token中解析用户ID(测试用,格式:test-token-{userId})
|
||
var userId = TestUserId;
|
||
if (token.StartsWith("test-token-"))
|
||
{
|
||
userId = token.Substring("test-token-".Length);
|
||
}
|
||
|
||
var claims = new[]
|
||
{
|
||
new Claim(ClaimTypes.NameIdentifier, userId),
|
||
new Claim(ClaimTypes.Name, "TestUser"),
|
||
};
|
||
|
||
var identity = new ClaimsIdentity(claims, AuthenticationScheme);
|
||
var principal = new ClaimsPrincipal(identity);
|
||
var ticket = new AuthenticationTicket(principal, AuthenticationScheme);
|
||
|
||
return Task.FromResult(AuthenticateResult.Success(ticket));
|
||
}
|
||
}
|