asp.net-core-2.0 - 使用 Identity Server 时测试 Web API 控制器
问题描述
我有兴趣测试对 web api 进行的特定调用,以确保它执行我期望它执行的操作。在控制器中,我正在根据当前登录的用户 ID 搜索一些信息(授权由身份服务器处理)。运行该测试时,我希望已经有一个经过身份验证和登录的用户。如何模拟/绕过 Identity 进行的整个授权过程?
解决方案
当您在 Web api 项目中正确设置身份验证处理程序时,来自访问令牌的声明将填充到 HttpContext 的用户对象中:
services.AddAuthentication(options =>
{
options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(options =>
{
options.Authority = "https://<youridentityserver>";
options.Audience = "yourapi";
options.SaveToken = true;
});
public async Task<ActionResult> Get(string userName)
{
//Does the subject claim match the user name?
var subject = HttpContext.User.FindFirst(ClaimTypes.NameIdentifier);
if ((subject == null) || (subject.Value != userName))
return Unauthorized();
}
通过在单元测试中模拟 HttpContext,您可以在控制器方法中检查 User 对象。如何模拟 HttpContext:
推荐阅读
- html - 为什么 nth-child 选择器在 css 中不起作用?
- linux - 为什么 React Native 会挂在 59% 上?
- c# - 等效于 C# 中的 C++“this”指针
- java - java合并两个List
- android - Android - 仅启用 URL 链接,但在触及 TextView 中的非 URL 链接时禁用其他链接
- bash - How to write String to a text File
- python - 使用索引列表对numpy数组的元素执行操作
- java - 读取对象类java实例的属性
- swift - 在模拟器中启用 CoreLocation
- node.js - 在树枝模板中使用 Metalsmith 全局元数据