Search code examples
c#asp.net-corebearer-tokenasp.net-core-identity

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. Is there a difference in the way to get the user from inside the controller in .NET Core 2.1? Following the examples I am constantly getting null for my user object. Thank you! :)

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

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

Solution

  • 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. 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);