Ejemplo n.º 1
0
        private async Task <ActionResult> CreateExternalProviderUserAsync(ExternalLoginInfo loginInfo)
        {
            //Create a New User and SignIn
            var user = new ApplicationUser();

            //If External Provider has email, set the email here. Otherwise we will take it on Profile Wizard
            user.Email = loginInfo.Email;
            //If email is set, check whether a User with same email exists or not
            if (!string.IsNullOrEmpty(user.Email))
            {
                if (UserManager.FindByEmail(user.Email) != null)
                {
                    TempData["SignUpError"] = new IdentityResult(new List <string>
                    {
                        "Email is already taken",
                    });
                    return(RedirectToAction("Index", "Home"));
                }

                //If an Email is returned from the Social Account, then Set the Email as Confirmed.
                //If an Email is no returned, we need to verify the Email first.
                user.EmailConfirmed = true;
            }


            string profilePictureUrl = null;

            //Check the Login Provider. We need to Extract the user data based on the LoginProvider
            switch (loginInfo.Login.LoginProvider)
            {
            case "Facebook":
                //Get Facebook User Data from the Saved Claim
                OAuthReponseUserFacebook facbookUserData = loginInfo.ExternalIdentity.GetOAuthUserData <OAuthReponseUserFacebook>();
                if (facbookUserData != null)
                {
                    //Save the Profile Image
                    if (facbookUserData.Picture.Data != null)
                    {
                        if (!facbookUserData.Picture.Data.is_silhouette)
                        {
                            profilePictureUrl = facbookUserData.Picture.Data.URL;
                        }
                    }

                    //Get the other Data
                    user.FullName = facbookUserData.Name;
                    user.UserName = "******" + facbookUserData.ID;
                }
                break;

            case "Google":
                //Get Google User Data from the Saved Claim
                OAuthReponseUserGoogle googleUserData = loginInfo.ExternalIdentity.GetOAuthUserData <OAuthReponseUserGoogle>();
                if (googleUserData != null)
                {
                    //Save the Profile Image
                    if (googleUserData.Image != null)
                    {
                        if (!googleUserData.Image.IsDefault)
                        {
                            profilePictureUrl = googleUserData.Image.URL;
                        }
                    }

                    //Get the other Data
                    user.FullName = googleUserData.DisplayName;
                    user.UserName = "******" + googleUserData.ID;
                }
                break;

            case "Instagram":
                //Get Google User Data from the Saved Claim
                OAuthReponseUserInstagram instagramUserData = loginInfo.ExternalIdentity.GetOAuthUserData <OAuthReponseUserInstagram>();
                if (instagramUserData != null)
                {
                    //Save the Profile Image
                    profilePictureUrl = instagramUserData.ProfilePicture;

                    //Get the other Data
                    user.FullName = instagramUserData.FullName;
                    user.UserName = "******" + instagramUserData.ID;
                }
                break;

            case "Twitter":
                //Get Google User Data from the Saved Claim
                OAuthReponseUserTwitter twitterUserData = loginInfo.ExternalIdentity.GetOAuthUserData <OAuthReponseUserTwitter>();
                if (twitterUserData != null)
                {
                    //Save the Profile Image
                    if (!twitterUserData.DefaultProfileImage)
                    {
                        profilePictureUrl = twitterUserData.ProfileImageUrl;
                    }

                    //Get the other Data
                    user.FullName = twitterUserData.Name;
                    user.UserName = "******" + twitterUserData.ID;
                }
                break;
            }

            //Set the User Profile Create and Update Date
            user.CreatedOn = DateTime.UtcNow;
            user.UpdatedOn = DateTime.UtcNow;

            //Create a User
            var createUserResult = await UserManager.CreateAsync(user);

            if (createUserResult.Succeeded)
            {
                //Add User Roles
                UserManager.AddToRole(user.Id, _UserRolesType.User);

                //Add Login Infor based on the Login Provider
                createUserResult = await UserManager.AddLoginAsync(user.Id, loginInfo.Login);

                if (createUserResult.Succeeded)
                {
                    //Download User Profile Image and Update User
                    string profileImageName = DateTime.UtcNow.ToString("yyyyddmmhhmmss") + "_profile_original.jpg";
                    string profileImagePath = Server.MapPath("~" + _FileSavingPaths.ProfileImage + "/" + profileImageName);
                    if (UtilityExtension.DownloadImage(profilePictureUrl, profileImagePath))
                    {
                        user.ProfileImageOriginal = profileImageName;
                        user.ProfileImageSelected = profileImageName;
                    }
                    await UserManager.UpdateAsync(user);

                    //Add Provider Claim
                    UserManager.AddClaim(user.Id, new Claim(_ClaimTypes.ExternalProviderType, loginInfo.Login.LoginProvider));
                    UserManager.AddClaim(user.Id, new Claim(_ClaimTypes.ExternalProviderUsername, loginInfo.DefaultUserName));
                    UserManager.AddClaim(user.Id, new Claim(_ClaimTypes.UrlUserName, loginInfo.DefaultUserName));
                    UserManager.AddClaim(user.Id, new Claim(_ClaimTypes.HasCompletedProfileWizard, false.ToString()));

                    //Login the current User
                    await SignInManager.SignInAsync(user, isPersistent : false, rememberBrowser : false);

                    //Add User Action Log
                    new LogsSerivce().RunAddLogTask(_LogActionType.AccountCreated, user.Id, extraMessage: loginInfo.Login.LoginProvider);

                    //TempData External Identity, After login, we will need some of these Claims
                    TempData["ExternalLoginInfo"] = loginInfo.ExternalIdentity;

                    //Add claims and Redirect to Profile Wizard Step 1
                    return(RedirectToAction("AddingClaims"));
                }
            }

            AddErrors(createUserResult);
            TempData["SignUpError"] = createUserResult;
            return(RedirectToAction("Index", "Home"));
        }
