Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
447 views
in Technique[技术] by (71.8m points)

c# - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...