How to customize the cookie generator of identityserver? (add claims into token but not into cookies)

Viewed 56

I am using the IdentityServer and I have a React client. so when I try to login into my client after checking credentials IDP generates some cookies in my browser. I read about these cookies (especially.AspNetCore.Identity.Application cookie) and discovered that some user information is stored in these cookies such as claims and roles. So I want to customize the cookie generator and remove some useless information from there. there are two questions:

1- how can I substitute the default cookie generator with a customized one?

2- are claims and roles needed for any other flows or I can remove the without any concerns?

1 Answers

I found the solution: We can customize the Authentication cookie using this link.

If I want to summarize this article you should change the login action fellow:

1- If you are using PasswordSignInAsync you should change it to CheckPasswordSignInAsync because the first one is using the default cookie generation workflow but 2nd has no action for cookie creation.

2- for creating the cookie you should use HttpContext.SignInAsync method. It will generate the authentication cookie for you. Remember that SubId is a required claim that must be included in the cookie. this is the cookie generator section of my code:

var claims = new List<Claim> { new Claim(JwtClaimTypes.Subject, user.Id.ToString()) };
claims.Add(new Claim(ClaimTypes.Name, user.UserName));
claims.Add(new Claim("user_type", $@"{user.UserType}"));
var claimIdentity = new ClaimsIdentity(claims, "pwd");
await HttpContext.SignInAsync("Identity.Application",new ClaimsPrincipal(claimIdentity),new AuthenticationProperties
                            {
                                IsPersistent = true
                            });
                         
Related