首页 > 解决方案 > 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?}");
        });
    }
}

标签: c#asp.net-corebearer-tokenasp.net-core-identity

解决方案


您可以在 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);

推荐阅读