MVC5 Facebook身份验证-帐户/外部登录回调?错误= access_denied#_ = _

时间:2018-08-25 00:12:39

标签: facebook asp.net-mvc-5 oauth-2.0 facebook-oauth

为什么在以本地主机调试和运行应用程序时可以通过Facebook成功登录,但在发布到1and1.com之后却无法通过Facebook登录?

我在这里待了近一个星期。我在阅读过的每个论坛中尝试了所有尝试,但收效甚微。问题是,它在以localhost身份运行时可以正常工作,但是在发布到我的生产站点时却失败。生产站点由1and1.com托管。令人困惑的是,我一次只能在生产环境中进行身份验证。但此后没有。在visual Studio 2017中创建新的MVC Web应用程序时,整个项目几乎是所有默认设置。这是整个设置:

Facebook应用设置:

  • 应用程序域:smarthomeprodealer.com
  • 网站网址:https://smarthomeprodealer.com
  • 客户端OAuth登录:Yes
  • Web OAuth登录:Yes
  • 强制进行Web OAuth重新认证:Yes
  • 对重定向URI使用严格模式:Yes
  • 强制实施HTTPS:Yes
  • 嵌入式浏览器OAuth登录:No
  • 有效的OAuth Redirct URI:https://smarthomeprodealer.com/ https://smarthomeprodealer.com/signin-facebook https://localhost:44300/ https://localhost:44300/signin-facebook

Startup.Auth.cs

public partial class Startup
{
    public void ConfigureAuth(IAppBuilder app)
    {
        app.CreatePerOwinContext(ApplicationDbContext.Create);
        app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
        app.CreatePerOwinContext<ApplicationSignInManager>(ApplicationSignInManager.Create);

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

        app.UseFacebookAuthentication(new FacebookAuthenticationOptions
        {
            AppId = "*************",
            AppSecret = "*********************************",
            SignInAsAuthenticationType = DefaultAuthenticationTypes.ExternalCookie, 
            Provider = new FacebookAuthenticationProvider
            {
                OnAuthenticated = context =>
                {
                    context.Identity.AddClaim(new Claim("FacebookAccessToken", context.AccessToken));
                    foreach (var claim in context.User)
                    {
                        var claimType = $"urn:facebook:{claim.Key}";
                        var claimValue = claim.Value.ToString();
                        if (!context.Identity.HasClaim(claimType, claimValue))
                            context.Identity.AddClaim(new Claim(claimType, claimValue, "XmlSchemaString", "Facebook"));
                    }
                    return Task.FromResult(0);
                }
            }
        });
    }
}

AccountController.cs

    [AllowAnonymous]
    public async Task<ActionResult> ExternalLoginCallback(string returnUrl, string error)
    {
        if (error != null)
        {
            return this.View("Error");
        }

        var loginInfo = await this.AuthenticationManager.GetExternalLoginInfoAsync();
        if (loginInfo == null)
        {
            this.ModelState.AddModelError("", "Failed to get external login info.");
            return this.RedirectToAction("Login");
        }

        // Sign in the user with this external login provider if the user already has a login
        var result = await this.SignInManager.ExternalSignInAsync(loginInfo, isPersistent: false);
        switch (result)
        {
            case SignInStatus.Success:
                return this.RedirectToLocal(returnUrl);
            case SignInStatus.LockedOut:
                return this.View("Lockout");
            case SignInStatus.RequiresVerification:
                return this.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
                this.ViewBag.ReturnUrl = returnUrl;
                this.ViewBag.LoginProvider = loginInfo.Login.LoginProvider;
                ExternalLoginConfirmationViewModel viewModel = null;
                if (string.Equals(loginInfo.Login.LoginProvider, "facebook", StringComparison.CurrentCultureIgnoreCase))
                {
                    var identity = this.AuthenticationManager.GetExternalIdentity(DefaultAuthenticationTypes.ExternalCookie);
                    var email = loginInfo.Email;
                    var firstName = identity.FindFirstValue("urn:facebook:first_name");
                    var lastName = identity.FindFirstValue("urn:facebook:last_name");
                    viewModel = new ExternalLoginConfirmationViewModel
                    {
                        Email = email,
                        FirstName = firstName,
                        LastName = lastName
                    };
                }

                if (viewModel == null)
                {
                    viewModel = new ExternalLoginConfirmationViewModel { Email = loginInfo.Email };
                }
                return this.View("ExternalLoginConfirmation", viewModel);
        }
    }

