Search code examples
claims-based-identityasp.net-core-identityasp.net-core-8

How to add custom claims to User after or before login?


I use ASP.NET Core 8 project and Microsoft Identity.

I have to some user properties like UserId, FirstName, LastName, ImageName and etc. to user claims to use it in several place in the project.

I can get these properties from the database, but I need to add these as claims to user after login and use in pages, services and layouts.

Please help me.


Solution

  • After a lot of effort, I was able to solve the problem, I tried to sign in with claims instead of PasswordsignIn:

           AppUser? user = await sm.UserManager.Users.FirstOrDefaultAsync(U=>U.UserName==Input.UserName);
       List<Claim> claims = new List<Claim>()
       {
           new Claim( "UserId",user.UserId.ToString()),
           new Claim( "FullName",user.Title),
           new Claim( "Image",user.ImageName),
           new Claim( "ExpireDate",user.ExpireDate??""),
       };
    
       SignInResult result = default!;
        result = await  sm.CheckPasswordSignInAsync(user, Input.Password,true);
       if (result.Succeeded)
       {
           await sm.SignInWithClaimsAsync(user, Input.RememberMe, claims);              
       }