且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何从ASP.NET Web API中的身份声明获取JWT身份验证的登录用户

更新时间:2023-02-17 11:10:15

  • 您不应添加user.Id作为声明.干什么用的?
  • 您不应添加user.Email作为声明.做什么的 ?用户名==电子邮件
  • 现在,您可以在通过Authorize属性注释的Web Api端点中编写如下代码:

    • You shouldn't add user.Id as a claim. What for ?
    • You shouldn't add user.Email as a claim. What for ? UserName == Email
    • Now you can, in your Web Api end point annotated by Authorize attribute, code something like this:

      var userName = HttpContext.User.Identity.Name.ToString();
      var user= userManager.FindByNameAsync(userName);
      
      var staff = applicationDbContext.Staffs.Where(m => m.ApplicationUser.Id == 
      user.Id);
      
      return await staffs.ToListAsync();
      

    • 注意:无需使用HttpContextAccessor ... HttpContext在控制器中可用

      Note: No need to use HttpContextAccessor... HttpContext is available in the controller

      此处的代码与您的代码非常相似.它从HttpContext中解脱用户名,调用FindByNameAsync检索用户,然后使用它.

      The code here is very similar to yours. It extricates the user name from the HttpContext, call the FindByNameAsync to retrieve the user, and then use it.

      请运行它,并报告其是否正常.如果没有,请报告该问题.

      Please, run it and report if its OK. If not, report the issue.

      更新: 如果希望将用户ID添加到Jwt令牌,除了用户名外,还应该在Login方法中执行以下操作:

      Update: If you wish to add the user Id to the Jwt token, in addition to the user name, you should do the following in your Login method:

    claims.Add(new Claim(ClaimTypes.Name, login.UserName));
     claims.Add(new Claim(ClaimTypes.NameIdentifier, user.Id));
    

    要从GetAllStaffServices方法获取用户ID,可以调用UserManager.GetUserId,并将从HttpContext中提取的声明主体对象传递给它:

    And to get the user id from the GetAllStaffServices method, you can call UserManager.GetUserId, passing it a claims principal object extracted from HttpContext:

    var userId = UserManager.GetUserId (HttpContext.User);