packages.config

<?xml version="1.0" encoding="utf-8"?>
<packages>
  <package id="Antlr" version="3.5.0.2" targetFramework="net472" />
  <package id="bootstrap" version="3.3.7" targetFramework="net472" />
  <package id="EntityFramework" version="6.2.0" targetFramework="net472" />
  <package id="Facebook" version="7.0.6" targetFramework="net472" />
  <package id="jQuery" version="3.3.1" targetFramework="net472" />
  <package id="jQuery.MaskedInput" version="1.4.1.0" targetFramework="net472" />
  <package id="jQuery.Validation" version="1.17.0" targetFramework="net472" />
  <package id="Microsoft.ApplicationInsights.Agent.Intercept" version="2.4.0" targetFramework="net472" />
  <package id="Microsoft.AspNet.Identity.Core" version="2.2.2" targetFramework="net472" />
  <package id="Microsoft.AspNet.Identity.EntityFramework" version="2.2.2" targetFramework="net472" />
  <package id="Microsoft.AspNet.Identity.Owin" version="2.2.2" targetFramework="net472" />
  <package id="Microsoft.AspNet.Mvc" version="5.2.4" targetFramework="net472" />
  <package id="Microsoft.AspNet.Razor" version="3.2.4" targetFramework="net472" />
  <package id="Microsoft.AspNet.TelemetryCorrelation" version="1.0.0" targetFramework="net472" />
  <package id="Microsoft.AspNet.Web.Optimization" version="1.1.3" targetFramework="net472" />
  <package id="Microsoft.AspNet.WebPages" version="3.2.4" targetFramework="net472" />
  <package id="Microsoft.CodeDom.Providers.DotNetCompilerPlatform" version="2.0.0" targetFramework="net472" />
  <package id="Microsoft.jQuery.Unobtrusive.Validation" version="3.2.4" targetFramework="net472" />
  <package id="Microsoft.Owin" version="4.0.0" targetFramework="net472" />
  <package id="Microsoft.Owin.Host.SystemWeb" version="4.0.0" targetFramework="net472" />
  <package id="Microsoft.Owin.Security" version="4.0.0" targetFramework="net472" />
  <package id="Microsoft.Owin.Security.Cookies" version="4.0.0" targetFramework="net472" />
  <package id="Microsoft.Owin.Security.Facebook" version="4.0.0" targetFramework="net472" />
  <package id="Microsoft.Owin.Security.Google" version="4.0.0" targetFramework="net472" />
  <package id="Microsoft.Owin.Security.MicrosoftAccount" version="4.0.0" targetFramework="net472" />
  <package id="Microsoft.Owin.Security.OAuth" version="4.0.0" targetFramework="net472" />
  <package id="Microsoft.Owin.Security.Twitter" version="4.0.0" targetFramework="net472" />
  <package id="Microsoft.Web.Infrastructure" version="1.0.0.0" targetFramework="net472" />
  <package id="Modernizr" version="2.8.3" targetFramework="net472" />
  <package id="Newtonsoft.Json" version="11.0.2" targetFramework="net472" />
  <package id="Owin" version="1.0" targetFramework="net472" />
  <package id="System.Diagnostics.DiagnosticSource" version="4.4.1" targetFramework="net472" />
  <package id="WebGrease" version="1.6.0" targetFramework="net472" />
</packages>

我成功打开了Facebook的身份验证窗口,但是单击continue后,我得到了以下网络呼叫:

