问题
我有一个 ASP.NET 站点,当我最初部署该站点时,该站点在登录/注销方面运行良好。当我重新部署新更改(通过替换文件)时,那些已登录(有 cookie)的人不再被识别为已登录。此外,他们无法登录,因为单击登录会将他们带到 azure 登录,然后它会重定向回到主页并没有检测到 cookie,所以它显示他们仍然注销。
仅当我部署到 QA (IIS 6.2) 时,这些事情都不会在 Visual Studio 和 IIS Express 中发生。
相关代码
帐户控制器
[AllowAnonymous]
public void SignIn()
{
if (Request.IsAuthenticated) { return; }
HttpContext.GetOwinContext().Authentication.Challenge(
new AuthenticationProperties() { RedirectUri = "/" }, OpenIdConnectAuthenticationDefaults.AuthenticationType
);
}
public void SignOut()
{
if (!Request.IsAuthenticated) { return; }
// SIGN OUT:
HttpContext.GetOwinContext().Authentication.SignOut(
OpenIdConnectAuthenticationDefaults.AuthenticationType, CookieAuthenticationDefaults.AuthenticationType
);
// COOKIE: Remove the cookie.
var cookie = Request.Cookies[FormsAuthentication.FormsCookieName];
cookie.Expires = DateTime.UtcNow.AddDays(-1);
Response.Cookies.Add(cookie);
}
AzureSettings 从 Startup.cs 运行
public static void ConfigureAzure(IAppBuilder app)
{
// COOKIES: Tells it to use cookies for authentication.
app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);
app.UseCookieAuthentication(new CookieAuthenticationOptions()
{
// CUSTOMIZE: This is where you would adjust cookie experiation and things of that nature.
});
//https://azure.microsoft.com/en-us/resources/samples/active-directory-dotnet-webapp-webapi-openidconnect/
// OPEN-ID: Handle OpenID stuff.
var notifications = new OpenIdConnectAuthenticationNotifications()
{
AuthenticationFailed = PrincipalService.OnAzureAuthenticationFailure,
// REFERENCE: https://russellyoung.net/2015/09/05/mvc-role-based-authorization-with-azure-active-directory-aad/
AuthorizationCodeReceived = PrincipalService.OnAzureAuthenticationSuccess
};
var options = new OpenIdConnectAuthenticationOptions()
{
ClientId = ClientID,
Authority = Authority,
PostLogoutRedirectUri = PostLogoutRedirectUri,
Notifications = notifications
};
app.UseOpenIdConnectAuthentication(options);
}
上面代码中引用的 PrincipalService.cs
/// <summary>
/// Redirects the user to the /Home/ErrorInfo page.
/// </summary>
public static Task OnAzureAuthenticationFailure(AuthenticationFailedNotification<OpenIdConnectMessage, OpenIdConnectAuthenticationOptions> context)
{
context.HandleResponse();
context.Response.Redirect("/Home/ErrorInfo");
return Task.FromResult(0);
}
/// <summary>
/// Stores the proper identity cookie (doesn't have customer permissions yet).
/// </summary>
public static Task OnAzureAuthenticationSuccess(AuthorizationCodeReceivedNotification context)
{
var username = context.AuthenticationTicket.Identity.Name;
try
{
StoreCookie(username);
}
catch (DbEntityValidationException ex)
{
var errors = ex.EntityValidationErrors.FirstOrDefault()?.ValidationErrors.FirstOrDefault()?.ErrorMessage;
Logger.Log(Level.Error, "An error occurred while storing authentication cookie.", ex);
}
catch (Exception ex)
{
Logger.Log(Level.Error, "An error occurred while storing authentication cookie.", ex);
}
return Task.FromResult(0);
}
/// <summary>
/// Creates and stores a forms authentication cookie for the user.
/// </summary>
private static void StoreCookie(string username, bool rememberMe = false)
{
Logger.Log(Level.Info, "Storing Cookie");
var azureUsers = new AzureUserRepository(new AuthenticationEntities());
var user = azureUsers.Get(u => u.Username == username);
if (user == null)
{
throw new NullReferenceException();
}
// Clear any old existing cookies.
HttpContext.Current.Request.RemoveFormsAuthCookie();
// Create the principal from the user object.
var principal = new PrincipalModel(user);
// Create and store the cookie in the response.
var serializer = new JavaScriptSerializer();
serializer.RegisterConverters(new JavaScriptConverter[] {
new ActivityConverter(),
new RoleConverter(),
new PrincipalModelConverter()
});
HttpContext.Current.Response.AddFormsAuthCookie(
username: user.Username,
userData: serializer.Serialize(principal),
isPersistent: rememberMe
);
}
概括
我在做什么导致这种情况?需要做些什么来防止这种情况发生?
我相信问题已经解决了。不确定我是否 100% 理解为什么,但在上面的代码中,我在添加它之前从请求而不是响应中删除了旧的 cookie。一旦我添加了从响应中删除cookie的代码,它就停止引起该问题。
(注意:如果有人能解释为什么会这样,我很乐意接受他们的回答)。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句