1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
|
// 模拟不同角色
public class RoleBasedTestAuthHandler : AuthenticationHandler<AuthenticationSchemeOptions>
{
private readonly string _role;
public RoleBasedTestAuthHandler(
IOptionsMonitor<AuthenticationSchemeOptions> options,
ILoggerFactory logger,
UrlEncoder encoder,
string role = "User") : base(options, logger, encoder)
{
_role = role;
}
protected override Task<AuthenticateResult> HandleAuthenticateAsync()
{
var claims = new[]
{
new Claim(ClaimTypes.NameIdentifier, "test-user"),
new Claim(ClaimTypes.Role, _role),
};
var identity = new ClaimsIdentity(claims, "TestScheme");
var principal = new ClaimsPrincipal(identity);
var ticket = new AuthenticationTicket(principal, "TestScheme");
return Task.FromResult(AuthenticateResult.Success(ticket));
}
}
// 测试
[Theory]
[InlineData("Admin", HttpStatusCode.OK)]
[InlineData("User", HttpStatusCode.Forbidden)]
public async Task AdminEndpoint_RoleCheck(string role, HttpStatusCode expectedStatus)
{
var factory = new RoleBasedWebApplicationFactory(role);
var client = factory.CreateClient();
var response = await client.GetAsync("/api/admin/settings");
Assert.Equal(expectedStatus, response.StatusCode);
}
|