对于jquery–使用CORS预检OPTIONS请求的Ajax防伪POST(302重定向)感兴趣的读者,本文将会是一篇不错的选择,并为您提供关于302重定向后的AJAX调用将origin设置为null
对于jquery – 使用CORS预检OPTIONS请求的Ajax防伪POST(302重定向)感兴趣的读者,本文将会是一篇不错的选择,并为您提供关于302重定向后的AJAX调用将origin设置为null、ajax – AWS S3 CORS 403 OPTIONS请求出错、ajax – 为什么我的跨域POST请求被OPTIONS请求预检?、angularjs – CORS预检请求在Azure托管的Web API中响应302重定向的有用信息。
本文目录一览:- jquery – 使用CORS预检OPTIONS请求的Ajax防伪POST(302重定向)
- 302重定向后的AJAX调用将origin设置为null
- ajax – AWS S3 CORS 403 OPTIONS请求出错
- ajax – 为什么我的跨域POST请求被OPTIONS请求预检?
- angularjs – CORS预检请求在Azure托管的Web API中响应302重定向
jquery – 使用CORS预检OPTIONS请求的Ajax防伪POST(302重定向)
$.ajaxPrefilter(function (options,localOptions,jqXHR) { if (options.type == "POST") { var token = GetAntiForgeryToken(); jqXHR.setRequestHeader(token.name,token.value); } });
当以管理员身份登录时,该站点还具有管理工具,该管理员使用CORS将数据发送到单独的管理站点.其中一个工具是AJAX发布请求.标头添加到请求中,它可以正常工作.
另一个工具是GET请求,它返回一个表单,该表单显示在对话框中.这很好用.但是,当提交表单时,预检OPTIONS请求遇到302,我收到错误“预检的响应无效(重定向)”
如果我删除ajaxPrefilter,表单发布工作,但直接发布请求不起作用.启用Prefilter后,直接发布请求有效,但表单发布没有.我很丢失. Access-Control-Allow-Headers中允许使用防伪标头.对两者的要求是:
OPTIONS http://localhost:64789/Example/Example/?_=1464356730712 HTTP/1.1 Host: localhost:64789 Connection: keep-alive Access-Control-Request-Method: POST Origin: http://localhost:64947 User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML,like Gecko) Chrome/50.0.2661.102 Safari/537.36 Access-Control-Request-Headers: __requestverificationtoken,accept,content-type Accept: */* Referer: http://localhost:64947/ Accept-Encoding: gzip,deflate,sdch Accept-Language: en-GB,en-US;q=0.8,en;q=0.6
这个返回302.
OPTIONS http://localhost:64789/Example2/Example2/ HTTP/1.1 Host: localhost:64789 Connection: keep-alive Access-Control-Request-Method: POST Origin: http://localhost:64947 User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML,en;q=0.6
这个返回200.
任何帮助都非常有用.
解决方法
302重定向后的AJAX调用将origin设置为null
我正在从域A到域B进行AJAX呼叫。
我的域B检查A是否在允许的域列表中,并将设置Access-Control-allow-Origin
为域A。到目前为止,一切都很好。
域B通过使用Location
标头向域C发送302重定向来响应请求。
AJAX调用遵循重定向到域C的操作,但具有标头: Origin: null
。
origin
在重定向之后,我希望将标头设置为域A。
谁能向我解释为什么将源设置null
为域A而不是域A?
例
- 从域A到B的请求
GET / HTTP/1.1 Host: domain-B.com Origin: http://domain-A.com
- 来自网域B的回应:
Access-Control-Allow-Origin: http://domain-A.com Location: http://domain-C.com
- AJAX调用将重定向到域C:
GET HTTP/ 1.1 Host: domain-C.com Origin: null
答案1
小编典典看到这里,这似乎暗示了它与“对隐私敏感”的上下文有关。
ajax – AWS S3 CORS 403 OPTIONS请求出错
我在线阅读AWS,如果我这样做,我需要设置AWS CORS规则来修复403错误.
但是,我已经尝试了两天而且没有任何运气.这是我的CORS配置:
<?xml version="1.0" encoding="UTF-8"?> <CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/"> <CORSRule> <AllowedOrigin>*</AllowedOrigin> <AllowedMethod>GET</AllowedMethod> <MaxAgeSeconds>3000</MaxAgeSeconds> <ExposeHeader>XMLHttpRequest</ExposeHeader> <AllowedHeader>x-csrftoken</AllowedHeader> </CORSRule> </CORSConfiguration>
我的HTTP请求如下:
Accept text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 Accept-Encoding gzip,deflate Accept-Language en-US,en;q=0.5 Access-Control-Request-He... x-csrftoken Access-Control-Request-Me... GET Connection keep-alive Host xxxxxxxxx.cloudfront.net Origin http://localhost:8000 User-Agent Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:18.0) Gecko/20100101 Firefox/18.0
谁能帮我看看我错过了什么?
谢谢!
解决方法
Beavior -> Origin /api/* -> my.api.com /static/* -> my.s3.bucket
但是,如果您确实需要跨源请求,则CORS标头应该由cloudfront转发并具有相同的行为,在您的示例中,您可能希望对您允许的标头更宽松(< AllowedHeader> *< / AllowedHeader> ?).但这与浏览器行为的关系比CLoudFront或S3更重要.
ajax – 为什么我的跨域POST请求被OPTIONS请求预检?
我在Firefox中没有得到这种行为,我根本不理解为什么会这样.这是我的设置代码:
function makeXDomainRequest(url,method,data) { var req = typeof XDomainRequest !== "undefined" ? new XDomainRequest() : new XMLHttpRequest(); req.open(method || "GET",url,true); if (typeof req.onload !== "undefined") { req.onload = onResponseLoad; req.onerror = onRequestError; } else { req.onreadystatechange = onRequestStateChange; } if (data && typeof req.setRequestHeader === "function") { req.setRequestHeader("Content-Type","application/x-www-form-urlencoded"); } else { // no way to set Content-Type req header in IE's XDomainRequest: // http://blogs.msdn.com/b/ieinternals/archive/2010/05/13/xdomainrequest-restrictions-limitations-and-workarounds.aspx } req.send(data || null); } function onResponseLoad() { alert("Response!\n" + this.responseText); } function onRequestError(args) { alert("Error!"); } function onRequestStateChange() { if (this.readyState === 4) { if (this.status === 200) { onResponseLoad.apply(this); } else { onRequestError.apply(this); } } }
这是我正在ping的服务器:
// thanks to http://saltybeagle.com/cors/ for having this demo endpoint: var URL = "http://ucommbieber.unl.edu/CORS/cors.PHP";
现在,如果我执行简单的POST请求 – 在上面的代码中将数据作为application / x-www-form-urlencoded发送 – 请求在Firefox中带有OPTIONS请求预检.它没有在Chrome中预检.在运行之前打开fiddler来亲眼看看:
makeXDomainRequest(URL,"POST","name=foobar"); // alerts "Response! Hello CORS [...] You sent a POST request. Your name is foobar"
这是fiddler中的预检OPTIONS请求(请注意Access-Control-Request-Method:POST标头,即使我指定了一个所谓的安全Content-Type而且没有自定义标头):
OPTIONS http://ucommbieber.unl.edu/CORS/cors.PHP HTTP/1.1 Host: ucommbieber.unl.edu User-Agent: Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.2.8) Gecko/20100722 Firefox/3.6.8 Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 Accept-Language: en-us,en;q=0.5 Accept-Encoding: gzip,deflate Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7 Keep-Alive: 115 Connection: keep-alive Origin: http://localhost Access-Control-Request-Method: POST
这是怎么回事?这是Firefox中的错误,还是我做错了什么?谢谢!
解决方法
angularjs – CORS预检请求在Azure托管的Web API中响应302重定向
我有两个在Windows Azure上单独托管的ASP.NET Web应用程序,它们都与同一个Azure Active Directory租户相关联:
>带有AngularJS SPA前端的MVC应用程序和用于在客户端上处理Azure AD身份验证的adal.js库.
>带有Microsoft OWIN中间件的Web API,用于在服务器上处理Azure AD身份验证.
问题:
当角度引导客户端应用程序时,页面在通过oauth重定向到正确的Identity Authority后正确加载,并且adal.js库正确检索并存储每个应用程序的不同令牌(通过检查“资源/会话 – 存储”选项卡进行验证Chrome开发工具).但是,当客户端应用程序尝试访问或更新API中的任何数据时,CORS预检请求正在响应302重定向到Identity Authority,这会导致控制台中出现以下错误:
XMLHttpRequest cannot load 07001.
The request was redirected to
‘07002{authority-guid}/oauth2/authorize?response_type=id_token&redirect_uri=….etc..etc..’,
which is disallowed for cross-origin requests that require preflight.
示例标头(匿名):
Request OPTIONS /api/items HTTP/1.1 Host: webapi.azurewebsites.net Connection: keep-alive Access-Control-Request-Method: GET Access-Control-Request-Headers: accept,authorization Origin: https://mvcapp.azurewebsites.net User-Agent: Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML,like Gecko) Chrome/39.0.2171.99 Safari/537.36 Accept: */* Referer: https://mvcapp.azurewebsites.net/ Response HTTP/1.1 302 Found Content-Length: 504 Location: https://login.windows.net/{authority-guid}/oauth2/authorize?response_type=id_token&redirect_uri=https%3A%2F%2F....etc..etc.%2F&client_id={api-guid}&scope=openid+profile+email&response_mode=form_post&state=...etc... Server: Microsoft-IIS/8.0 X-Powered-By: ASP.NET Set-Cookie: ARRAffinity=4f51...snip....redact....db6d;Path=/;Domain=webapi.azurewebsites.net
我做了什么/尝试过
>确保Azure AD租户允许OAou2隐式流,如here和其他地方所述.
>确保API exposes access permissions和MVC / SPA registers for access使用那些公开的权限.
>在API的web.config中明确添加了一个OPTIONS动词处理程序(见下文).
>使用在API服务器上启用CORS的各种组合,OWIN本身以及EnableCorsAttribute(见下文).
问题
有没有办法让Azure AD租户关联的Web API不重定向CORS预检请求?
我在adal.js库和/或OWIN启动代码中缺少一些初始化设置(见下文)?
Azure门户中是否有允许OPTIONS请求通过OWIN管道的设置?
相关代码:
adal.js初始化
angular.module("myApp",["ngRoute","AdalAngular"]) .config(["$routeProvider","$locationProvider","$httpProvider","adalAuthenticationServiceProvider",function ($routeProvider,$locationProvider,$httpProvider,adalProvider) { $routeProvider.when("/",{ // other routes omitted for brevity templateUrl: "/content/views/home.html",requireADLogin: true // restrict to validated users in the Azure AD tenant }); // CORS support (I've tried with and without this line) $httpProvider.defaults.withCredentials = true; adalProvider.init({ tenant: "contoso.onmicrosoft.com",clientId: "11111111-aaaa-2222-bbbb-3333cccc4444",// Azure id of the web app endpoints: { // URL and Azure id of the web api "https://webapi.azurewebsites.net/": "99999999-zzzz-8888-yyyy-7777xxxx6666" } },$httpProvider); } ]);
OWIN中间件初始化
public void ConfigureAuth(IAppBuilder app) { // I've tried with and without the below line and also by passing // in a more restrictive and explicit custom CorsOptions object app.UseCors(CorsOptions.AllowAll); app.UseWindowsAzureActiveDirectoryBearerAuthentication( new WindowsAzureActiveDirectoryBearerAuthenticationoptions { TokenValidationParameters = new TokenValidationParameters { // Azure id of the Web API,also tried the client app id ValidAudience = "99999999-zzzz-8888-yyyy-7777xxxx6666" },Tenant = "contoso.onmicrosoft.com" } ); // I've tried with and without this app.UseWebApi(GlobalConfiguration.Configuration); }
WebApiConfig初始化
public static void Register(HttpConfiguration config) { // I've tried with and without this and also using both this // and the OWIN CORS setup above. Decorating the ApiControllers // or specific Action methods with a similar EnableCors attribute // also doesn't work. var cors = new EnableCorsAttribute("https://mvcapp.azurewebsites.net","*","*") { cors.SupportsCredentials = true // tried with and without }; config.EnableCors(cors); // Route registration and other initialization code removed }
API OPTIONS动词处理程序注册
<system.webServer> <handlers> <remove name="ExtensionlessUrlHandler-Integrated-4.0" /> <remove name="OPTIONsverbHandler" /> <remove name="TRACEVerbHandler" /> <add name="OPTIONSHandler" path="*" verb="OPTIONS" modules="IsapiModule" scriptprocessor="C:\Windows\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll" /> <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" /> </handlers> </system.webServer>
相关资源
在某个时间,我已经尝试了以下(以及更多)论坛和博客文章以及github示例代码中的所有可以想象的组合.
> ADAL JavaScript and AngularJS – Deep Dive
> Secure ASP.NET Web API 2 using Azure Active Directory,Owin Middleware,and ADAL
> Token Based Authentication using ASP.NET Web API 2,Owin,and Identity
> AzureADSamples/SinglePageApp-DotNet (github)
> AngularJSCORS (github)
> How to make CORS Authentication in WebAPI 2?
> AngularJS and OWIN Authentication on WebApi
<package id="Microsoft.Owin" version="3.0.0" targetFramework="net45" /> <package id="Microsoft.Owin.Cors" version="2.1.0" targetFramework="net45" />
处理程序的WebConfig选项:
<system.webServer> <handlers> <remove name="ExtensionlessUrlHandler-Integrated-4.0" /> <remove name="OPTIONsverbHandler" /> <remove name="TRACEVerbHandler" /> <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" /> </handlers>
你正在使用owin config中的specsiying cors选项做对了.
public void ConfigureAuth(IAppBuilder app) { app.UseWindowsAzureActiveDirectoryBearerAuthentication( new WindowsAzureActiveDirectoryBearerAuthenticationoptions { Audience = ConfigurationManager.AppSettings["ida:Audience"],Tenant = ConfigurationManager.AppSettings["ida:Tenant"] }); app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll); }
控制器不需要CORS相关属性.
[Authorize] public class ContactsController : ApiController { // GET api/<controller> public IEnumerable<string> Get() { return new string[] { "person1","person2" }; } // GET api/<controller>/5 public string Get(int id) { return "person" + id; }
WebAPIConfig不需要与CORS相关的条目.
工作示例如下:https://github.com/omercs/corsapisample
您可以使用以下代码在应用中进行测试:
app.factory('contactService',['$http',function ($http) { var serviceFactory = {}; var _getItems = function () { $http.defaults.useXDomain = true; delete $http.defaults.headers.common['X-Requested-With']; return $http.get('http://yourhostedpage/api/contacts'); }; serviceFactory.getItems = _getItems; return serviceFactory;
}]);
预检回应示例:
Remote Address:127.0.0.1:8888 Request URL:http://localhost:39725/api/contacts Request Method:OPTIONS Status Code:200 OK Request Headersview source Accept:*/* Accept-Encoding:gzip,deflate,sdch Accept-Language:en-US,en;q=0.8 Access-Control-Request-Headers:accept,authorization Access-Control-Request-Method:GET Host:localhost:39725 Origin:http://localhost:49726 Proxy-Connection:keep-alive Referer:http://localhost:49726/myspa.html User-Agent:Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML,like Gecko) Chrome/39.0.2171.99 Safari/537.36 Response Headersview source Access-Control-Allow-Credentials:true Access-Control-Allow-Headers:authorization Access-Control-Allow-Origin:http://localhost:49726 Content-Length:0 Date:Fri,23 Jan 2015 01:10:54 GMT Server:Microsoft-IIS/8.0 X-Powered-By:ASP.NET
今天关于jquery – 使用CORS预检OPTIONS请求的Ajax防伪POST(302重定向)的分享就到这里,希望大家有所收获,若想了解更多关于302重定向后的AJAX调用将origin设置为null、ajax – AWS S3 CORS 403 OPTIONS请求出错、ajax – 为什么我的跨域POST请求被OPTIONS请求预检?、angularjs – CORS预检请求在Azure托管的Web API中响应302重定向等相关知识,可以在本站进行查询。
本文标签: