c# - CORS 预检选项请求从 Windows 身份验证的 web api 返回 401(未经授权)

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

我有一个使用 Windows 身份验证.NET Web API 项目。在我的开发环境中,我无法使用来 self 的 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 中执行以下操作,请告诉我):

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 服务(将组件的数据发布到我的 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 header 。但我不知道要传递什么作为 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 应用程序的默认端口?

您也可以像这样添加 header (前提是您有不记名 token ):

将下面的 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);
      });

关于c# - CORS 预检选项请求从 Windows 身份验证的 web api 返回 401(未经授权),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51566333/

相关文章:

c# - ASP.NET CurrentUICulture 在任务和 WebAPI 延迟结果中的行为不同

asp.net - 如何在 Web API 中捕获 SerializationException?

c# - 使用自托管 Web Api 服务进行热部署

c# - .Net 日期计算的循环库

c# - 使用 Async/Await 时,如何在请求属性更改时更新所有请求?

Angular 内插值未在订阅时更新

angular - 如何在 Angular2 2.0.0 RC.5 中设置全局提供者?

javascript - 如何在 CheckboxList selectedIndexChange 上显示确认框?

c# - 解析复杂 json 字符串的最佳实践

Angular 5 ngfor同时让两个变量