OWIN - Access External Claims in subsequent reques

2019-08-09 04:52发布

问题:

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