Claiming the users profile picture and name, when registering with Google account in ASP.NET MVC 5

asp.net asp.net-mvc c# entity-framework-6 oauth

Question

I'm making an ASP.NET MVC 5 project with Entity Framework (version 6.0) and I could really use some help.

I have added the simple Google+ login/registering by enabling my Google API and adding the credentials in the Startup.Auth.cs file:

app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions()
        {
            ClientId = "MyClientId",
            ClientSecret = "MyClientSecret"
        });

How do I claim the users Google+ name and profile picture and assign it to an ASP.NET Identity User, when they register?

And also, how do I access this data (profile picture and name of an identity user) and how it in a view?

1
1
4/29/2017 3:45:52 PM

Popular Answer

According to Google's own sample code, first you need an OnAuthenticated callback to capture the image URL at the time of authentication:

// After OAuth authentication completes successfully,
// read user's profile image URL from the profile
// response data and add it to the current user identity
OnAuthenticated = context =>
{
    var profileUrl = context.User["image"]["url"].ToString();
    context.Identity.AddClaim(new Claim(ClaimTypes.Uri, profileUrl));
    return Task.FromResult(0);
}

Then you can access both name and image URL from the User class:

public class User : ClaimsPrincipal
{
    public User(IPrincipal principal) : base(principal as ClaimsPrincipal) { }

    public string Name => this.Identity.Name;
    public string UserId => this.FindFirst(ClaimTypes.NameIdentifier).Value;
    public string ProfileImage => this.FindFirst(ClaimTypes.Uri).Value;
}
0
4/29/2017 4:36:48 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow