65.9K
CodeProject is changing. Read more.
Home

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

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.75/5 (3 votes)

Sep 30, 2014

CPOL
viewsIcon

16873

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):

  [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:

  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.