Adding Custom Claims when Logging In with Asp.Net Core Identity Cookie

Georg Dangl by Georg Dangl in Web Development Sunday, December 24, 2017

Sunday, December 24, 2017

When working with Asp.Net Core applications, Asp.Net Core Identity is a great and easy to use choice for managing app authentication and authorization. By default, logins happen via an application cookie. This means that on a successful login, a cookie is set in the users browser that can be verified by the server on each request, without requiring database roundtrips. It also stores a few claims (pieces of information about the logged in user) directly in the cookie, such as the username or roles. You can even easily define your own claims, and the default implementation will automatically store this information in the cookie as well, allowing you to access it in every request.

However, sometimes you don't want to store a claim as persistent in the database, but still attach some information to a login sessions or context. This could be for claims that are somehow stored not as regular claims, like a team the user is associated with, or even data generated on the fly, like if the login happened on a Tuesday. If you take a look at Asp.Net Core Identities SignInManagers source, you see it just generates a ClaimsPrincipal for the user and then performs the sign in action (generating the cookie and appending it to the http response as a Set-Cookie header). This means, if you want to intercept that action and append more claims to the generated principal, you can do that either by providing your own ClaimsFactory or, as what I'll show you, just provide a custom SignInHandler.

The CustomClaimsCookieSignInHelper<TIdentityUser> provides just a wrapping mechanism around the core sign in functionality. It's easy to use in your AccountControllers login action:

To add custom claims, simply pass them as arguments to the SignInHandler.SignInUserAsync() method. If you want to go further down that route, you should check out the official implementation for the UserClaimsPrincipalFactory.

Merry Christmas and happy authenticating!

Share this post

comments powered by Disqus

About me

Hi, my name's George! I love coding and blogging about it. I focus on all things around .Net, Web Development and DevOps.


Need a consultant for BIM, GAEB or Software Development?

Contact me at [email protected], +49 (173) 56 45 689 or visit my professional page!

// Just 💗 Coding

Social Links