简体   繁体   中英

Transforming / Modifying claims in asp.net identity 2

In Windows Identity Framework (WIF) you could implement a ClaimsAuthenticationManager in order to modify the claims on the principal or add new claims to it.

The claims authentication manager provides an extensibility point in the application's claims processing pipeline that you can use to validate, filter, modify, incoming claims or inject new claims into the set of claims presented by a ClaimsPrincipal before the RP application code is executed.

Does ASP.net Identity 2 have any sort of pipeline hook like this? If I want to add some claims without having them persisted in the AspNetUserClaims table how can I do this?

The logical place to do this would be right after the user has successfully signed in. This would occur in the AccountController login action:

    public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
            {
                if (!ModelState.IsValid) { return View(model); }

                var result = await SignInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, shouldLockout: false);
                switch (result)
                {
                    case SignInStatus.Success:

                        // Transform here
                        var freshClaims = new List<Claim>
                        {
                           new Claim(ClaimTypes.Email, model.Email),
                           new Claim(ClaimTypes.Locality, "Earth (Milky Way)"),
                           new Claim(ClaimTypes.Role, "Trooper"),
                           new Claim(ClaimTypes.SerialNumber, "555666777")
                        };
                        AuthenticationManager.AuthenticationResponseGrant.Identity.AddClaims(freshClaims);
                        return RedirectToLocal(returnUrl);

I use DI to inject AuthenticationManager into AccountControllers constructor and set it up as a property of AccountController . If you don't do this then you can just get it off the OWIN context:

var authManager = HttpContext.Current.GetOwinContext().Authentication;
authManager.AuthenticationResponseGrant.Identity.AddClaims(freshClaims);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM