要在MVC5中获取当前登录的用户,我们所要做的就是:
using Microsoft.AspNet.Identity;
[Authorize]
public IHttpActionResult DoSomething() {
string currentUserId = User.Identity.GetUserId();
}
现在,有了 ASP.NET 核心,我认为这应该可以工作,但它抛出了一个错误。
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;
如果您的代码位于 MVC 控制器中:
public class MyController : Microsoft.AspNetCore.Mvc.Controller
从Controller
基类中,可以从 User
属性获取ClaimsPrincipal
System.Security.Claims.ClaimsPrincipal currentUser = this.User;
您可以直接检查声明(无需往返数据库(:
bool isAdmin = currentUser.IsInRole("Admin");
var id = _userManager.GetUserId(User); // Get user id:
其他字段可以从数据库的用户实体中获取:
使用依赖关系注入获取用户管理器
private UserManager<ApplicationUser> _userManager; //class constructor public MyController(UserManager<ApplicationUser> userManager) { _userManager = userManager; }
并使用它:
var user = await _userManager.GetUserAsync(User); var email = user.Email;
如果代码是服务类,则可以使用依赖项注入来获取一个IHttpContextAccessor
,该允许您从 HttpContext 获取User
。
private IHttpContextAccessor _httpContextAccessor;
public MyClass(IHttpContextAccessor httpContextAccessor)
{
_httpContextAccessor = httpContextAccessor;
}
private void DoSomething()
{
var user = _httpContextAccessor.Context?.User;
}
如果使用承载令牌身份验证,则上述示例不会返回应用程序用户。
相反,请使用以下内容:
ClaimsPrincipal currentUser = this.User;
var currentUserName = currentUser.FindFirst(ClaimTypes.NameIdentifier).Value;
ApplicationUser user = await _userManager.FindByNameAsync(currentUserName);
这适用于apsnetcore 2.0。在早期版本中没有尝试过。
对于上下文,我使用 ASP.NET Core 2 Web 应用程序模板创建了一个项目。然后,选择 Web 应用程序 (MVC(,然后点击 更改身份验证 按钮并选择个人用户帐户。
此模板为您构建了许多基础设施。 在"控制器"文件夹中找到ManageController
。
此ManageController
类构造函数需要填充此用户管理器变量:
private readonly UserManager<ApplicationUser> _userManager;
然后,看看这个类中的 [HttpPost] Index 方法。 他们以这种方式获取当前用户:
var user = await _userManager.GetUserAsync(User);
作为补充说明,您可以在此处将任何自定义字段更新到已添加到 AspNetUsers 表中的用户配置文件。 将字段添加到视图中,然后将这些值提交到 IndexViewModel,然后将该模型提交到此 Post 方法。 我在默认逻辑后添加了此代码以设置电子邮件地址和电话号码:
user.FirstName = model.FirstName;
user.LastName = model.LastName;
user.Address1 = model.Address1;
user.Address2 = model.Address2;
user.City = model.City;
user.State = model.State;
user.Zip = model.Zip;
user.Company = model.Company;
user.Country = model.Country;
user.SetDisplayName();
user.SetProfileID();
_dbContext.Attach(user).State = EntityState.Modified;
_dbContext.SaveChanges();
在 .NET Core 2.0 中,用户已作为基础继承控制器的一部分存在。只需像往常一样使用 User,或者传递到任何存储库代码即可。
[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"
});
}
}
这是它继承它的地方
#region Assembly Microsoft.AspNetCore.Mvc.Core, Version=2.0.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60
// C:UsersBhailDa.nugetpackagesmicrosoft.aspnetcore.mvc.core2.0.0libnetstandard2.0Microsoft.AspNetCore.Mvc.Core.dll
#endregion
using System;
using System.IO;
using System.Linq.Expressions;
using System.Runtime.CompilerServices;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using Microsoft.AspNetCore.Mvc.ModelBinding.Validation;
using Microsoft.AspNetCore.Routing;
using Microsoft.Net.Http.Headers;
namespace Microsoft.AspNetCore.Mvc
{
//
// Summary:
// A base class for an MVC controller without view support.
[Controller]
public abstract class ControllerBase
{
protected ControllerBase();
//
// Summary:
// Gets the System.Security.Claims.ClaimsPrincipal for user associated with the
// executing action.
public ClaimsPrincipal User { get; }
如果有人感兴趣,这对我有用。我有一个自定义标识,它使用 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;
}
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);
}
我已经在我的控制器类中放了这样的东西,它起作用了:
IdentityUser user = await userManager.FindByNameAsync(HttpContext.User.Identity.Name);
其中userManager是Microsoft.AspNetCore.Identity.UserManager类的一个实例(随之而来的所有奇怪的设置(。