请求头没有origin参数_CORS错误 - 在请求的资源上没有“Access-Control-Allow-Origin”头...

I am using an Angular front end to connect to a WEB API 2 backend. The failing use case is the following. When a user registers, on successful registration, they must be logged into the system and be redirected to a new page to collect further information. I am using TOKENS for authentication.

I have enabled CORS in the WebAPI config:

var cors = new EnableCorsAttribute("http://localhost:7812", "*", "*");

config.EnableCors(cors);

The registration request is successful and the response headers have the required CORS headers:

**Access-Control-Allow-Credentials:true

Access-Control-Allow-Origin:http://localhost:7812**

Content-Length:0

Date:Sun, 24 Aug 2014 09:31:55 GMT

Server:Microsoft-IIS/8.0

X-Powered-By:ASP.NET

X-SourceFiles:=?UTF-8?B?QzpcUHJvamVjdHNcVGVzdGluZ1xNYWx0QXBhcnRtZW50c1xNYWx0YXBhcnRtZW50cy5BUElcTWFsdGFwYXJ0bWVudHMuQVBJXGFwaVxhY2NvdW50XHJlZ2lzdGVy?=

In the next step I attempt to log in the user to the system. As part of the login, the front end requests a TOKEN from the server at Request URL:http://localhost:7802/token. The request header once again sends a Origin header Origin:http://localhost:7812 but this time I get the error : XMLHttpRequest cannot load http://localhost:7802/token. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:7812' is therefore not allowed access.

Anyone have any ideas?

解决方案

When dealing with CORS, we need to keep in mind that there may be two requests sent by the browsers for a non GET request. There is usually the preflight (OPTIONS) request and then the actual request (POST). During the preflight requests, the server needs to add the Access-Control-Allow-Origin header with the value matching the request Origin header. This authorizes the subsequent request to be sent.

For the subsequent/actual request, the server also needs to add the Access-Control-Allow-Origin header. Otherwise, this request fails.

When using the OWIN OAuthAuthorizationServerProvider, we need to customize the MatchEndpoint handler to manage the header logic. This handler is executed before validate client authentication.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值