SignInManager.ExternalSignInAsync与Facebook总是返回失败 [英] SignInManager.ExternalSignInAsync with Facebook always returns failure

查看:1325
本文介绍了SignInManager.ExternalSignInAsync与Facebook总是返回失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Google+的工作,但Facebook总是返回失败。当我审视LOGININFO它表明身份验证= TRUE。

这是Statup.Auth.cs的code - 我包括了Google+ code其中工程

 公共无效ConfigureAuth(IAppBuilder应用程序)
        {
            //配置分贝范围内,用户管理和登入管理器使用每个请求的单个实例
            app.CreatePerOwinContext(ApplicationDbContext.Create);
            app.CreatePerOwinContext< ApplicationUserManager>(ApplicationUserManager.Create);
            app.CreatePerOwinContext< ApplicationSignInManager>(ApplicationSignInManager.Create);            //使应用程序能够使用cookie来存储信息,在用户签订
            //并利用co​​okie来临时存储有关用户记录的信息与第三方供应商登录
            //配置在cookie中的标志
            app.UseCookieAuthentication(新CookieAuthenticationOptions
            {
                AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                LOGINPATH =新PathString(/帐号/登录),
                供应商=新CookieAuthenticationProvider
                {
                    //允许应用验证安全戳当用户登录英寸
                    //这是一项安全功能,当您更改密码或添加外部登录到您的帐户被使用。
                    OnValidateIdentity = SecurityStampValidator.OnValidateIdentity< ApplicationUserManager,ApplicationUser>(
                        validateInterval:TimeSpan.FromMinutes(30),
                        regenerateIdentity:(经理,用户)=> user.GenerateUserIdentityAsync(经理))
                }
            });
            app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);            //使应用程序能够临时存储时,他们正在核实在双因素身份验证过程的第二个因素用户信息。
            app.UseTwoFactorSignInCookie(DefaultAuthenticationTypes.TwoFactorCookie,TimeSpan.FromMinutes(5));            //使应用程序能够记住第二次登录验证的因素,如电话或电子邮件。
            //一旦选中此选项,在登录过程中验证的第二个步骤将是你从登录的设备记住。
            //这是类似的,当你登录了rememberMe选项。
            app.UseTwoFactorRememberBrowserCookie(DefaultAuthenticationTypes.TwoFactorRememberBrowserCookie);            //取消注释以下行来实现与第三方供应商登录登录
            //app.UseMicrosoftAccountAuthentication(
            //的clientId:,
            // clientSecret:);            //app.UseTwitterAuthentication(
            // consumerKey:,
            // consumerSecret:);            VAR的选择=新FacebookAuthenticationOptions();
            options.Scope.Add(电子邮件);
            options.Scope.Add(friends_about_me);
            options.Scope.Add(friends_photos);
            options.AppId =XXXXXXXXX;
            options.AppSecret =XXXXXXX;
            options.Provider =新FacebookAuthenticationProvider()
           {
               OnAuthenticated =背景=>
                   {                       VAR userDetail = context.User;                       字符串ID =(动态)context.Id;                       字符串emmail =(动态)context.Email;                       VAR的currentUser = UserManager.FindByName(emmail);
                       如果(currentUser.UserProfile == NULL)
                       {
                           currentUser.EmailConfirmed = TRUE;                           尝试
                           {
                               currentUser.UserProfile =新用户配置
                               {
                                   UserProfileId = currentUser.ToString(),
                                   阿凡达= ConvertImageURLToBase64(@https://graph.facebook.com/+身份证+/图片?类型=大),
                                   姓氏=((动态)context.User).first_name.Value,
                                   名字=((动态)context.User).last_name.Value,
                                   MemberSince = DateTime.Now.Date,
                                   ProfileVisibility =私人,
                                   邮编code =0
                               };
                               UserManager.Update(的currentUser);
                           }
                           赶上(异常前)
                           {
                               字符串x = ex.StackTrace.ToString();
                           }
                       }
                       返回System.Threading.Tasks.Task.FromResult(0);
                   }
           };
            app.UseFacebookAuthentication(选件);
            app.UseGooglePlusAuthentication(新GooglePlusAuthenticationOptions()
            {
                客户端Id =XXXXXXX,
                ClientSecret =XXXXX,
                供应商=新GooglePlusAuthenticationProvider()
                {                    OnAuthenticated =背景=>
                    {
                        VAR userDetail = context.Person;
                        context.Identity.AddClaim(新索赔(ClaimTypes.Name,context.Identity.FindFirstValue(ClaimTypes.Name)));
                        context.Identity.AddClaim(新索赔(ClaimTypes.Email,context.Identity.FindFirstValue(ClaimTypes.Email)));
                        字符串ID =((动态)context.Person).ID;
                        字符串emmail =((动态)context.Person).emails [0] .value.Value;
                        VAR的currentUser = UserManager.FindByName(emmail);
                        如果(currentUser.UserProfile == NULL)
                        {
                            currentUser.EmailConfirmed = TRUE;                            currentUser.UserProfile =新用户配置
                            {
                                UserProfileId = currentUser.ToString(),
                                阿凡达= ConvertImageURLToBase64(((动态)context.Person).image.url.Value)
                                姓氏=((动态)context.Person).name.familyName.Value,
                                名字=((动态)context.Person).name.givenName.Value,
                                MemberSince = DateTime.Now.Date,
                                ProfileVisibility =私人,
                                邮编code =0
                            };
                            UserManager.Update(的currentUser);
                        }                        返回System.Threading.Tasks.Task.FromResult(0);
                    },
                },
            });
        }

