c# - Bearer Token Auth - 如何在控制器 ASP.NET Core 2.1 中获取登录用户值
问题描述
我尝试了几种方法从控制器内部获取登录用户,但它似乎不起作用。这是我尝试的示例之一。我看到的大多数示例都与 .NET Core 1.x 相关。在 .NET Core 2.1 中从控制器内部获取用户的方式有什么不同吗?按照示例,我的用户对象不断为空。谢谢!:)
var user = await _userManager.GetUserAsync(HttpContext.User);
启动.cs
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
//For ASP.NET Identity Only | You can reuse this but replace dbname with your own database name
private string GetRdsConnectionString()
{
string hostname = Configuration.GetValue<string>("RDS_HOSTNAME");
string port = Configuration.GetValue<string>("RDS_PORT");
string dbname = "ASPNETIdentityUser";
string username = Configuration.GetValue<string>("RDS_USERNAME");
string password = Configuration.GetValue<string>("RDS_PASSWORD");
return $"Data Source={hostname},{port};Initial Catalog={dbname};User ID={username};Password={password};";
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.Configure<CookiePolicyOptions>(options =>
{
// This lambda determines whether user consent for non-essential cookies is needed for a given request.
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.None;
});
//Using RDS
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(
GetRdsConnectionString()));
//This has been commented out and moved to Identity Hosting Startup
//services.AddIdentity<IdentityUser, IdentityRole>()
// .AddEntityFrameworkStores<ApplicationDbContext>()
// .AddDefaultTokenProviders();
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1)
.AddRazorPagesOptions(options =>
{
options.AllowAreas = true;
options.Conventions.AuthorizeAreaFolder("Identity", "/Account/Manage");
options.Conventions.AuthorizeAreaPage("Identity", "/Account/Logout");
});
services.ConfigureApplicationCookie(options =>
{
options.LoginPath = $"/Identity/Account/Login";
options.LogoutPath = $"/Identity/Account/Logout";
options.AccessDeniedPath = $"/Identity/Account/AccessDenied";
});
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseDatabaseErrorPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseCookiePolicy();
app.UseAuthentication();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
}
解决方案
您可以在 ASP.Net Core 操作方法中使用基本 Controller 类 IClaimsPrincipal User 属性,而不是传统的 httpcontext,前提是 UserManager 在 Controller Constructor 中初始化并且用户正在登录。像下面
var user = await _userManager.GetUserAsync(this.User);
在 Bearer Token 的情况下,通过 Name 获取 SignIn User。如下所示:
//Get userId
var userId = this.User.FindFirst(ClaimTypes.NameIdentifier).Value;
var user = await _userManager.FindByNameAsync(userName);
推荐阅读
- android - Gradle:DSL 元素“useProguard”已过时,将很快被删除
- ios - 使用 CoreBluetooth CBL2CAPChannel 移动数据
- java - 如何单击具有输入类型和值的按钮?
- jquery - 如何使用jQuery ajax 重新加载用户不知道的页面是正在重新加载的页面?
- html - CSS样式表第一次没有链接到HTML web-dev
- android - 使用改造(pdf,ppt,png,jpg)“code = 500,内部服务器错误”上传文件有什么问题
- android - 如何绑定具有多个 IN 值的 SQL 语句?
- android - 如何使用导航视图
- c# - Net Core:用于数据检查的私有成员和数据注释之间的区别
- razorpay - 如何通过razorpay api取消特定用户(最终用户)的订阅