jbr*_*aun 58 c# asp.net-identity asp.net-core-mvc asp.net-core
要在MVC5中获取当前登录的用户,我们所要做的就是:
using Microsoft.AspNet.Identity;
[Authorize]
public IHttpActionResult DoSomething() {
string currentUserId = User.Identity.GetUserId();
}
Run Code Online (Sandbox Code Playgroud)
现在,使用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);
}
Run Code Online (Sandbox Code Playgroud)
有任何想法吗?
编辑: Gerardo的回应是正常的,但要获得用户的实际"Id",这似乎工作:
ClaimsPrincipal currentUser = this.User;
var currentUserID = currentUser.FindFirst(ClaimTypes.NameIdentifier).Value;
Run Code Online (Sandbox Code Playgroud)
Ger*_*oli 97
假设您的代码在MVC控制器中:
public class MyController : Microsoft.AspNetCore.Mvc.Controller
Run Code Online (Sandbox Code Playgroud)
从Controller
基层,您可以IClaimsPrincipal
从User
酒店获取
System.Security.Claims.ClaimsPrincipal currentUser = this.User;
Run Code Online (Sandbox Code Playgroud)
您可以直接检查索赔(无需往返数据库):
bool IsAdmin = currentUser.IsInRole("Admin");
var id = _userManager.GetUserId(User); // Get user id:
Run Code Online (Sandbox Code Playgroud)
可以从数据库的User实体中获取其他字段:
使用依赖注入获取用户管理器
private UserManager<ApplicationUser> _userManager;
//class constructor
public MyController(UserManager<ApplicationUser> userManager)
{
_userManager = userManager;
}
Run Code Online (Sandbox Code Playgroud)并使用它:
var user = await _userManager.GetUserAsync(User);
var email = user.Email;
Run Code Online (Sandbox Code Playgroud)Gre*_*Gum 20
如果您使用的是Bearing Token Auth,则上述示例不会返回应用程序用户.
相反,使用这个:
ClaimsPrincipal currentUser = this.User;
var currentUserName = currentUser.FindFirst(ClaimTypes.NameIdentifier).Value;
ApplicationUser user = await _userManager.FindByNameAsync(currentUserName);
Run Code Online (Sandbox Code Playgroud)
这适用于apsnetcore 2.0.没有在早期版本中尝试过.
就上下文而言,我使用ASP.NET Core 2 Web应用程序模板创建了一个项目。然后,选择Web应用程序(MVC),然后单击“更改身份验证”按钮并选择“个人用户”帐户。
此模板为您建立了许多基础结构。找到ManageController
在Controllers文件夹。
此类的ManageController
构造函数需要填充以下UserManager变量:
private readonly UserManager<ApplicationUser> _userManager;
Run Code Online (Sandbox Code Playgroud)
然后,查看此类中的[HttpPost] Index方法。他们以这种方式获取当前用户:
var user = await _userManager.GetUserAsync(User);
Run Code Online (Sandbox Code Playgroud)
值得一提的是,您想在这里将任何自定义字段更新为已添加到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();
Run Code Online (Sandbox Code Playgroud)
如果有人感兴趣的话,这对我有用。我有一个自定义 Identity,它使用 int 作为主键,因此我覆盖了 GetUserAsync 方法
重写 GetUserAsync
public override Task<User> GetUserAsync(ClaimsPrincipal principal)
{
var userId = GetUserId(principal);
return FindByNameAsync(userId);
}
Run Code Online (Sandbox Code Playgroud)
获取身份用户
var user = await _userManager.GetUserAsync(User);
Run Code Online (Sandbox Code Playgroud)
如果您使用常规 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;
}
Run Code Online (Sandbox Code Playgroud)
小智 6
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);
}
Run Code Online (Sandbox Code Playgroud)
在.NET Core 2.0中,用户已作为底层继承控制器的一部分存在.只需像平常一样使用用户或传递给任何存储库代码.
[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"
});
}
}
Run Code Online (Sandbox Code Playgroud)
这是它从中继承的地方
#region Assembly Microsoft.AspNetCore.Mvc.Core, Version=2.0.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60
// C:\Users\BhailDa\.nuget\packages\microsoft.aspnetcore.mvc.core\2.0.0\lib\netstandard2.0\Microsoft.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; }
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
87437 次 |
最近记录: |