Search code examples
asp.netauthenticationasp.net-identity

Why userManager.GetUserName(User) is null?


I'm testing my WEB API with Fiddler, the logging in works perfectly (I think), but when I want to get back the signed in user's name then it gives back null.

The signing in method:

[HttpPost("signIn")]
    public async Task<IActionResult> SignIn(SignInViewModel model)
    {
        if (ModelState.IsValid)
        {
            var signInResult = await signInManager.PasswordSignInAsync(model.user_name, model.password, false, false);
            if (signInResult.Succeeded)
            {
                return Ok(model.user_name);
            }
        }
        return BadRequest(ModelState);
    }

The method where it brokes:

[HttpPost("addGrade")]
    public async Task<ActionResult<Grades>> AddGrade(Grades grade)
    {
        if (ModelState.IsValid)
        {
            var name = userManager.GetUserName(User);
            grade.manufacturer = name.ToString();
            db.Add(grade);

            await db.SaveChangesAsync();
            return CreatedAtAction("Get", new { id = grade.id_grades }, grade);
        }
        else
        {
            return BadRequest(ModelState);
        }
    }

My Startup.cs:

public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    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.AddAuthorization();
        services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
                .AddCookie();
        services.AddDbContext<DiaryDataContext>();
        //services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
        services.AddMvc(x => x.Filters.Add(new AuthorizeFilter())).AddXmlSerializerFormatters()
               .AddXmlDataContractSerializerFormatters();


        services.AddControllersWithViews();

        services.AddIdentity<IdentityUser, IdentityRole>()
            .AddEntityFrameworkStores<DiaryDataContext>()
            .AddDefaultTokenProviders();

        services.ConfigureApplicationCookie(opt =>
        {
            opt.ExpireTimeSpan = new TimeSpan(0, 5, 30);
            opt.Events = new CookieAuthenticationEvents
            {
                OnRedirectToLogin = redirextContext =>
                {
                    redirextContext.HttpContext.Response.StatusCode = 401;
                    return Task.CompletedTask;
                },
                OnRedirectToAccessDenied = redirectContext =>
                {
                    redirectContext.HttpContext.Response.StatusCode = 401;
                    return Task.CompletedTask;
                }
            };
        });
        //services.ConfigureApplicationCookie(options =>
        //{
        //    options.Cookie.HttpOnly = true;
        //    options.Cookie.Expiration = TimeSpan.FromSeconds();
        //    options.SlidingExpiration = true;
        //});
        //services.Configure<IdentityOptions>(options =>
        //  options.ClaimsIdentity.UserIdClaimType = ClaimTypes.NameIdentifier);
        




    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        app.UseAuthentication();

        app.UseRouting();
        app.UseAuthorization();
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
            // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
            app.UseHsts();
        }

        app.UseExceptionHandler(
            options =>
            {
                options.Run(async context =>
                {
                    context.Response.StatusCode = 500;
                    context.Response.ContentType = "application/json";
                    //var ex = context.Features.Get<IExceptionHandlerFeature>();
                    //if (ex != null)
                    //{
                    //    await context.Response.WriteAsync(ex.Error.Message);
                    //}
                });
            });
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
            // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
            app.UseHsts();
        }
        app.UseHttpsRedirection();
        app.UseStaticFiles();


      
        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers();
            endpoints.MapRazorPages();
        });
        //app.UseEndpoints(endpoints =>
        //{
        //    endpoints.MapControllerRoute(
        //        name: "default",
        //        pattern: "{controller=Home}/{action=Index}/{id?}");
        //});
        var cookiePolicyOptions = new CookiePolicyOptions
        {
            MinimumSameSitePolicy = SameSiteMode.Strict,
        };
        app.UseCookiePolicy(cookiePolicyOptions);


    }
}

Pictures of the successful login (with Fiddler) and the where I want to use userManager.GetUserName(User):

Successful login:

The name is null:


Solution

  • Based on documentation, GetUserName will returns the Name claim value if present otherwise returns null. So, the answer there is no value claim name on your signmanager identity.

    Try to using GetUserAsync() method first. And debugging what's on it. If it's null, then there is something wrong with you signin proccess.