[英]CORS preflight OPTIONS request returns 401 (Unauthorized) from Windows Authenticated web api
我有一个使用Windows Authentication
的.NET Web API
项目。 在我的开发环境中,我无法使用来自Angular
应用程序的数据成功发出POST
请求。 它返回:
OPTIONS http://localhost:9090/api/values 401 (Unauthorized)
Failed to load http://localhost:9090/api/values: Response for preflight has invalid HTTP status code 401.
我已经尝试了所有使用Microsoft.AspNet.WebApi.Cors
实现 cors 的方法,但无济于事。 但是目前我已经从我的项目中删除了Microsoft.AspNet.WebApi.Cors
包以支持web.config
方法(如果我实际上仍然需要安装Microsoft.AspNet.WebApi.Cors
来在Web.config
中执行以下操作,请让我知道) :
网络配置:
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="http://localhost:5200" />
<add name="Access-Control-Allow-Headers" value="*" />
<add name="Access-Control-Allow-Methods" value="GET,POST,PUT,DELETE,OPTIONS" />
<add name="Access-Control-Allow-Credentials" value="true" />
</customHeaders>
</httpProtocol>
.NET Web API 'ValuesController.cs':
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
namespace api.Controllers
{
[Authorize]
public class ValuesController : ApiController
{
// GET api/values
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
// GET api/values/5
public string Get(int id)
{
return "value";
}
// POST api/values
public void Post([FromBody]string value)
{
}
// PUT api/values/5
public void Put(int id, [FromBody]string value)
{
}
// DELETE api/values/5
public void Delete(int id)
{
}
}
}
Angular 组件(将数据发送到我的 Angular 服务):
constructor(private myService: MyService) {
this.myService.myPost({ID: 1, FirstName: 'Bob'})
.subscribe(
data => console.warn(data),
err => console.error(err),
() => console.log("empty")
);
}
Angular Service(将组件的数据发布到我的Web API
):
import { Injectable } from '@angular/core';
import { HttpClient, HttpResponse, HttpRequest, HttpHeaders, HttpInterceptor, HttpHandler, HttpEvent, HttpParams} from '@angular/common/http';
import { Observable } from 'rxjs';
import { from } from 'rxjs';
import { map, filter, catchError, mergeMap } from 'rxjs/operators';
@Injectable({
providedIn: 'root'
})
export class MyService {
constructor(private http: HttpClient) {
};
public myPost(body) {
const httpOptions = {
withCredentials: true
}
return this.http.post("http://localhost:9090/api/values", body, httpOptions);
}
}
从我的研究看来,我似乎需要通过服务中的httpOptions
变量在我的请求中传递一个Authorization
标头。 但我不知道要传递什么作为Authorization
属性的值。 请参阅下面的问号: MyService.ts
public myPost(body) {
const httpOptions = {
headers: new HttpHeaders({
'Authorization': '?????'
}),
withCredentials: true
}
return this.http.post("http://localhost:9090/api/values", body, httpOptions);
}
也许这甚至不是我的问题。 CORS + Windows 身份验证 - 有什么想法吗?
您是否允许来自端口 4200 的 CORS 连接,这是使用 Angular CLI 的 Angular 应用程序的默认端口?
您还可以像这样添加标头(前提是您有不记名令牌):
将下面的 GET 更改为 POST。
使用 Http
import { Http, Headers, Response } from '@angular/http';
const headers = new Headers({ 'Authorization': 'Bearer ' + token});
const options = {
headers: headers,
withCredentials: true
};
return this.http.get('http://localhost:9090/api/values', options)
.map((response: Response) => {
const stuff = response.json();
return stuff;
}).catch(error => Observable.throw(error));
使用 HttpClient
import { HttpClient, HttpHeaders } from '@angular/common/http';
const httpOptions = {
headers: new HttpHeaders({ 'Content-Type': 'application/json' }),
withCredentials: true
};
this.http
.post('http://localhost:9090/api/values', body, httpOptions)
.pipe(
catchError(this.handleErrors)
).subscribe((result: any) => {
return Observable.of(result);
});
添加 :
App_Start/WebApiConfig - 注册方法:
config.EnableCors();
如果不起作用,请尝试
Foo控制器:
[EnableCors(origins: "*", headers: "*", methods: "*")]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.