Get ExtraData from MVC5 framework OAuth/OWin identity provider with external auth provider

前端 未结 7 2020
旧巷少年郎
旧巷少年郎 2020-11-30 20:22

I\'m trying to use the new MVC5 framework in VS 2013 preview.

The membership authentication framework has been overhauled and replaced with OWin.

<
7条回答
  •  被撕碎了的回忆
    2020-11-30 21:14

    Recently I had to get access to Google profile's picture as well and here is how I solve it...

    If you just enable the code app.UseGoogleAuthentication(); in the Startup.Auth.cs file it's not enough because in this case Google doesn't return any information about profile's picture at all (or I didn't figure out how to get it).

    What you really need is using OAuth2 integration instead of Open ID that enabled by default. And here is how I did it...

    First of all you have to register your app on Google side and get "Client ID" and "Client secret". As soon as this done you can go further (you will need it later). Detailed information how to do this here.

    Replace app.UseGoogleAuthentication(); with

        var googleOAuth2AuthenticationOptions = new GoogleOAuth2AuthenticationOptions
        {
            ClientId = "<>",
            ClientSecret = "<>",
            CallbackPath = new PathString("/Account/ExternalGoogleLoginCallback"),
            Provider = new GoogleOAuth2AuthenticationProvider() {
                OnAuthenticated = async context =>
                {
                    context.Identity.AddClaim(new Claim("picture", context.User.GetValue("picture").ToString()));
                    context.Identity.AddClaim(new Claim("profile", context.User.GetValue("profile").ToString()));
                }
            }
        };
    
        googleOAuth2AuthenticationOptions.Scope.Add("email");
    
        app.UseGoogleAuthentication(googleOAuth2AuthenticationOptions);
    

    After that you can use the code to get access to the profile's picture URL same way as for any other properties

    var externalIdentity = HttpContext.GetOwinContext().Authentication.GetExternalIdentityAsync(DefaultAuthenticationTypes.ExternalCookie);
    var pictureClaim = externalIdentity.Result.Claims.FirstOrDefault(c => c.Type.Equals("picture"));
    var pictureUrl = pictureClaim.Value;
    

提交回复
热议问题