Click here to Skip to main content
15,887,214 members
Articles / Programming Languages / C#
Tip/Trick

Get Live Email ID and Google Email ID using OAuth (MVC5)

Rate me:
Please Sign up or sign in to vote.
4.75/5 (3 votes)
30 Sep 2014CPOL 16.6K   8   1
How to get Windows live Email ID and Google Email ID using OAuth

Introduction

We can Get Windows live Email ID and Google Email ID using OAuth.

In Controller page (It works for Google and Windows live):

C#
[AllowAnonymous]
      public async Task<ActionResult> ExternalLoginCallback(string returnUrl)
      {
          UserLogin objUserLogin = new UserLogin();
          string providerKey = string.Empty;
          string issuer = string.Empty;
          string name = string.Empty;
          string emailAddress = string.Empty;

          var loginInfo = await AuthenticationManager.AuthenticateAsync
                           (DefaultAuthenticationTypes.ExternalCookie);

          if (loginInfo != null && loginInfo.Identity != null &&
                           loginInfo.Identity.IsAuthenticated)
          {
              var claimsIdentity = loginInfo.Identity;
              var providerKeyClaim = claimsIdentity.FindFirst(ClaimTypes.NameIdentifier);

              providerKey = providerKeyClaim.Value;
              issuer = providerKeyClaim.Issuer;
              name = claimsIdentity.FindFirstValue(ClaimTypes.Name);
              emailAddress = claimsIdentity.FindFirstValue(ClaimTypes.Email);
          }
          else
          {
              return RedirectToAction("Index", "Home");
          }

Follow to configure in Windows live is get “client id” and “client secret” values and check in local http://www.benday.com/2014/02/25/walkthrough-asp-net-mvc-identity-with-microsoft-account-authentication/.

Follow to configure in Google is get “client id” and “client secret” values and check in local http://www.asp.net/mvc/tutorials/mvc-5/create-an-aspnet-mvc-5-app-with-facebook-and-google-oauth2-and-openid-sign-on.

In Startup.Auth.cs:

C#
public void ConfigureAuth(IAppBuilder app)
      {
          app.CreatePerOwinContext<DbConnection>(() =>
               ConnectionStrings.DefaultConnection.ReliableConnection());
          app.CreatePerOwinContext<PortalUserStore>(PortalUserStore.Create);
          app.CreatePerOwinContext<PortalUserManager>(PortalUserManager.Create);

          // Enable the application to use a cookie to store information
          // for the signed in user
          // and to use a cookie to temporarily store information
          // about a user logging in with a third party login provider
          // Configure the sign in cookie
          app.UseCookieAuthentication(new CookieAuthenticationOptions
          {
              AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
              LoginPath = new PathString("/Account/Login"),
              Provider = new CookieAuthenticationProvider
              {
                  OnValidateIdentity = SecurityStampValidator.OnValidateIdentity
                                       <PortalUserManager, PortalUserData, int>(
                       TimeSpan.FromMinutes(30),
                       (manager, user) => user.GenerateUserIdentityAsync(manager),
                       (id) => int.Parse(id.GetUserId()))
              }
          });

          app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

          var ms = new Microsoft.Owin.Security.MicrosoftAccount.MicrosoftAccountAuthenticationOptions();
          ms.Scope.Add("wl.emails");
          ms.Scope.Add("wl.basic");
          ms.ClientId = System.Configuration.ConfigurationManager.AppSettings
                            ["LiveIdClientId"].ToString();
          ms.ClientSecret = System.Configuration.ConfigurationManager.AppSettings
                            ["LiveIdClientSecret"].ToString();
          ms.Provider = new Microsoft.Owin.Security.MicrosoftAccount.
                              MicrosoftAccountAuthenticationProvider()
          {
              OnAuthenticated = async context =>
              {
                  context.Identity.AddClaim(new System.Security.Claims.Claim
                  ("urn:microsoftaccount:access_token", context.AccessToken));

                  foreach (var claim in context.User)
                  {
                      var claimType = string.Format("urn:microsoftaccount:{0}", claim.Key);
                      string claimValue = claim.Value.ToString();
                      if (!context.Identity.HasClaim(claimType, claimValue))
                          context.Identity.AddClaim(new System.Security.Claims.Claim
                          (claimType, claimValue, "XmlSchemaString", "Microsoft"));
                  }
              }
          };

          app.UseMicrosoftAccountAuthentication(ms);

          /*Google Start Added*/
          app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions()
          {
              ClientId = System.Configuration.ConfigurationManager.AppSettings
                           ["GoogleClientId"].ToString(),
              ClientSecret = System.Configuration.ConfigurationManager.AppSettings
                           ["GoogleClientSecret"].ToString()
          });
          /*End Added*/
      }

In this way, we can get email for Windows live id and Google.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Unknown
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralMy vote of 5 Pin
Humayun Kabir Mamun30-Sep-14 20:24
Humayun Kabir Mamun30-Sep-14 20:24 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.