我正在构建一个与使用ASP.NET Web API 2构建的API交互的Angular应用程序。我使用基本身份验证通过向每个请求发送授权标头需要身份验证:
I am building an Angular app that interacts with an API built with ASP.NET Web API 2. I am using Basic Authentication by sending an Authorization header with each request that requires authentication:
Angular snippet:
$http.defaults.headersmon['Authorization'] = authHeader;要求:
Accept:application/json, text/javascript Accept-Encoding:gzip, deflate, sdch Accept-Language:en-US,en;q=0.8 Access-Control-Max-Age:1728000 Authorization:Basic [base64 encoded credential couplet here] Connection:keep-alive DNT:1 Host: blah Origin:localhost:9000 Referer:localhost:9000/ User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_3) AppleWebKit/53这一切都可以,但预检 OPTIONS 请求与每个 GET 或 POST 请求一起发送。这主要影响应用程序的感知速度。我已经对CORS简单请求进行了大量阅读,似乎为了避免可怕的预检 OPTIONS 请求是为了避免在我的请求中添加任何自定义标头。我尝试了许多其他的东西,例如发送 Content-Type 的 text / plain ,但似乎是授权标头是违反CORS简单请求要求的东西。
This all works OKAY, but a preflight OPTIONS request is sent with every GET or POST request. This is majorly impacting the perceived speed of the application. I have done lots of reading on CORS "Simple Requests" and it seems that in order to avoid the dreaded preflight OPTIONS request is to avoid adding any custom headers in my requests. I've tried lots of other stuff like sending a Content-Type of text/plain, but it seems that the Authorization header is the thing that is violating the CORS "Simple request" requirement.
因此我似乎不得不将API移到使用基于令牌的身份验证/授权。为了避免预检请求,似乎我需要将令牌放在查询字符串中。这是可以的,因为它只是一个小的内部Web应用程序,无论如何只能由几个用户访问。我打算在控制器响应上实现缓存。由于每个对控制器操作的请求都会根据当前经过身份验证的用户在查询字符串中使用不同的令牌,这会使缓存无效吗?
So it seems that I may have to move the API over to use token based authentication/authorization. In order to avoid preflight requests, it seems that I will need to place the token in the query string. This is okay as it is only a small internal web app which will only be accessed by a couple of users anyway. I intend to implement caching on controller responses. As each request to an controller action will have a different token in the querystring based on the currently authenticated user, will this render cacheing useless?
所以:
nb我知道SO和其他地方还有其他一些线程在网上关于这一点,但他们都没有提供关于是否有可能避免预检请求 GET 和 POST 使用自定义 HTTP 授权标题时。
n.b I know there are a couple of other threads on SO and elsewhere on the web regarding this, but none of them tend to provide a definitive answer on whether it is possible to avoid preflight requests for GETs and POSTs when using custom HTTP authorization headers.
推荐答案我认为这篇文章(如何将CORS预检缓存应用于整个域)几乎说明了一切 - 你可以做的事情不多
I think this post (How to apply CORS preflight cache to an entire domain) pretty much says it all - there is not much you can do about this
一个简单的解决方案是为代理/网络服务器添加一个反向代理服务你的角应用程序(例如nginx)通过相同的域路由您的RESTful呼叫,例如appdomain/api - > apidomain。
The one simple solution is to add a reverse proxy to the proxy/webserver serving your angular app (e.g. nginx) to route your RESTful calls via the same domain, e.g. appdomain/api --> apidomain.
更多推荐
使用CORS避免预检OPTIONS请求
发布评论