常规

    Request URL: https://smarthomeprodealer.com/signin-facebook?code=AQDBJtnrFRAOWXlsP-XwPpGYmOck3299lBcir6-W-1pK_jZDkKELCflt91yJ_RJQ5hChBUBgvxa6X-ZPxuCDiojdQOMiSOlxAdS6-3IUmGqCwfEqgROmnZF2WD3xsdZJNgRctbsR5-DPWcNUunB4Nmi0Z2fLPb6Cz7_kozK3MRRSuEiKDwfStUHeP_Hb07IZYXYQcDzq5XuR8FB-ZUDn4LLGoMgVQQ-O96FIvt7d_Yrm1_-THCk94HBdBRWlUyVXWBTFCssBZt7h5rE2lxqBnNREmEHXZgYaEDPDIAXA7Evp_M7tUu-BnkjJp1KojzXtcrcvCzV2oFflFy33gZr6kWvo&state=VctNDgrl9b6gQpcRUucyMLSWedxDOr6yhbmvlGRD37mWbVgAuW2p1nFbBkzJzIMjaXF65YKpKzEDiTYrSJDpVRnZIRyjiUnL-JW3Y6-evmerqysAezMENlneW3i3bvkH4f6BAvAMJw0C7SC6B2E2zlcGqvYJZvp0hlFqJbI1KhgMlozrChZcEFlYU0_leEXAp7JiwokC0ZloyRN9o3YA4siHolsHIR1tcOKnAoHSYaU
    Request Method: GET
    Status Code: 302 
    Remote Address: 74.208.236.203:443
    Referrer Policy: origin-when-cross-origin

响应标题

content-length: 0
date: Fri, 24 Aug 2018 23:52:41 GMT
location: /Account/ExternalLoginCallback?error=access_denied
server: Microsoft-IIS/10.0
set-cookie: .AspNet.Correlation.Facebook=; path=/; expires=Thu, 01-Jan-1970 00:00:00 GMT
status: 302
x-powered-by: ASP.NET

请求标头

:authority: smarthomeprodealer.com
:method: GET
:path: /signin-facebook?code=AQDBJtnrFRAOWXlsP-XwPpGYmOck3299lBcir6-W-1pK_jZDkKELCflt91yJ_RJQ5hChBUBgvxa6X-ZPxuCDiojdQOMiSOlxAdS6-3IUmGqCwfEqgROmnZF2WD3xsdZJNgRctbsR5-DPWcNUunB4Nmi0Z2fLPb6Cz7_kozK3MRRSuEiKDwfStUHeP_Hb07IZYXYQcDzq5XuR8FB-ZUDn4LLGoMgVQQ-O96FIvt7d_Yrm1_-THCk94HBdBRWlUyVXWBTFCssBZt7h5rE2lxqBnNREmEHXZgYaEDPDIAXA7Evp_M7tUu-BnkjJp1KojzXtcrcvCzV2oFflFy33gZr6kWvo&state=VctNDgrl9b6gQpcRUucyMLSWedxDOr6yhbmvlGRD37mWbVgAuW2p1nFbBkzJzIMjaXF65YKpKzEDiTYrSJDpVRnZIRyjiUnL-JW3Y6-evmerqysAezMENlneW3i3bvkH4f6BAvAMJw0C7SC6B2E2zlcGqvYJZvp0hlFqJbI1KhgMlozrChZcEFlYU0_leEXAp7JiwokC0ZloyRN9o3YA4siHolsHIR1tcOKnAoHSYaU
:scheme: https
accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8
accept-encoding: gzip, deflate, br
accept-language: en-US,en;q=0.9
cache-control: max-age=0
cookie: __RequestVerificationToken=S5Juj1hBkXIjmD-grTT7GznV6FrUMuyGCBmI5JoL9wXGoo3l9PKqscj54umCFGOSuK5pmx6Kjv8ap9QJ8q6ixNF2M9syQkq-iwDchS5m1u81; ASP.NET_SessionId=xaj1bb3qc5mzuefk3imxhhnl; .AspNet.Correlation.Facebook=pfQHMd0GIkxHeDwrLwGzcUdfmCUPPS2tR9G_WFPeueE
dnt: 1
referer: https://www.facebook.com/
upgrade-insecure-requests: 1
user-agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36

为什么在以本地主机调试和运行应用程序时可以通过Facebook成功登录,但在发布到1and1.com之后却无法通过Facebook登录?

1 个答案:

答案 0 :(得分:0)

我知道这已经有一段时间了,但在与托管团队进行故障排除后,他们建议我将其放在 web.cofig 中,并且它奏效了!

<system.net> <defaultProxy> <proxy usesystemdefault = "false" bypassonlocal="false" proxyaddress="http://ntproxy.1and1.com:3128" /> </defaultProxy> </system.net>