CORS预检OPTIONS请求从Windows身份验证的Web API返回401(未经授权)

时间:2018-07-27 22:31:36

标签: c# angular asp.net-web-api cors windows-authentication

我有一个使用.NET Web API的{​​{1}}项目。在开发环境中,我无法使用Windows Authentication应用中的数据成功完成POST请求。它返回:

Angular

我尝试了使用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. 实现cors的所有方法,但均无济于事。但是目前,我已经从项目中删除了Microsoft.AspNet.WebApi.Cors软件包,而推荐使用Microsoft.AspNet.WebApi.Cors方法(如果我实际上仍然需要安装web.config来执行{{1}中的以下操作},请让我知道)

Web.config:

Microsoft.AspNet.WebApi.Cors

.NET Web API'ValuesController.cs':

Web.config

Angular组件(将数据发送到我的Angular服务):

<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>

Angular Service(将组件的数据发布到我的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) { } } } ):

  constructor(private myService: MyService) {
    this.myService.myPost({ID: 1, FirstName: 'Bob'})
    .subscribe(
      data => console.warn(data),
      err => console.error(err),
      () => console.log("empty")
    );
  }

从我的研究看来,也许我需要通过服务中的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); } } 标头。但是我不知道将Authorization属性的值作为什么传递。请参阅下面的问号: MyService.ts

httpOptions

也许这甚至不是我的问题。 CORS + Windows身份验证-有什么想法吗?

2 个答案:

答案 0 :(得分:0)

您是否允许来自端口4200的CORS连接,端口4200是使用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);
      });

答案 1 :(得分:0)

已添加:

App_Start / WebApiConfig-注册方法:

config.EnableCors();

如果不起作用,请尝试

FooController:

[EnableCors(origins: "*", headers: "*", methods: "*")]