Transforming / Modifying claims in asp.net identity 2

佐手、 提交于 2019-11-29 12:00:40

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);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!