ASP.NET核心身份 - 获取当前用户

时间:2016-08-03 18:57:33

标签: c# asp.net-core asp.net-core-mvc asp.net-identity

要在MVC5中获取当前登录的用户,我们所要做的就是:

using Microsoft.AspNet.Identity;
[Authorize]
public IHttpActionResult DoSomething() {
    string currentUserId = User.Identity.GetUserId();
}

现在,使用ASP.NET Core我认为这应该可行,但它会引发错误。

using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Http;

private readonly UserManager<ApplicationUser> _userManager;
[HttpPost]
[Authorize]
public async Task<IActionResult> StartSession() {
    var curUser = await _userManager.GetUserAsync(HttpContext.User);
}

有什么想法吗?

编辑: Gerardo的回复正在进行中,但要获得用户的实际“ID”,这似乎有效:

ClaimsPrincipal currentUser = this.User;
var currentUserID = currentUser.FindFirst(ClaimTypes.NameIdentifier).Value;

7 个答案:

答案 0 :(得分:84)

假设您的代码在MVC控制器内:

public class MyController : Microsoft.AspNetCore.Mvc.Controller

Controller基类,您可以从IClaimsPrincipal属性获取User

System.Security.Claims.ClaimsPrincipal currentUser = this.User;

您可以直接查看索赔(无需往返数据库):

bool IsAdmin = currentUser.IsInRole("Admin");
var id = _userManager.GetUserId(User); // Get user id:

可以从数据库的用户实体中获取其他字段:

  1. 使用依赖注入获取用户管理器

    private UserManager<ApplicationUser> _userManager;
    
    //class constructor
    public MyController(UserManager<ApplicationUser> userManager)
    {
        _userManager = userManager;
    }
    
  2. 并使用它:

    var user = await _userManager.GetUserAsync(User);
    var email = user.Email;
    

答案 1 :(得分:18)

如果您使用的是Bearing Token Auth,则上述示例不会返回应用程序用户。

相反,请使用:

ClaimsPrincipal currentUser = this.User;
var currentUserName = currentUser.FindFirst(ClaimTypes.NameIdentifier).Value;
ApplicationUser user = await _userManager.FindByNameAsync(currentUserName);

这适用于apsnetcore 2.0。没有在早期版本中尝试过。

答案 2 :(得分:6)

对于上下文,我使用ASP.NET Core 2 Web应用程序模板创建了一个项目。然后,选择Web应用程序(MVC),然后单击“更改身份验证”按钮并选择“个人用户帐户”。

此模板为您构建了大量基础架构。在Controllers文件夹中找到 name test1 test2 select value 1 student1 50 30 test2 30 2 student2 30 20 test1 30 3 student3 20 15 test2 15 4 student4 6 10 test1 6

ManageController类构造函数需要填充此UserManager变量:

ManageController

然后,看看这个类中的[HttpPost] Index方法。他们以这种方式获得当前用户:

private readonly UserManager<ApplicationUser> _userManager;

作为奖励说明,您可以在此处将任何自定义字段更新为您已添加到AspNetUsers表的用户个人资料。将字段添加到视图,然后将这些值提交到IndexViewModel,然后将其提交给此Post方法。我在默认逻辑之后添加了此代码来设置电子邮件地址和电话号码:

var user = await _userManager.GetUserAsync(User);

答案 3 :(得分:5)

在.NET Core 2.0中,用户已作为底层继承控制器的一部分存在。只需像平常一样使用用户或传递给任何存储库代码。

<p class="qualify" style="display:none;">You have a sufficient amount of leaseholders to qualify for Right to Manage</p>
<p class="count" style="display:none;">You need <span id="remaining"></span> more consenting leaseholders to qualify</p>
<p class="surprise" style="display:none;"> r < 0 : What do you want to do here ?</p>

这是从

继承它的地方
[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme, Policy = "TENANT")]
[HttpGet("issue-type-selection"), Produces("application/json")]
public async Task<IActionResult> IssueTypeSelection()
{
    try
    {
        return new ObjectResult(await _item.IssueTypeSelection(User));
    }
    catch (ExceptionNotFound)
    {
        Response.StatusCode = (int)HttpStatusCode.BadRequest;
        return Json(new
        {
            error = "invalid_grant",
            error_description = "Item Not Found"
        });
    }
}

答案 4 :(得分:1)

private readonly UserManager<AppUser> _userManager;

 public AccountsController(UserManager<AppUser> userManager)
 {
            _userManager = userManager;
 }

[Authorize(Policy = "ApiUser")]
[HttpGet("api/accounts/GetProfile", Name = "GetProfile")]
public async Task<IActionResult> GetProfile()
{
   var userId = ((ClaimsIdentity)User.Identity).FindFirst("Id").Value;
   var user = await _userManager.FindByIdAsync(userId);

   ProfileUpdateModel model = new ProfileUpdateModel();
   model.Email = user.Email;
   model.FirstName = user.FirstName;
   model.LastName = user.LastName;
   model.PhoneNumber = user.PhoneNumber;

   return new OkObjectResult(model);
}

答案 5 :(得分:0)

我已经在Controller类中添加了类似的内容,并且效果很好:

IdentityUser user = await userManager.FindByNameAsync(HttpContext.User.Identity.Name);

其中,userManager是Microsoft.AspNetCore.Identity.UserManager类的实例(带有所有与此相关的怪异设置)。

答案 6 :(得分:0)

只要有兴趣,这对我有用。我有一个使用int作为主键的自定义标识,因此我覆盖了GetUserAsync方法

覆盖GetUserAsync

public override Task<User> GetUserAsync(ClaimsPrincipal principal)
{
    var userId = GetUserId(principal);
    return FindByNameAsync(userId);
}

获取身份用户

var user = await _userManager.GetUserAsync(User);

如果您使用常规的Guid主键,则无需覆盖GetUserAsync。所有这些都假设您的令牌已正确配置。

public async Task<string> GenerateTokenAsync(string email)
{
    var user = await _userManager.FindByEmailAsync(email);
    var tokenHandler = new JwtSecurityTokenHandler();
    var key = Encoding.ASCII.GetBytes(_tokenProviderOptions.SecretKey);

    var userRoles = await _userManager.GetRolesAsync(user);
    var roles = userRoles.Select(o => new Claim(ClaimTypes.Role, o));

    var claims = new[]
    {
        new Claim(JwtRegisteredClaimNames.Sub, user.UserName),
        new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
        new Claim(JwtRegisteredClaimNames.Iat, DateTime.UtcNow.ToString(CultureInfo.CurrentCulture)),
        new Claim(JwtRegisteredClaimNames.GivenName, user.FirstName),
        new Claim(JwtRegisteredClaimNames.FamilyName, user.LastName),
        new Claim(JwtRegisteredClaimNames.Email, user.Email),
    }
    .Union(roles);

    var tokenDescriptor = new SecurityTokenDescriptor
    {
        Subject = new ClaimsIdentity(claims),
        Expires = DateTime.UtcNow.AddHours(_tokenProviderOptions.Expires),
        SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
    };

    var token = tokenHandler.CreateToken(tokenDescriptor);

    return Task.FromResult(new JwtSecurityTokenHandler().WriteToken(token)).Result;
}