Sunday, April 2, 2017

Storing Identity Claims in Session or Redis


ASP.NET Core Identity by default uses cookies to store claims. If your authorization is very granular then you will end up using many claims. With all these claims stored in cookie, the cookie size gets bigger and you can exceed the cookie limit.

We can achieve the authorization granularity without exceeding the cookie limit and impacting the way ASP.NET Identity authorizes users by storing the claims in session, Redis or any other memory storage.

Below are the steps I implemented to store the claims in session.

First let’s store the claims in session (assuming that the ASP.NET Core Session is already configured). During authentication, Identity system uses SignInManager for creating principal object of the logged in user. While creating the principal object, Identity populates the claims. We can override this SignInManager and store the claims as shown below:

public class ApplicationSignInManager : SignInManager<ApplicationUser>
{
    private IHttpContextAccessor contextAccessor;

    public ApplicationSignInManager(UserManager<ApplicationUser> userManager, IHttpContextAccessor contextAccessor, IUserClaimsPrincipalFactory<ApplicationUser> claimsFactory, IOptions<IdentityOptions> optionsAccessor, ILogger<SignInManager<ApplicationUser>> logger)
        : base(userManager, contextAccessor, claimsFactory, optionsAccessor, logger)
    {
        this.contextAccessor = contextAccessor;
    }

    public override async Task<ClaimsPrincipal> CreateUserPrincipalAsync(ApplicationUser user)
    {
        var principal = await base.CreateUserPrincipalAsync(user);
        ClaimsIdentity identity = (ClaimsIdentity)principal.Identity;

        // storing claims in session and removing them. These claims will be added by Transformer
        List<ClaimModel> sessionClaims = new List<ClaimModel>();
        List<Claim> identityClaims = identity.Claims.ToList();
        foreach (var claim in identityClaims)
        {
            sessionClaims.Add(new ClaimModel() { ClaimType = claim.Type, ClaimValue = claim.Value });
            identity.RemoveClaim(claim);
        }

        this.contextAccessor.HttpContext.Session.SetString("IdentityClaims", JsonConvert.SerializeObject(sessionClaims));

        return principal;
    }
}

The Identity system should be configured to use our ApplicationSignInManager instead of the default one. For this we need to define the dependency injection in the Startup under ConfigureServices

services.AddScoped<SignInManager<ApplicationUser>, ApplicationSignInManager>();

As you see with above code claims are removed from the principal identity and stored in the session. These claims should to be added back to the principal identity for every request. This done through the claims transformer as shown below:

public class ClaimsTransformer : IClaimsTransformer
{
    public Task<ClaimsPrincipal> TransformAsync(ClaimsTransformationContext context)
    {
        ClaimsPrincipal principal = context.Principal;
        ClaimsIdentity identity = (ClaimsIdentity)principal.Identity;
        string claimString = NTContext.HttpContext.Session.GetString("IdentityClaims");
        if (claimString != null)
        {
            List<ClaimModel> sessionClaims = JsonConvert.DeserializeObject<List<ClaimModel>>(claimString);
            identity.AddClaims(sessionClaims.Select(sc => new Claim(sc.ClaimType, sc.ClaimValue)));
        }

        return Task.FromResult(principal);
    }
}

This ClaimsTransformer class is configured in the Startup under Configure section as shown below:

app.UseClaimsTransformation(new ClaimsTransformationOptions()
{
    Transformer = new ClaimsTransformer(),
});

app.UseIdentity();


With the above setup now the claims are stored in session when the user logs in. At every request from the user these claims will be copied from session to the identity object. Now we have overridden the default approach of using cookies with session J

