简体   繁体   中英

ASP.NET MVC Identity Google access user profile via AccessToken given from GetExternalLoginInfo

I'm using Facebook & Google for login to my MVC app. For Facebook is login and fetching data about user working good. Google login is also working and it hits my method "ExternalLoginCallback" which is bellow where I recieve AccessToken.

BUT - I didn't find any nuget package simple as "FacebookClient", where I can just pass AccessToken and I can get more information about logged user which I would like store them to DB.

I found other nugets for Google such: Google.Apis.Plus.v1 where I need again pass clientId, secreatId nad credentials with X509Certificate2, so my question is if there is any simple way as provide "FacebookClient". If not could you please describe how you will retrieve information about logged in user ? Thank you.

[AllowAnonymous]
public ActionResult Login(string provider)
{
    HttpContext.GetOwinContext().Authentication.Challenge(new AuthenticationProperties
    {
        RedirectUri = Url.Action("ExternalLoginCallback")
    }, provider);

    return new HttpUnauthorizedResult();
}

[AllowAnonymous]
public ActionResult ExternalLoginCallback()
{            
    var externalLoginInfo = HttpContext.GetOwinContext().Authentication.GetExternalLoginInfo();
    var accessToken = externalLoginInfo.ExternalIdentity.Claims.FirstOrDefault(x => x.Type == "FacebookAccessToken")?.Value;

    // HERE I WOULD LIKE TO HAVE FUNCTIONALITY SIMILAR TO FacebookClient
    var client = new FacebookClient(accessToken);
    dynamic facebookData = client.Get("me", new { fields = "email,name,first_name,last_name,gender,locale" });
}

Finally I found way how to do it:

var userInfoUrl = "https://www.googleapis.com/oauth2/v2/userinfo?alt=json";
var hc = new HttpClient();
hc.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
var response = hc.GetAsync(userInfoUrl).Result;
var userInfo = response.Content.ReadAsStringAsync().Result;            
dynamic data = JObject.Parse(userInfo);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM