【问题标题】:ASP.NET identity auth session and cookie works only locallyASP.NET 身份验证会话和 cookie 仅在本地工作
【发布时间】:2018-04-14 14:22:07
【问题描述】:

我正在使用 ASP.NET Identity,它可以通过常规登录和外部登录在本地完美运行。出于某种原因,当我发布我的项目并在远程服务器上运行它时,我有大约 1 分钟的授权会话。 1 分钟后,我被重定向到我的登录页面。 (没有错误信息)

我的启动验证配置:

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"),
                ExpireTimeSpan = TimeSpan.FromDays(2),
                Provider = new CookieAuthenticationProvider
                {
                    OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, VisU>(
                        validateInterval: TimeSpan.FromMinutes(30),
                        regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
                }
            });
            var googleOptions = new GoogleOAuth2AuthenticationOptions()
                   {
                       ClientId = "***",
                       ClientSecret = "***",
                       SignInAsAuthenticationType = DefaultAuthenticationTypes.ExternalCookie,
                       Provider = new GoogleOAuth2AuthenticationProvider()
                       {
                           OnAuthenticated = (context) =>
                       {
                           context.Identity.AddClaim(new Claim("urn:google:name", context.Identity.FindFirstValue(ClaimTypes.Name)));
                           context.Identity.AddClaim(new Claim("urn:google:email", context.Identity.FindFirstValue(ClaimTypes.Email)));
                           context.Identity.AddClaim(new Claim("urn:google:accesstoken", context.AccessToken, ClaimValueTypes.String, "Google"));
                           return Task.FromResult(0);
                       }
                   }
               };
               app.UseGoogleAuthentication(googleOptions);
}

我的帐户控制器:

[AllowAnonymous]
public ActionResult Login(string returnUrl)
{
    ViewBag.ReturnUrl = returnUrl;
    return View();
}


[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<string> Login()
{
            var result = await SignInManager.PasswordSignInAsync(Request.Form["emailLogin"], Request.Form["passwordLogin"], true, shouldLockout: true);
            switch (result)
            {
                case SignInStatus.Success:
                    return ViewBag.ReturnUrl ?? "https://localhost:44300/Account";
                case SignInStatus.LockedOut:
                    return Resources.Multilang.ERRORLockedOut;
                case SignInStatus.Failure:
                    //Mail or password are incorrect
                    return Resources.Multilang.ERRORInvalidLogin;
                default:
                    return Resources.Multilang.ERRORInvalidLogin;
            }
  }

这种行为的原因可能是什么?

(“https://localhost:44300/”发布时改成我的域名了。)

【问题讨论】:

  • 猜测:任何roles 对限制访问(和重定向)的资源?
  • 是的。我以管理员角色登录用户并在仅限于管理员角色的页面上工作。本地效果很好,但在服务器上,我在 1 分钟后被重定向到登录页面。
  • 有多少台服务器?如果 >1 并且在负载均衡器之后,您可能会遇到会话问题。
  • 您是否在 web.config 中设置了机器密钥?这就是 .NET 用来加密/解密身份验证 cookie 的方法。如果未设置并且您使用某种类型的共享主机(例如 Azure),则不同的 Web 服务器将无法读取 cookie。通过设置机器密钥,您可以确保应用程序的任何实例都能够读取执行授权所需的相关 cookie。
  • 汤米,非常感谢!不知道我怎么错过了!请发表您的评论作为我问题的答案,以便我将其标记为答案!

标签: c# asp.net-mvc authentication asp.net-identity


【解决方案1】:

此问题的最常见原因之一是未在 web.config 中设置 MachineKey 元素。 MachineKey 用于加密和解密诸如您的授权 cookie 之类的内容。当MachineKey元素没有设置时,IIS会为你补一个MachineKey。

如果您将应用程序发布到 Azure 或 GoDaddy 等第 3 方网络托管服务,则会出现问题。这些提供商通常在不止一台 Web 服务器上拥有 Web 应用程序。因为如果没有设置,Web 服务器将组成自己的MachineKey,因此托管您的应用程序的每个 Web 服务器都将拥有自己的 MachineKey。最终结果是 Web 服务器 A 发布并加密了授权 cookie。如果下一个请求发送到 Web 服务器 B,它将无法解密和读取 cookie,因此它假定您没有登录。

在您的 web.config 中设置 MachineKey 可确保托管您的应用程序的每个 Web 服务器都可以毫无问题地加密和解密授权 cookie。

【讨论】:

    猜你喜欢
    • 2010-10-02
    • 1970-01-01
    • 1970-01-01
    • 2015-03-25
    • 1970-01-01
    • 2019-10-28
    • 2016-06-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多