locked
Add Claims after windows authentication RRS feed

  • Question

  • User-1236951964 posted

    hello everyone, 

    I'm working on MVC 5 model with automatic windows login IIS. 

    Is there a simple way to add some claims after windows auth. 

    I search for an eventHandler witch is call after IIS pass user info. 

    Thanks

    Wednesday, January 23, 2019 9:24 AM

All replies

  • User-2054057000 posted

    You can add claims to the user like this:

    AppUser user = await userManager.GetUserAsync(HttpContext.User);
    Claim claim = new Claim(claimType, claimValue, ClaimValueTypes.String); 
    IdentityResult result = await userManager.AddClaimAsync(user, claim);

    Reference - How to work with Claims in Identity Membership System

    Wednesday, January 23, 2019 8:32 PM
  • User1724605321 posted

     Hi antho10440,

    you can load your custom roles (or claims) from your custom store/database and then augment the current principal with them in the Application_PostAuthenticateRequest in global.asax :

     protected void Application_AuthenticateRequest(object sender, EventArgs args)
        {
            if (Request.IsAuthenticated)
            {
    
                ClaimsPrincipal principal = new ClaimsPrincipal(User.Identity);
    
                var identity = (ClaimsIdentity)principal.Identity;
    
                identity.AddClaim(new Claim("test", "helloworld!!!"));
    
                Thread.CurrentPrincipal = HttpContext.Current.User = principal;
            }
        }

    Best Regards,

    Nan Yu

    Thursday, January 24, 2019 2:46 AM
  • User-1236951964 posted

    Thank for reply, 

    i tried this approach , but i load some data for my db each time, and i think it will be to heavy because this function is called each time user send request. 

    I tried to store claims at Session_Start() but it seams like IIS clear my claims on each request. 

    (My need is not add claim for a particular user, but for a user witch is on dynamic AD group store in base)

    Have you a solution for that ? 

    Thursday, January 24, 2019 8:04 AM
  • User1724605321 posted

    Hi antho10440,

    In Application_AuthenticateRequest method , you can check whether current user is IsAuthenticated and has the claim already  , so that you can avoid searching the database again .

    Best Regards,

    Nan Yu

    Friday, January 25, 2019 3:20 AM
  • User-1236951964 posted

    Thank Nan yu , 

    I tried this too , but i use Windows Authentication and it seems claims are erased at each request by IIS. 

    I found a solution by using OWIN and at session start redirect too login controller who create personnal claim and redirect too home page.

    If you have an easier solution, i'll take it. 

    Best regards 

    Friday, January 25, 2019 7:57 AM