c# - c# User.IsInRole 在单元测试中失败
问题描述
我有这个方法:
[HttpPut]
[AuthorizeClaim("field:write")]
[ApiConventionMethod(typeof(AttemptApiConventions), nameof(AttemptApiConventions.AttemptPut))]
public override async Task<ActionResult<Field>> UpdateAsync(Field model)
{
var getAttempt = await Mediator.Send(new GenericGet<Field>(model.Id));
if (getAttempt.Failure) return Ok(getAttempt);
var field = getAttempt.Result;
if (!field.IsSpecification && !User.IsInRole("Administrator"))
return Ok(new ForbiddenError(string.Format(Resources.PermissionError, "this field")).ToAttempt<Field>());
if (!field.IsSpecification && model.Name != field.Name)
return Ok(new ValidationError(string.Format(Resources.CannotBeChanged, nameof(Field.Name))).ToAttempt<Field>());
return await base.UpdateAsync(model);
}
如您所见,我检查User.IsInRole在尝试更改字段时是否显示不同的错误消息。问题是,我有这个单元测试:
[Test]
public async Task ReturnBadRequestIfSpecificationFieldNameChanges()
{
// Assemble
var model = new Field {Id = 1, IsSpecification = false, Name = "Test"};
var services = FieldsControllerContext.GivenServices();
var controller = services.WhenCreateController("Administrator");
services.Mediator.Send(Arg.Any<GenericGet<Field>>())
.Returns(new Field {Id = 1, IsSpecification = false, Name = "Old"});
// Act
var actionResult = await controller.UpdateAsync(model);
// Assert
actionResult.ShouldBeBadRequest(string.Format(Sxp.Web.Properties.Resources.CannotBeChanged, nameof(Field.Name)));
}
看看线services.WhenCreateController("Administrator");
。它正在传递我希望被模拟用户成为成员的角色。这是这样设置的:
public static class ControllerExtensions
{
public static T WithUser<T>(this T controller, string roles = null) where T: ControllerBase
{
var id = Guid.NewGuid().ToString();
var claims = new List<Claim>
{
new Claim(ClaimTypes.Name, "example name"),
new Claim(ClaimTypes.NameIdentifier, id),
new Claim(JwtClaimTypes.Subject, id),
};
if (!string.IsNullOrEmpty(roles))
{
var r = roles.Split(",");
claims.AddRange(r.Select(role => new Claim(JwtClaimTypes.Role, role)));
}
var user = new ClaimsPrincipal(new ClaimsIdentity(claims, "mock"));
controller.ControllerContext = new ControllerContext
{
HttpContext = new DefaultHttpContext
{
User = user
}
};
return controller;
}
}
当我调试我的测试时,我可以看到:
谁能告诉我为什么?
解决方案
我找到了答案。这条线是罪魁祸首:
claims.AddRange(r.Select(role => new Claim(JwtClaimTypes.Role, role)));
不是JwtClaimTypes
它检查,它实际上检查:
"http://schemas.microsoft.com/ws/2008/06/identity/claims/role"
推荐阅读
- ios - 如何使用 Apple Developer Account 创建一个在 ios10 和 ios12 上都可以信任的 ipa
- java - 并行运行多个 HystrixCommand 的最佳方式
- codeigniter-3 - 使用 Morris Bar 无法显示
- c++ - 如何解析 libcurl 在 IMAP 上的响应?
- javascript - HLS 代理和 CORS
- excel - VBA:空字典中的“Comparemode”错误
- pip - pkg_resources.DistributionNotFound:未找到“Sphinx==1.8.5”分布,应用程序需要该分布
- asp.net-core - Entity FrameWorkCore 一对多外键关系
- css - CSS 中的这段代码将背景图像堆叠在一起。为什么?
- tkinter - tkinter 画布矩形使用项目配置调整大小