如果未经授权,ASP.NET Identity (MVC 5) 对ajax请求返回200。

问题描述 投票:0回答:1

我使用ASP.NET Identity (MVC 5),如果用户不再被授权,ajax请求将返回200,而不是302(重定向)或401(未授权)。

app.UseCookieAuthentication(new CookieAuthenticationOptions {
    AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
    LoginPath = new PathString("/Account/Login"),
    ExpireTimeSpan = TimeSpan.FromMinutes(20),
    SlidingExpiration = true,
    Provider = new CookieAuthenticationProvider {
        OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser, int>(
            validateInterval: TimeSpan.FromMinutes(15),
            regenerateIdentityCallback: (manager, user) => user.GenerateUserIdentityAsync(manager), getUserIdCallback: (id) => (id.GetUserId<int>())),

    }
}); 

通过FilterConfig进行授权。

public static void RegisterGlobalFilters(GlobalFilterCollection filters) {
    filters.Add(new AuthorizeAttribute());
}

简单的ajax表单。

@using (Ajax.BeginForm("Index2", "Home", null, new AjaxOptions {
    InsertionMode = InsertionMode.Replace,
    HttpMethod = "POST",
    UpdateTargetId = "content",
}, new { id = "Test" })) {

    @Html.AntiForgeryToken()

    <input type="submit" value="Submit Data" id="btnSubmit" />
}

如果我登录到应用程序中,它就会像预期的那样工作。如果我删除了 .AspNet.ApplicationCookie 然后它返回一个200状态码

HTTP/2 200 OK
cache-control: private
server: Microsoft-IIS/10.0
x-aspnetmvc-version: 5.2
x-aspnet-version: 4.0.30319
x-responded-json: {"status":401,"headers":{"location":"https:\/\/localhost\/TestApp\/Account\/Login?ReturnUrl=%TestApp%2FHome%2FIndex2"}}
x-powered-by: ASP.NET
date: Tue, 16 Jun 2020 14:36:49 GMT
content-length: 0
X-Firefox-Spdy: h2

如果我检查Global.asax中的Application_EndRequest(),也有200状态码。我只是在上面的response中可以看到是一个x-responded-json的401。但ajax错误函数 error: function (xhr, ajaxOptions, thrownError) 并没有被调用。

我只知道这样的解决方案,在表单认证的情况下。https:/www.codeproject.comarticles1056969asp-mvc-handle-ajax-errors-properly

但是我不能在ASP.NET Identity中使用这个功能,因为响应会是200代码而不是302。

我如何用ASP.NET Identity (MVC5)解决这个问题?目前我将得到一个空的响应...

asp.net-mvc asp.net-mvc-5 asp.net-identity
1个回答
0
投票

200只是意味着调用没有错误。302可能不存在,因为你使用的是ajax调用,而且,会话已经过期。当用户的授权过期时,防止中间件调用ajax的一种方法是在头中检查是否有Auth,或者在全局ajax处理程序中使用任何机制。这些全局处理程序在附加的任何其他事件之前启动,所以如果用户没有得到授权,你可以防止传播。

$(document).ajaxError(function (event, jqxhr, settings, data) {
    _ajaxHandler.handleAjaxError(event, jqxhr, settings, data);
});
$(document).ajaxSuccess(function (event, jqxhr, settings, exception) {
    _ajaxHandler.handleAjaxSuccess(event, jqxhr, settings, exception)
});
© www.soinside.com 2019 - 2024. All rights reserved.