这是AccountController.cs - Google+的工作,但Facebook并没有

  [使用AllowAnonymous]
        公共异步任务<&的ActionResult GT; ExternalLoginCallback(字符串RETURNURL)
        {
            VAR LOGININFO =等待AuthenticationManager.GetExternalLoginInfoAsync();
            如果(LOGININFO == NULL)
            {
                返回RedirectToAction(登录);
            }            // SIGN在这个外部登录提供用户,如果用户已经有一个登录
            VAR的结果=等待SignInManager.ExternalSignInAsync(LOGININFO,isPersistent:假);
            开关(结果)
            {
                案例SignInStatus.Success:
                    返回RedirectToLocal(RETURNURL);
                案例SignInStatus.LockedOut:
                    返回视图(锁定);
                案例SignInStatus.RequiresVerification:
                    返回RedirectToAction(发送code,新的{RETURNURL = RETURNURL,与rememberMe = FALSE});
                案例SignInStatus.Failure:
                默认:
                    //如果用户没有一个帐户,然后提示用户创建一个帐户
                    ViewBag.ReturnUrl = RETURNURL;
                    ViewBag.L`enter code here`oginProvider = loginInfo.Login.LoginProvider;
                    返回视图(ExternalLoginConfirmation,新ExternalLogi [此处输入的形象描述] [1] nConfirmationViewModel {电子邮件= loginInfo.Email}!);
            }
        }


解决方案

事实证明了code正在工作。我想我可以电汇和现有用户为Facebook的用户,当Facebook的用户电子邮件相匹配的用户ID(是电子邮件),但事实并非如此,思考它之后它是有道理的。你有Facebook的用户与新用户关联起来。

Google+ works, but Facebook always returns a failure. When I examine loginInfo it shows that authenticated = true.

This is the code in Statup.Auth.cs - I included the Google+ code which works.

