SignInManager.ExternalSignInAsync 与 Facebook 总是返回失败

问题描述 投票:0回答:4

Google+ 有效,但 Facebook 总是返回失败。当我检查 loginInfo 时,它显示 authenticated = true.

这是 Statup.Auth.cs 中的代码 - 我包含了有效的 Google+ 代码。

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);
                    },
                },
            });
        }

这是 AccountController.cs - Google+ 可用,但 Facebook 不可用。

[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 });
            }
        }
facebook asp.net-mvc-5 owin
4个回答
1
投票

事实证明代码是有效的。我在想当 Facebook 用户电子邮件与用户 ID(即电子邮件)匹配时,我可以将现有用户连接为 Facebook 用户,但事实并非如此,在考虑之后它是有道理的。您必须将 Facebook 用户与新用户相关联。


1
投票

将以下行添加到您的 Startup.cs 类:

app.CreatePerOwinContext<ApplicationSignInManager>(ApplicationSignInManager.Create);

0
投票

Startup.cs 文件中的 (Configuration) 应该是这样的,不要忘记相应地用 clientSecret 更改 clientId

 public void Configuration(IAppBuilder app)
    {
        //ConfigureAuth(app);

        // Configure the db context and user 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
            {
                OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
                    validateInterval: TimeSpan.FromMinutes(30),
                    regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
            }
        });

        app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

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

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

        //app.UseFacebookAuthentication(
        //   appId: "",
        //   appSecret: "");

        app.UseGoogleAuthentication(
             clientId: "297643237302-gnpd43h4ob896h2091da9idb3v0hn7bm.apps.googleusercontent.com",
             clientSecret: "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");
     
    }

-1
投票

你是怎么解决的? 我仍然面临同样的问题

© www.soinside.com 2019 - 2024. All rights reserved.