微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

.NET 5、ASP .NET Core 5 应用程序 ajax 发布请求 cookie 为空

如何解决.NET 5、ASP .NET Core 5 应用程序 ajax 发布请求 cookie 为空

标题所述,我有一个 ASP.NET Core 5 MVC 应用程序,它部署在 Windows 2019 服务器上的 IIS 上。

这是一些细节

ASP.NET Core version ->
dotnet --version 5.0.301
IIS Version: 10.0.17763.1

dotnet --info输出

.NET SDK (reflecting any global.json):
Version: 5.0.301
Commit: ef17233f86

当我使用 POST 方法发送 ajax 请求时,它无法通过身份验证,这要求 cookie 中存在一些声明。

请求很简单:

$.ajax({
           url: '@Url.Action("Index","ControllerTest")',type: "POST",dataType: "json",data: formData,success: function (response) {
               if (response.success) {
                   window.location.href = '@Url.Action("Index","Controller2",new { Area = "MyArea" })?ID=' + response.ID;
               }
               else
                   window.location.href = '@Url.Action("Index",new { Area = "MyArea" })';
           },error: function (xhr,textStatus,errorThrown) {
               // Error code
           }
       });

控制器上的授权是

[Authorize(Policy = "Require.Ldap.User",AuthenticationSchemes = CookieAuthenticationDefaults.AuthenticationScheme)]

非常奇怪的是:在本地主机上它可以工作。在我与 IIS 一起放置的 Azure VM 上,它可以工作。在装有 IIS 的客户机器上,我收到此错误

我设置了这样的 cookie 身份验证:

var cookiesConfig = this.Configuration.GetSection("CookiesOptions")
                                      .Get<CookiesOptions>();

services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
         .AddCookie(options =>
                {
                    options.Cookie.Name = cookiesConfig.CookieName;
                    options.LoginPath = cookiesConfig.LoginPath;
                    options.logoutPath = cookiesConfig.logoutPath;
                    options.AccessDeniedpath = cookiesConfig.AccessDeniedpath;
                    options.ReturnUrlParameter = cookiesConfig.ReturnUrlParameter;
                    options.ExpireTimeSpan = TimeSpan.FromSeconds(cookiesConfig.TokenExpireInSeconds);
                });
 
    services.AddAuthorization(options =>
            {
                options.AddPolicy("Require.Ldap.User",policy =>
                                  policy.RequireClaim("MYAPP_ENABLED_USER","true")
                                        .AddAuthenticationSchemes(CookieAuthenticationDefaults.AuthenticationScheme)
                                      );
            });

然后在调用 Login(使用 [AllowAnonymous])后的控制器上我使用这个

var userClaims = new List<Claim>
                        {
                            new Claim(ClaimTypes.Name,user.Username),new Claim(ClaimTypes.WindowsAccountName,userDescription),};

var claimsIdentity = new ClaimsIdentity(userClaims,authService.GetType().Name);

claimsIdentity.AddClaim(new Claim("MYAPP_ENABLED_USER","true"));

await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme,new ClaimsPrincipal(claimsIdentity),new AuthenticationProperties
                            {
                                IsPersistent = model.RememberMe
                            }
                        );

return Redirect(Url.IsLocalUrl(model.ReturnUrl)
                            ? model.ReturnUrl
                            : "/");

查看 Chrome 开发者控制台,我得到一个共同点

POST MyApplication/Controller/Action 401 (Unauthorized)

没有任何其他细节

我的控制器有这个认证

[Authorize(Policy = "Require.Ldap.User",AuthenticationSchemes = CookieAuthenticationDefaults.AuthenticationScheme)]

真正的奥秘在于:

  • localhost Visual Studio 工作
  • 我使用 IIS 设置的带有 Windows Server 2019 的 Azure VM 运行良好且完美无缺。
  • 使用 Windows Server 2019 和相同 IIS 版本的客户虚拟机产生该错误

我还通过将其放入 appsettings.json添加了一些登录事件查看器:

{
  "Logging": {
    "LogLevel": {
      "Default": "information","Microsoft": "Warning","Microsoft.Hosting.Lifetime": "information"
    },//This sets our debug level in event view
    "EventLog": {
      "LogLevel": {
        "Default": "information"
      }
    }
  },

这是在客户服务器上的事件查看器中显示内容

################################### 类别:Microsoft.AspNetCore.Hosting.Diagnostics事件 ID:1 SpanId: ab3998eb3f2a4048 TraceId:180f1ccebad55449a5c211e9dabf3c20 ParentId: 0000000000000000 请求 ID:800000a7-0001-ff00-b63f-84710c7967bb 请求路径:/MyApplication/Home/Login

请求开始 HTTP/1.1 POST http://CustomerVirtualMachineHost/MyApplication/Home/Login application/json;+charset=UTF-8 59

################################### 类别:Microsoft.AspNetCore.HttpsPolicy.HstsMiddleware事件 ID:1 SpanId: ab3998eb3f2a4048 TraceId:180f1ccebad55449a5c211e9dabf3c20 ParentId: 0000000000000000 请求 ID:800000a7-0001-ff00-b63f-84710c7967bb 请求路径:/MyApplication/Home/Login

请求不安全。跳过 HSTS 标头。

################################### 类别:Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware事件 ID:1 SpanId:ab3998eb3f2a4048 TraceId:180f1ccebad55449a5c211e9dabf3c20 ParentId: 0000000000000000 RequestId: 800000a7-0001-ff00-b63f-84710c7967bb 请求路径: /MyApplication/Home/登录

不支持POST请求 ################################### 类别:Microsoft.AspNetCore.Routing.Matching.DfaMatcher EventId : 1001 跨度 ID: ab3998eb3f2a4048 TraceId:180f1ccebad55449a5c211e9dabf3c20 ParentId: 0000000000000000 请求 ID:800000a7-0001-ff00-b63f-84710c7967bb 请求路径:/MyApplication/Home/Login

为请求路径“/MyApplication/Home/Login”找到 1 个候选

################################### 类别:Microsoft.AspNetCore.Routing.Matching .DfaMatcher EventId: 1005 SpanId: ab3998eb3f2a4048 TraceId:180f1ccebad55449a5c211e9dabf3c20 ParentId: 0000000000000000 请求 ID:800000a7-0001-ff00-b63f-84710c7967bb 请求路径:/MyApplication/Home/Login

端点 'MYAPPLICATION.Areas.MyApplication.Controllers.HomeController.Login (MYAPPLICATION)' 带有路由模式 'MyApplication/{controller=Home}/{action=Index}/{id?}' 适用于 请求路径'/MyApplication/Home/Login'

################################### 类别:Microsoft.AspNetCore.Routing.EndpointRoutingMiddleware事件 ID:1 SpanId:ab3998eb3f2a4048 TraceId:180f1ccebad55449a5c211e9dabf3c20 ParentId: 0000000000000000 RequestId: 800000a7-0001-ff00-b63f-84710c7967bb 请求路径: /MyApplication/Home/登录

请求匹配的端点 'MYAPPLICATION.Areas.MyApplication.Controllers.HomeController.Login (我的应用程序)'

################################### 类别:Microsoft.AspNetCore.Authentication.Cookies .CookieAuthenticationHandler 事件 ID:7 SpanId:ab3998eb3f2a4048 跟踪 ID: 180f1ccebad55449a5c211e9dabf3c20 ParentId: 0000000000000000 RequestId: 800000a7-0001-ff00-b63f-84710c7967bb 请求路径: /MyApplication/Home/登录

Cookie 未经过身份验证。失败消息:票已过期

################################### 类别:Microsoft.AspNetCore.Authorization.DefaultAuthorizationService 事件 ID:2 跨度 ID:ab3998eb3f2a4048 跟踪 ID: 180f1ccebad55449a5c211e9dabf3c20 ParentId: 0000000000000000 RequestId: 800000a7-0001-ff00-b63f-84710c7967bb 请求路径: /MyApplication/Home/登录

授权失败。这些要求没有得到满足: DenyAnonymousAuthorizationRequirement:需要经过身份验证的用户。 ClaimsAuthorizationRequirement:Claim.Type=MYAPPLICATION_ENABLED_USER 和 Claim.Value 是以下值之一:(true)

################################### 类别:Microsoft.AspNetCore.Authentication.Cookies .CookieAuthenticationHandler 事件 ID:12 跨度 ID:ab3998eb3f2a4048 跟踪 ID: 180f1ccebad55449a5c211e9dabf3c20 ParentId: 0000000000000000 RequestId: 800000a7-0001-ff00-b63f-84710c7967bb 请求路径: /MyApplication/Home/登录

AuthenticationScheme:Cookie 受到质询。

################################### 类别:Microsoft.AspNetCore.Hosting.Diagnostics事件 ID:2 SpanId: ab3998eb3f2a4048 TraceId:180f1ccebad55449a5c211e9dabf3c20 ParentId: 0000000000000000 请求 ID:800000a7-0001-ff00-b63f-84710c7967bb 请求路径:/MyApplication/Home/Login

请求完成 HTTP/1.1 POST http://CustomerVirtualMachineHost/MyApplication/Home/Login

application/json;+charset=UTF-8 59 - 401 - - 2.7820ms

它可以是什么?我该如何解决这个问题? 是 IIS 的一些 cookie 设置吗?

我怀疑这与某些 IIS cookie 配置有关,或者可能与用户浏览器和驻留在不同域的客户服务器之间的差异有关?

有人可以帮我吗?

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。