简体   繁体   English

承载令牌身份验证-如何在控制器ASP.NET Core 2.1中获取登录用户值

[英]Bearer Token Auth - How to get SignIn User Value in controller ASP.NET Core 2.1

I tried a few ways to get the logged in user from inside the controller but it does not seem to be working. 我尝试了几种方法来从控制器内部获取登录用户,但似乎无法正常工作。 Here is one of the examples I tried. 这是我尝试过的示例之一。 Most of the examples I saw was related to .NET Core 1.x. 我看到的大多数示例都与.NET Core 1.x有关。 Is there a difference in the way to get the user from inside the controller in .NET Core 2.1? 从.NET Core 2.1中的控制器内部获取用户的方式是否有所不同? Following the examples I am constantly getting null for my user object. 遵循示例之后,我的用户对象不断为null。 Thank you! 谢谢! :) :)

var user = await _userManager.GetUserAsync(HttpContext.User);

Startup.cs Startup.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?}");
        });
    }
}

Instead of traditional httpcontext you can use the base Controller class IClaimsPrincipal User property in ASP.Net Core action method provided UserManager is initialized in Controller Constructor and the User is signin. 代替传统的httpcontext,您可以在ASP.Net Core操作方法中使用基本的Controller类IClaimsPrincipal User属性,只要在Controller Constructor中初始化了UserManager并登录了User。 Like below 像下面

var user = await _userManager.GetUserAsync(this.User);

In case of Bearer Token, get SignIn User by Name. 对于无记名令牌,请按名称获取登录用户。 Like below: 如下所示:

//Get userId
var userId = this.User.FindFirst(ClaimTypes.NameIdentifier).Value;
var user = await _userManager.FindByNameAsync(userName);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM