OWIN - Access External Claims in subsequent requests

馋奶兔 提交于 2019-12-11 13:57:00

问题


I have an ASP.Net application that uses OWIN and External logins through a third party provider, specifically google.

During Authentication, this code is used to pull the ClaimsIdentity from the OwinContext

var loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync();

where AuthenticationManager is

    private IAuthenticationManager AuthenticationManager
    {
        get
        {
            return HttpContext.GetOwinContext().Authentication;
        }
    }

However, on subsequent requests (i.e. redirecting to the home page after successful login) the GetExternalLoginInfoAsync() returns null. What I want to do is access information about the user's account (i.e. profile picture) that the external provider returns from my auth request. How can I access these Claims from an MVC controller or a Web API controller?

Almost all of the code I have is Visual Studio boiler plate code, so I won't include it here, but I can add some if anything specific is needed.

Thanks for any help you can offer.


回答1:


I was trying to use the external login info to pull data such as picture and profile url. The correct way to do this is to assign claims from the external source to the local identity as so:

  public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<User, string> manager, IAuthenticationManager authentication = null)
    {
        // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
        var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
        // Add custom user claims here

        if (authentication != null)
        {
            ExternalLoginInfo info = authentication.GetExternalLoginInfo();

            if (info != null)
                foreach (Claim claim in info.ExternalIdentity.Claims.Where(claim => !userIdentity.HasClaim(c => c.Type == claim.Type)))
                {
                    userIdentity.AddClaim(claim);
                    await manager.AddClaimAsync(userIdentity.GetUserId(), claim);
                }
        }

        return userIdentity;
    }


来源:https://stackoverflow.com/questions/33760676/owin-access-external-claims-in-subsequent-requests

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