0

We have an asp.net core 6.0 web app. When we login we need to add a few additional claims to control users. These new claims come from database, but we can't do it in the "GenerateClaimsAsync" of the IdentityUser since this is a multi tenant SAAS app with a single database and depending on the tenant the user is, those claims are going to be different.

await _signInManager.SignInWithClaimsAsync(user, isPersistent: true, GetUserTenantAdditionalClaims(user));

In the "GetUserTenantAdditionalClaims" we get the claims for the user depending on which tenant is.

Everything works just fine when connecting but after a few minutes (15-20) the Athentication Cookie changes and loses all the additional claims, BUT the user is still logged !!! So after that time we have the user logged with the "regular" claims but we have lost our additional claims.

I know this is a problem when .NET refreshes the cookie, but is there any way to not refreshing that cookie or can add a few lines of code in a "on refreshing cookie" procedure to reload also our additional claims?

Thanks in advance.

John Mathison
  • 904
  • 1
  • 11
  • 36
  • One method is override `SignInWithClaimsAsync` method, you can refer to this [link](https://stackoverflow.com/questions/60758152/how-to-change-cookie-expiration-time-when-signin-with-passwordsigninasync). – Xinran Shen Mar 02 '23 at 05:06

1 Answers1

0

You can use IUserClaimsPrincipalFactory for change default claim when user logging.

For example I add my custom claim in my code blow:

I used Identity default .net core

Startup.cs :

  services.AddScoped<IUserClaimsPrincipalFactory<ApplicationUser>, CustomClaimsPrincipalFactory>();

public class CustomClaimsPrincipalFactory : UserClaimsPrincipalFactory<ApplicationUser,IdentityRole>
{
    public CustomClaimsPrincipalFactory(UserManager<ApplicationUser> userManager, RoleManager<IdentityRole> roleManager, IOptions<IdentityOptions> options) : base(userManager, roleManager, options)
    {
    }

    public async override Task<ClaimsPrincipal> CreateAsync(ApplicationUser user)
    {
        var principal = await base.CreateAsync(user);

        ((ClaimsIdentity)principal.Identity).AddClaims(new[] 
            {
            new Claim(CustomClaimTypes.StaffId, user.StaffID.ToString()),
            new Claim(CustomClaimTypes.FullName, user.FullName.ToString()),
            new Claim(CustomClaimTypes.BranchId, user.BranchId.ToString())
             });

        return principal;
    }

    
}
Soheil
  • 190
  • 1
  • 1
  • 14
  • Thanks for your answer, but as I was explaining in my question, it doesn't work for us. I can't use CustomClaimsIdentityFactory since the additional claims depend on the tenant and use other tables than the User one. – John Mathison Mar 01 '23 at 11:45
  • Could you **sign in user again** After knowing about what claims need for user? – Soheil Mar 02 '23 at 07:17