public void ConfigureAuth(IAppBuilder app)
        {
            // Configure the db context, user manager and signin manager to use a single instance per request
            app.CreatePerOwinContext(ApplicationDbContext.Create);
            app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
            app.CreatePerOwinContext<ApplicationSignInManager>(ApplicationSignInManager.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
                {
                    // Enables the application to validate the security stamp when the user logs in.
                    // This is a security feature which is used when you change a password or add an external login to your account.  
                    OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
                        validateInterval: TimeSpan.FromMinutes(30),
                        regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
                }
            });
            app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

            // Enables the application to temporarily store user information when they are verifying the second factor in the two-factor authentication process.
            app.UseTwoFactorSignInCookie(DefaultAuthenticationTypes.TwoFactorCookie, TimeSpan.FromMinutes(5));

            // Enables the application to remember the second login verification factor such as phone or email.
            // Once you check this option, your second step of verification during the login process will be remembered on the device where you logged in from.
            // This is similar to the RememberMe option when you log in.
            app.UseTwoFactorRememberBrowserCookie(DefaultAuthenticationTypes.TwoFactorRememberBrowserCookie);

            // Uncomment the following lines to enable logging in with third party login providers
            //app.UseMicrosoftAccountAuthentication(
            //    clientId: "",
            //    clientSecret: "");

            //app.UseTwitterAuthentication(
            //   consumerKey: "",
            //   consumerSecret: "");

            var options = new FacebookAuthenticationOptions();
            options.Scope.Add("email");
            options.Scope.Add("friends_about_me");
            options.Scope.Add("friends_photos");
            options.AppId = "xxxxxxxxx";
            options.AppSecret = "xxxxxxx";
            options.Provider = new FacebookAuthenticationProvider()
           {
               OnAuthenticated = context =>
                   {

                       var userDetail = context.User;

                       string id = (dynamic)context.Id;

                       string emmail = (dynamic)context.Email;

                       var currentUser = UserManager.FindByName(emmail);
                       if (currentUser.UserProfile == null)
                       {
                           currentUser.EmailConfirmed = true;

                           try
                           {
                               currentUser.UserProfile = new UserProfile
                               {
                                   UserProfileId = currentUser.ToString(),
                                   Avatar = ConvertImageURLToBase64(@"https://graph.facebook.com/" + id + "/picture?type=large"),
                                   LastName = ((dynamic)context.User).first_name.Value,
                                   FirstName = ((dynamic)context.User).last_name.Value,
                                   MemberSince = DateTime.Now.Date,
                                   ProfileVisibility = "Private",
                                   ZipCode = "0",
                               };
                               UserManager.Update(currentUser);
                           }
                           catch (Exception ex)
                           {
                               string x = ex.StackTrace.ToString();
                           }
                       }
                       return System.Threading.Tasks.Task.FromResult(0);
                   }
           };
            app.UseFacebookAuthentication(options);


            app.UseGooglePlusAuthentication(new GooglePlusAuthenticationOptions()
            {
                ClientId = "xxxxxxx",
                ClientSecret = "xxxxx",
                Provider = new GooglePlusAuthenticationProvider()
                {

                    OnAuthenticated = context =>
                    {
                        var userDetail = context.Person;
                        context.Identity.AddClaim(new Claim(ClaimTypes.Name, context.Identity.FindFirstValue(ClaimTypes.Name)));
                        context.Identity.AddClaim(new Claim(ClaimTypes.Email, context.Identity.FindFirstValue(ClaimTypes.Email)));
                        string id = ((dynamic)context.Person).id;
                        string emmail = ((dynamic)context.Person).emails[0].value.Value;
                        var currentUser = UserManager.FindByName(emmail);
                        if (currentUser.UserProfile == null)
                        {
                            currentUser.EmailConfirmed = true;

                            currentUser.UserProfile = new UserProfile
                            {
                                UserProfileId = currentUser.ToString(),
                                Avatar = ConvertImageURLToBase64(((dynamic)context.Person).image.url.Value),
                                LastName = ((dynamic)context.Person).name.familyName.Value,
                                FirstName = ((dynamic)context.Person).name.givenName.Value,
                                MemberSince = DateTime.Now.Date,
                                ProfileVisibility = "Private",
                                ZipCode = "0"
                            };
                            UserManager.Update(currentUser);
                        }

                        return System.Threading.Tasks.Task.FromResult(0);
                    },
                },
            });
        }

This is the AccountController.cs - Google+ works, but Facebook does not.

[AllowAnonymous]
        public async Task<ActionResult> ExternalLoginCallback(string returnUrl)
        {
            var loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync();
            if (loginInfo == null)
            {
                return RedirectToAction("Login");
            }

            // 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.L`enter code here`oginProvider = loginInfo.Login.LoginProvider;
                    return View("ExternalLoginConfirmation", new ExternalLogi![enter image description here][1]nConfirmationViewModel { Email = loginInfo.Email });
            }
        }

解决方案

As it turns out the code is working. I was thinking I could wire up and existing user as a Facebook user when the Facebook user email matched the user id (Which is email), but that is not the case and after thinking about it it makes sense. You have to associate the Facebook user with a new user.

这篇关于SignInManager.ExternalSignInAsync与Facebook总是返回失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