Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get ExternalIdentity after all the login process?

Tags:

c#

asp.net-mvc

I am using MVC 5 and I can successfully login using Google.

I want to have access to the user external identity claims after the login process. I want in a view to access, for example, the claim "picture" from the user. However if I try to run this code it always return null. (except in the login process - auto generated code for mvc template)

external info is null

Is there a way for me to have access to the external identity claims? (after the login process)

like image 824
BrunoLM Avatar asked Dec 25 '22 04:12

BrunoLM


1 Answers

I found how the identity is created. Basically the ExternalSignInAsync makes an internal call to SignInAsync which makes a call to CreateUserIdentityAsync.

I found a class ApplicationSignInManager in the IdentityConfig file and then I changed the CreateUserIdentityAsync method to:

public override async Task<ClaimsIdentity> CreateUserIdentityAsync(ApplicationUser user)
{
    var externalIdentity = await AuthenticationManager.GetExternalIdentityAsync(DefaultAuthenticationTypes.ExternalCookie);

    var localIdentity = await user.GenerateUserIdentityAsync((ApplicationUserManager)UserManager);

    foreach (var item in externalIdentity.Claims)
    {
        if (!localIdentity.HasClaim(o => o.Type == item.Type))
            localIdentity.AddClaim(item);
    }

    return localIdentity;
}

So every time I sign in I am going to have my claims + external claims in the loggedin user. From a view I can call:

@HttpContext.Current.GetOwinContext()
    .Authentication.User.FindFirst("urn:google:picture").Value
like image 171
BrunoLM Avatar answered Feb 13 '23 20:02

BrunoLM