带有凭据的HTTP CORS请求使用Axios失败

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

我有一个遗留的webforms asp.net网站和一个新的asp.net核心站点共享一个auth cookie。当我尝试使用TypescriptAxios(在核心站点中)向Web服务方法(在旧站点中)发出CORS HTTP请求时,除非我传递空数据对象,否则它将失败。例如:

此请求将失败:

    const url: string = "http://legacy.mydev.machine:1259/MyService.asmx/GetInformation";
    const optionsThatWontWork: AxiosRequestConfig = {
        withCredentials: true
    };
    axios.get(url, optionsThatWontWork)
        .then((response) => { console.log(response); })
        .catch((error) => { console.log(error); });

浏览器执行1 HTTP GET(无飞行前)请求,该请求返回HTTP 500,并在响应中显示以下消息

“对于意外以'/ GetInformation'结尾的URL,请求格式无法识别。”

但这有效:

    const url: string = "http://legacy.mydev.machine:1259/MyService.asmx/GetInformation";
    const optionsThatWillWork: AxiosRequestConfig = {
        withCredentials: true,
        data: {
            // Adding this empty data object makes a difference
        }
    };
    axios.get(url, optionsThatWillWork)
        .then((response) => { console.log(response); })
        .catch((error) => { console.log(error); });

在这种情况下,浏览器发出2个请求。第一个是HTTP OPTIONS请求,返回200,然后第二个是GET成功点击GetInformation端点并返回带有json数据的200。

比较2个HTTP GET消息时,我能看到的唯一区别是成功的消息有一个Content-Type: application/json;charset=utf-8头。

我尝试手动添加该标题,但这也不起作用:

    const optionsThatStillWontWork: AxiosRequestConfig = {
        withCredentials: true,
        headers: {
            "Content-Type": "application/json;charset=utf-8"
        },
    };

我使用Owin在遗留站点的Microsoft.Owin.Cors管道中配置了CORS:

Private Sub ConfigureCors(ByVal app As IAppBuilder)
    Dim corsPolicy = New CorsPolicy() With {
        .AllowAnyMethod = True,
        .AllowAnyHeader = True,
        .SupportsCredentials = True,
        .AllowAnyOrigin = False
    }

    corsPolicy.Origins.Add("http://newsite.mydev.machine:9050")

    Dim corsPolicyProvider = New CorsPolicyProvider With {
        .PolicyResolver = Function(context) Task.FromResult(corsPolicy)
    }

    Dim options = New CorsOptions With {
        .PolicyProvider = corsPolicyProvider
    }

    app.UseCors(options)
End Sub

注意:http://legacy.mydev.machine:1259http://newsite.mydev.machine:1259都在我的hosts文件中指向127.0.0.1的条目。

根据the axios documentationdata配置选项是

“仅适用于请求方法'PUT','POST'和'PATCH'”

......我同意的。

几个问题然后:

  1. 为什么添加空的data对象使这个工作?
  2. 为什么第一个例子没有进行飞行前?
  3. 遗留站点中的CORS设置是否正常?
typescript http cors axios asmx
1个回答
2
投票

这似乎是服务器端代码中的一个问题。

  1. 可能是因为Content-Type自动添加,因为提供了data。即使对于不发送有效负载的GET请求也是如此。
  2. 没有为"simple" request发送预检。在whilelist之外没有任何标题的GET查询不需要发送预检。
  3. 根本原因与CORS无关(因为它在“特殊”流程中返回200 OK,因为在“正常”流程中根本没有触及)

我认为检查处理请求的控制器代码是有意义的。假设应该明确指定内容类型。

顺便说一句,如果CORS预检失败,GET请求就不会有500内部服务器错误。选项预检将失败,下一步将不会有GET请求。

© www.soinside.com 2019 - 2024. All rights reserved.