我使用身份验证创建了一个全新的ASP.NET MVC项目。
自动生成的Startup.Auth.cs
具有以下代码:
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),
}
});
// ......
上面的重要部分是LoginPath
,设置为 /帐户/登录(这是默认设置)。
当我尝试在没有登录的情况下访问具有[Authorize]
属性的页面/操作时,我被重定向到该登录页面,如检测到的那样。
在我的Global.asax.cs
文件中,我输入了以下代码:
protected void Application_EndRequest(object sender, EventArgs e)
{
var subnet = ConfigurationManager.AppSettings["SubnetForWindowsAuthentication"].ToString().Split(';');
if (this.Response.StatusCode == 302
&& this.Response.RedirectLocation.Contains("/Account/Login")
&& subnet.Any(ip => this.Request.UserHostAddress.Contains(ip))
&& this.Request.Browser.Win32)
{
this.Response.StatusCode = 401; // ask the browser to negotiate an identity
this.Response.SuppressFormsAuthenticationRedirect = true;
}
}
当用户被重定向时,StatusCode
是302.现在,我需要检查用户是否被重定向到登录页面。问题是this.Response.RedirectLocation
是null
,即使响应状态代码是302。
为什么this.Response.RedirectLocatio
为空?
有趣的是this.Response.Headers["location"]
有我要重定向的网址(也应该是this.Response.RedirectLocation
)。我可以直接使用标题来检查URL是否包含 / Account / Login ,但是当我将this.Response.StatusCode
更改为401时,应该挑战浏览器协商Windows身份验证标识,例如,但它只是失败显示IIS错误页面显示: HTTP错误401.0 - 未经授权。
我正在尝试实现提议的解决方案in this link,但我没有使用表单身份验证,而是使用ASP.NET身份。