asp.net-corecookiesnullauthorizationclaims

Cant get claims in authorization handler


public class RequestLoginIsUserLoginHandler : AuthorizationHandler<AccessRequirement, string>
{
    protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, AccessRequirement requirement, string resource)
    {
        string? name = context.User.Identity?.Name;
        if (name == resource)
        {
            context.Succeed(requirement);
        }
        return Task.CompletedTask;
    }
}

I can see claims values in database, but context.User.Identity?.Name is always null. image

Im using cookies authentication. Im adding claim this way:

var claims = new List<Claim>
        {
            new Claim(ClaimTypes.Name, input.Login),
            new Claim(ClaimTypes.Role, "user")
        };
await userManager.AddClaimsAsync(user, claims);

Maybe I have problems here:

[HttpPost("/login")]
    public async Task<IActionResult> Login(string login, string password)
    {
        var user = await mediator.Send(new GetUserByLoginQuery(login));
        if (user is null) return Unauthorized("wrong login");

        var result = await signInManager.PasswordSignInAsync(user, password, false, false);
        if(!result.Succeeded) 
        {
            return Unauthorized("wrong password");
        }
        return Ok();
    }

I tried to use ClaimTypes.Name and my own type "Name". Result is the same.

Updated. I add claims during registration. Code:

[HttpPost("/register")]
    public async Task<IActionResult> CreateUser(RegisterInput input)
    {
        var userWithSameLogin = await mediator.Send(new GetUserByLoginQuery(input.Login));
        if (userWithSameLogin != null)
        {
            return Conflict();
        }

        var user = new User
        {
            UserName = input.Login,
            FirstName = input.FirstName,
            LastName = input.LastName,
            PhoneNumber = input.PhoneNumber,
            Email = input.Email
        };
        
        var result = await userManager.CreateAsync(user, input.Password);
        if (!result.Succeeded)
        {
            return BadRequest(result.Errors);
        }
        
        var claims = new List<Claim>
        {
            new Claim(ClaimTypes.Name, input.Login),
            new Claim(ClaimTypes.Role, "user")
        };
        await userManager.AddClaimsAsync(user, claims);

        return Ok();
    }

Solution

  • You are getting this issue might be because claim is not properly attached to the authentication principal or when they are not being correctly loaded during the authentication process.

    you could try this below sample code to make the claim being added correctly s it does not shows null:

    Program.cs:

    builder.Services.AddControllersWithViews();
    builder.Services.AddDbContext<ApplicationDbContext>(options =>
        options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));
    
    // Add Identity services
    builder.Services.AddIdentity<IdentityUser, IdentityRole>()
        .AddEntityFrameworkStores<ApplicationDbContext>()
        .AddDefaultTokenProviders();
    
    // Configure Cookie Authentication
    builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
        .AddCookie(options =>
        {
            options.LoginPath = "/Account/Login";
            options.AccessDeniedPath = "/Account/AccessDenied";
        });
    

    AccountController.cs:

    using Microsoft.AspNetCore.Authentication.Cookies;
    using Microsoft.AspNetCore.Authentication;
    using Microsoft.AspNetCore.Identity;
    using Microsoft.AspNetCore.Mvc;
    using System.Security.Claims;
    using CookieAuthDemo1.Models;
    
    namespace CookieAuthDemo1.Controllers
    {
        public class AccountController : Controller
        {
            private readonly SignInManager<IdentityUser> _signInManager;
            private readonly UserManager<IdentityUser> _userManager;
    
            public AccountController(SignInManager<IdentityUser> signInManager, UserManager<IdentityUser> userManager)
            {
                _signInManager = signInManager;
                _userManager = userManager;
            }
    
            [HttpGet]
            public IActionResult Login()
            {
                return View();
            }
    
            [HttpPost]
            public async Task<IActionResult> Login(LoginViewModel model)
            {
                if (!ModelState.IsValid)
                {
                    return View(model);
                }
    
                var user = await _userManager.FindByNameAsync(model.Login);
                if (user == null)
                {
                    ModelState.AddModelError(string.Empty, "Invalid login.");
                    return View(model);
                }
    
                var result = await _signInManager.PasswordSignInAsync(user, model.Password, false, false);
                if (result.Succeeded)
                {
                    var claims = new List<Claim>
               {
                   new Claim(ClaimTypes.Name, user.UserName),
                   new Claim(ClaimTypes.Role, "user")
               };
                    var claimsIdentity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
                    var authProperties = new AuthenticationProperties { IsPersistent = true };
    
                    await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(claimsIdentity), authProperties);
    
                    return RedirectToAction("Index", "Home");
                }
    
                ModelState.AddModelError(string.Empty, "Invalid password.");
                return View(model);
            }
    
    
            [HttpPost]
            public async Task<IActionResult> Logout()
            {
                await _signInManager.SignOutAsync();
                return RedirectToAction("Index", "Home");
            }
        }
        }
    

    enter image description here

    enter image description here

    enter image description here