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

前端 未结 7 2019
旧巷少年郎
旧巷少年郎 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 20:49

    Using Alex Wheat's answer, I came up with a solution to retrive the google+ profile, gender and e-mail using Google Authentication.

    Startup.Auth.cs:

    var googleOptions = new GoogleOAuth2AuthenticationOptions()
    {
        ClientId = "<>",
        ClientSecret = "<>",
        Provider = new GoogleOAuth2AuthenticationProvider()
        {
            OnAuthenticated = context =>
            {
                var userDetail = context.User;
                context.Identity.AddClaim(new Claim(ClaimTypes.Name,context.Identity.FindFirstValue(ClaimTypes.Name)));
                context.Identity.AddClaim(new Claim(ClaimTypes.Email,context.Identity.FindFirstValue(ClaimTypes.Email)));
    
                var gender = userDetail.Value("gender");
                context.Identity.AddClaim(new Claim(ClaimTypes.Gender, gender));
    
                var picture = userDetail.Value("picture");
                context.Identity.AddClaim(new Claim("picture", picture));
    
                return Task.FromResult(0);
            },
        },
    };
    googleOptions.Scope.Add("https://www.googleapis.com/auth/plus.login");
    googleOptions.Scope.Add("https://www.googleapis.com/auth/userinfo.email");
    
    app.UseGoogleAuthentication(googleOptions);
    

    To get access to extended profile data, you should add two scopes to the request - plus.login and userinfo.email. If you only add the plus.login scope, you won't be able to see the user's e-mail. If you use ASP.NET MVC5's default template to authenticate, it will only show the user's e-mail, Name, Surname and google+ profile address. Using the way shown here, you'll have access also to the user's picture link.

    The context.User property carries a JSON serialization of the user's data sent across the wire and have useful methods to let the user find a property by its key.

    To learn more about login scopes concept, please take a look at: https://developers.google.com/+/api/oauth#login-scopes

提交回复
热议问题