【问题标题】:Test Web API controller when using Identity Server使用 Identity Server 时测试 Web API 控制器
【发布时间】:2018-10-05 13:52:27
【问题描述】:

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

【问题讨论】:

    标签: asp.net-core-2.0 identityserver4


    【解决方案1】:

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

    Mock HttpContext for unit testing a .NET core MVC controller?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-06-02
      • 1970-01-01
      相关资源
      最近更新 更多