【发布时间】: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