首页 > 解决方案 > 使用 Identity Server 时测试 Web API 控制器

问题描述

我有兴趣测试对 web api 进行的特定调用,以确保它执行我期望它执行的操作。在控制器中,我正在根据当前登录的用户 ID 搜索一些信息(授权由身份服务器处理)。运行该测试时,我希望已经有一个经过身份验证和登录的用户。如何模拟/绕过 Identity 进行的整个授权过程?

标签: asp.net-core-2.0identityserver4

解决方案


当您在 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:

用于单元测试 .NET 核心 MVC 控制器的模拟 HttpContext?


推荐阅读