How do I access Microsoft.Owin.Security.xyz OnAuthenticated context AddClaims values?

前端 未结 3 1520
再見小時候
再見小時候 2020-12-04 17:02

I\'m trying to retrieve user properties that are returned as the OnAuthenticated context and added as a claims following this example: How to access Facebook private inform

3条回答
  •  抹茶落季
    2020-12-04 17:44

    So this article explains how this all works pretty well: Decoupling owin external auth

    But the short answer is, when you get authenticated from facebook, that is giving you an external identity. You then need to take that external identity and 'sign in' a local app identity, its in that stepthat you need to add any claims you want from the external identity to the ClaimsIdentity that becomes User.Identity.

    Edit: To clarify further, you could do it inside of ExternalLoginCallback:

        // GET: /Account/ExternalLoginCallback
        [AllowAnonymous]
        public async Task ExternalLoginCallback(string returnUrl) {
            var loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync();
            if (loginInfo == null) {
                return RedirectToAction("Login");
            }
    
            // Sign in this external identity if its already linked
            var user = await UserManager.FindAsync(loginInfo.Login);
            if (user != null) {
                await SignInAsync(user, isPersistent: false);
                return RedirectToLocal(returnUrl);
            }
    
        private async Task SignInAsync(ApplicationUser user, bool isPersistent) {
            AuthenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie);
            var identity = await UserManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie);
            AuthenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = isPersistent }, identity);
        }
    

    So you will need to pass in extra data to the SignIn, which will look something like this:

       ClaimsIdentity id = await AuthenticationManager.GetExternalIdentityAsync(DefaultAuthenticationTypes.ExternalCookie);
    

    This ClaimsIdentity will have your added claim, and you will need to add that claim to the identity created in the SignInAsync method for it to show up.

提交回复
热议问题