72 comments:

  1. Oh, they are really hard to distinguish from each other! Thanks for the help

    ReplyDelete
  2. The saving all applications is optimal in each case. However, this also has a limit. The users will be able to leave their requests for review.

    ReplyDelete
  3. This comment has been removed by the author.

    ReplyDelete
  4. I have read a few of the articles on your website now, and I really like your style of blogging. I added it to my favourites blog site list and will be checking back soon.
    Click here:
    angularjs training in chennai
    Click here:
    angularjs2 training in chennai

    ReplyDelete
  5. A good blog always comes-up with new and exciting information and while reading I have feel that this blog is really have all those quality that qualify a blog to be a one.I wanted to leave a little comment to support you and wish you a good continuation. Wishing you the best of luck for all your blogging efforts read this.
    Click here:
    Microsoft azure training in chennai
    Click here:
    Microsoft azure training in online

    ReplyDelete
  6. Thanks you for sharing this unique useful information content with us. Really awesome work. keep on blogging
    Devops training in velachery
    Devops training in annanagar

    ReplyDelete
  7. Fake IDs can be awesome fun as long as you utilize them legitimately. http://idhurry.com/ Numerous individuals imagine that fake ids are illicit, yet for the most part this isn't the situation.

    ReplyDelete
  8. A very nice guide. I will definitely follow these tips. Thank you for sharing such detailed article. I am learning a lot from you.

    rpa training in electronic-city | rpa training in btm | rpa training in marathahalli | rpa training in pune

    ReplyDelete
  9. It would have been the happiest moment for you,I mean if we have been waiting for something to happen and when it happens we forgot all hardwork and wait for getting that happened.
    java training in jayanagar | java training in electronic city

    java training in chennai | java training in USA

    ReplyDelete
  10. When I initially commented, I clicked the “Notify me when new comments are added” checkbox and now each time a comment is added I get several emails with the same comment. Is there any way you can remove people from that service? Thanks.

    Amazon Web Services Training in Pune | Best AWS Training in Pune


    AWS Training in Pune | Best Amazon Web Services Training in Pune

    ReplyDelete
  11. Your good knowledge and kindness in playing with all the pieces were very useful. I don’t know what I would have done if I had not encountered such a step like this.

    Java training in Chennai | Java training in Tambaram

    Java training in Chennai | Java training in Velachery

    Java training in Chennai | Java training in Omr

    Oracle training in Chennai

    ReplyDelete
  12. This comment has been removed by the author.

    ReplyDelete
  13. Thanks for your interesting ideas.the information's in this blog is very much useful
    for me to improve my knowledge.
    Selenium training near me
    Selenium Training in Chennai
    Selenium Training in Amjikarai
    Selenium Training Institutes in Vadapalani

    ReplyDelete
  14. All are saying the same thing repeatedly, but in your blog I had a chance to get some useful and unique information, I love your writing style very much, I would like to suggest your blog in my dude circle, so keep on updates.
    python course institute in bangalore
    python Course in bangalore
    python training institute in bangalore

    ReplyDelete
  15. All are saying the same thing repeatedly, but in your blog I had a chance to get some useful and unique information, I love your writing style very much, I would like to suggest your blog in my dude circle, so keep on updates.
    Best Devops training in sholinganallur
    Devops training in velachery
    Devops training in annanagar
    Devops training in tambaram

    ReplyDelete
  16. Your blog provided us with valuable information to work with. Each & every tips of your post are awesome. Thanks a lot for sharing. Keep blogging.. Brazilian wax in Manhattan

    ReplyDelete
  17. I’m planning to start my blog soon, but I’m a little lost on everything. Would you suggest starting with a free platform like Word Press or go for a paid option? There are so many choices out there that I’m completely confused. Any suggestions? Thanks a lot.
    Best AWS Training in Marathahalli | AWS Training in Marathahalli
    Best AWS Amazon Web Services Training in Chennai | Best AWS Training and Certification for Solution Architect in Chennai

    ReplyDelete
  18. I am so proud of you and your efforts and work make me realize that anything can be done with patience and sincerity. Well I am here to say that your work has inspired me without a doubt.
    angularjs Training in bangalore

    angularjs Training in bangalore

    angularjs interview questions and answers

    angularjs Training in marathahalli

    angularjs interview questions and answers

    angularjs-Training in pune

    ReplyDelete
  19. These super programmers do exist. I've met them. I've lived with them. They live on an unexpected plane in comparison to us unimportant humans. What's more, they all work at Google. how to learn programming Lodi

    ReplyDelete
  20. Make money on kasino online and do not regret anything gamble casino with us Make money on kaino online and do not regret anything.

    ReplyDelete
  21. Very nice post here and thanks for it .I always like and such a super contents of these post.
    Excellent and very cool idea and great content of different kinds of the valuable information's.
    Java training in Chennai
    Java training in Bangalore
    Java online training
    Java training in Pune

    ReplyDelete
  22. After reading this web site I am very satisfied simply because this site is providing comprehensive knowledge for you to audience.
    Thank you to the perform as well as discuss anything incredibly important in my opinion. We loose time waiting for your next article writing in addition to I beg one to get back to pay a visit to our website in



    selenium training in Bangalore
    selenium training in Marathahalli
    selenium training in Btm layout
    selenium training in Jaya nagar
    selenium training in Electronic city
    selenium training in Kalyan nagar



    ReplyDelete
  23. Your good knowledge and kindness in playing with all the pieces were very useful. I don’t know what I would have done if I had not encountered such a step like this.
    microsoft azure training in bangalore
    rpa training in bangalore
    best rpa training in bangalore
    rpa online training

    ReplyDelete
  24. Современная диодная лента по всем стандартам отличного качества я обычно беру у компании Ekodio

    ReplyDelete
  25. It was very informative and the way you write..good and are very helpful... webstagram

    ReplyDelete
  26. After seeing your article I want to say that the presentation is very good and also a well-written article with some very good information which is very useful for the readers....thanks for sharing it and do share more posts like this.
    angularjs online training

    apache spark online training

    informatica mdm online training

    devops online training

    aws online training

    ReplyDelete
  27. Thanks for such a great article here. I was searching for something like this for quite a long time and at last I’ve found it on your blog. It was definitely interesting for me to read  about their market situation nowadays.
    Microsoft Azure online training
    Selenium online training
    Java online training
    Python online training
    uipath online training

    ReplyDelete

  28. It has been simply incredibly generous with you to provide openly what exactly many individuals would’ve marketed for an eBook to end up making some cash for their end, primarily given that you could have tried it in the event you wanted.
    Data Science Training in Chennai | Data Science Course in Chennai
    Python Course in Chennai | Python Training Course Institutes in Chennai
    RPA Training in Chennai | RPA Training in Chennai
    Digital Marketing Course in Chennai | Best Digital Marketing Training in Chennai

    ReplyDelete
  29. This comment has been removed by the author.

    ReplyDelete
  30. Home Mart is a site about Home Improvement, Furniture, Home Appliances and many more.
    Check out the best
    home office desks nz
    coffee table nz
    bookshelves

    ReplyDelete
  31. An inflatable backrest and comfortable seating increases your comfort experience with paddling. The front of the kayak is used entirely to store your stuffs with mesh top.

    Intex Explorer K2 Kayak 2 Person Inflatable Sit On Top Kayak

    ReplyDelete
  32. Wow it is really wonderful and awesome thus it is veWow, it is really wonderful and awesome thus it is very much useful for me to understand many concepts and helped me a lot.

    python training in bangalore

    python courses in bangalore

    python classes in bangalore

    python training institute in bangalore

    python course syllabus

    best python training

    python training centers

    ReplyDelete
  33. This is the exact information I am been searching for, Thanks for sharing the required infos with the clear update and required points. To appreciate this I like to share some useful information.

    aws training in bangalore

    aws courses in bangalore

    aws classes in bangalore

    aws training institute in bangalore

    aws course syllabus

    best aws training

    aws training centers

    ReplyDelete
  34. Great Article. Thank you for sharing! Really an awesome post for every one.

    IEEE Final Year projects Project Centers in Chennai are consistently sought after. Final Year Students Projects take a shot at them to improve their aptitudes, while specialists like the enjoyment in interfering with innovation. For experts, it's an alternate ball game through and through. Smaller than expected IEEE Final Year project centers ground for all fragments of CSE & IT engineers hoping to assemble. Final Year Project Domains for IT It gives you tips and rules that is progressively critical to consider while choosing any final year project point.

    JavaScript Training in Chennai

    JavaScript Training in Chennai


    ReplyDelete