Ejemplo n.º 2
0
        private void ConfigureTwitter(IAppBuilder app)
        {
            /* -------------------------------------------------------------------------------
             * Normal configuration
             * ------------------------------------------------------------------------------- */

            //app.UseTwitterAuthentication("Your consumer key", "Your consumer secret");

            /* -------------------------------------------------------------------------------
             * Specify an alternate callback path
             * ------------------------------------------------------------------------------- */

            //var options = new TwitterAuthenticationOptions
            //{
            //    ConsumerKey = "Your consumer key",
            //    ConsumerSecret = "Your consumer secret",
            //    CallbackPath = new PathString("/oauth-redirect/twitter")
            //};
            //app.UseTwitterAuthentication(options);

            /* -------------------------------------------------------------------------------
             * Retrieve the access token and other user information
             * ------------------------------------------------------------------------------- */

            var options = new TwitterAuthenticationOptions
            {
                ConsumerKey    = ConfigurationManager.AppSettings["TWITTER_API_KEY"],
                ConsumerSecret = ConfigurationManager.AppSettings["TWITTER_API_SECRET"],
                //BackchannelCertificateValidator = new CertificateSubjectKeyIdentifierValidator(new[] {
                //    "A5EF0B11CEC04103A34A659048B21CE0572D7D47", // VeriSign Class 3 Secure Server CA – G2
                //    "0D445C165344C1827E1D20AB25F40163D8BE79A5", // VeriSign Class 3 Secure Server CA – G3
                //    "7FD365A7C2DDECBBF03009F34339FA02AF333133", // VeriSign Class 3 Public Primary Certification Authority – G5
                //    "39A55D933676616E73A761DFA16A7E59CDE66FAD", // Symantec Class 3 Secure Server CA – G4
                //    "5168FF90AF0207753CCCD9656462A212B859723B", //DigiCert SHA2 High Assurance Server C‎A
                //    "B13EC36903F8BF4701D498261A0802EF63642BC3" //DigiCert High Assurance EV Root CA
                //}),
                //CallbackPath = new PathString("/en/Account/LoginCallback"),
                CallbackPath = new PathString("/en/signin-twitter"),
            };

            options.Provider = new TwitterAuthenticationProvider
            {
                OnAuthenticated = context =>
                {
                    try
                    {
                        // Retrieve the OAuth access token to store for subsequent API calls
                        //string accessToken = context.AccessToken;

                        // Retrieve the screen name (e.g. @jerriepelser)
                        //string twitterScreenName = context.ScreenName;

                        // Retrieve the user ID
                        //var twitterUserId = context.UserId;
                        var userData = new OAuthReponseUserTwitter
                        {
                            //ProfilePicture = string.Format("https://twitter.com/{0}/profile_image?size=original", twitterScreenName)
                        };
                        OAuthReponseUserTwitter response = TwitterLogin(context.AccessToken, context.AccessTokenSecret, options.ConsumerKey, options.ConsumerSecret);
                        if (response != null)
                        {
                            context.Identity.AddClaim(new Claim(ClaimTypes.Email, response.Email));
                            context.Identity.AddClaim(new Claim(ClaimTypes.UserData, JsonConvert.SerializeObject(response)));
                        }
                        context.Identity.AddClaim(new Claim(_ClaimTypes.ExternalProviderAccessToken, context.AccessToken));
                    }
                    catch (Exception e)
                    {
                        File.AppendAllText(HttpContext.Current.Server.MapPath("~/Logs.txt"), DateTime.UtcNow.ToShortDateString() + " - " + HttpContext.Current.Request.Browser.Type + "\n\n" + e.Message + "\n\n===============================\n\n");
                    }
                    return(Task.FromResult(true));
                }
            };

            app.UseTwitterAuthentication(options);
        }