CodeChrist - This is a personal blog which I write to help follow coders

If you like it, feel free to comment and appreciate the good work


Following are the some features of CodeChrist

  • Easy to navigate and use.
  • You can subscibe for emails
  • CodeChrist is beautiful on every screen size (try resizing your browser!)
by · 2 comments:

A tutorial on how to get Profile Picture, email, etc through Google Plus and Facebook in ASP.net MVC

I am assuming you have already got Client Secret and Client Id from Google Plus Api.

Now in Startup.Auth.cs remove the below code
 
//app.UseFacebookAuthentication(

            //   appId: "",

            //   appSecret: "");
and paste this
 var googleOptions = new GoogleOAuth2AuthenticationOptions()
            {
                ClientId = "9ac07032788-agi11p78tp105iqkodc8tebie14jbd7i.apps.googleusercontent.com",
                ClientSecret = "B1cvuBL5rBPUNh1molEBkVLVl",
                Provider = new GoogleOAuth2AuthenticationProvider()
                {
                    OnAuthenticated = (context) =>
                    {
                        context.Identity.AddClaim(new Claim("urn:google:name", context.Identity.FindFirstValue(ClaimTypes.Name)));
                        context.Identity.AddClaim(new Claim("urn:google:email", context.Identity.FindFirstValue(ClaimTypes.Email)));
                        //This following line is need to retrieve the profile image
                        context.Identity.AddClaim(new System.Security.Claims.Claim("urn:google:accesstoken", context.AccessToken, ClaimValueTypes.String, "Google"));

                        return Task.FromResult(0);
                    }
                }
            };

            app.UseGoogleAuthentication(googleOptions);
And in AccountController.cs change the method ExternalLoginCallback as
 
  
        // GET: /Account/ExternalLoginCallback
        [AllowAnonymous]
        public async Task ExternalLoginCallback(string returnUrl)
        {
     
            var loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync();
            if (loginInfo == null)
            {
                return RedirectToAction("Login");
            }
            var accessToken = loginInfo.ExternalIdentity.Claims.Where(c => c.Type.Equals("urn:google:accesstoken")).Select(c => c.Value).FirstOrDefault();
            Uri apiRequestUri = new Uri("https://www.googleapis.com/oauth2/v2/userinfo?access_token=" + accessToken);
            dynamic userPicture;
            //request profile image
            using (var webClient = new System.Net.WebClient())
                {
                var json = webClient.DownloadString(apiRequestUri);
                dynamic resul = JsonConvert.DeserializeObject(json);
                userPicture = resul.picture;
            }
            this.Session["userPicture"] = userPicture;

 
            // Sign in the user with this external login provider if the user already has a login
            var result = await SignInManager.ExternalSignInAsync(loginInfo, isPersistent: false);
            switch (result)
            {
                case SignInStatus.Success:
                    return RedirectToLocal(returnUrl);
                case SignInStatus.LockedOut:
                    return View("Lockout");
                case SignInStatus.RequiresVerification:
                    return RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = false });
                case SignInStatus.Failure:
                default:
                    // If the user does not have an account, then prompt the user to create an account
                    ViewBag.ReturnUrl = returnUrl;
                    ViewBag.LoginProvider = loginInfo.Login.LoginProvider;
                    return View("ExternalLoginConfirmation", new ExternalLoginConfirmationViewModel { Email = loginInfo.Email });
            }
            //get access token to use in profile image request
           
        }

Now you can access image anywhere in project, because we have put it in Session variable. To show image, you can try this
 
@{
    ViewBag.Title = "About";
}
@ViewBag.Title

@ViewBag.Message
@HttpContext.Current.Session["userPicture"]
This is your image
@HttpContext.Current.Session["hello"] Use this area to provide additional information.
It will look something like this
Read More