Angular 2 - Consuming restful api calls with windows authentication

天大地大妈咪最大 提交于 2019-12-06 04:30:32

You need to check if the Authorization header is correctly sent within your request. If you forgot to import the Headers class, the header won't be sent:

import {Http, Headers, ...} from 'angular2/http';

Another option would be that, since you are in the case of a preflighted request (GET method with the Authorization header), an OPTIONS request is sent. In fact, this request is transparently sent by the browser and the credentials are present in it. So you don't have to check security here on the server side. Otherwise you will have a 401 error since the server won't be able to authenticate the request...

See these articles for more details:

I have stumbled upon the same problem when using Angular 2 within an ASP.NET Core solution. For me, I had the explicitly specify withCredentials: true:

  getSomeModels() {
      return this.http.get(this.apiBasePath + 'models', { withCredentials: true })
          .map(res => res.json());
  }

CORS must be enabled on the server side (Web API) and no other changes were required on the client side.

NOTE: Server side code to enable CORS (Startup.cs)

public void ConfigureServices(IServiceCollection services)
{
    // injected services
    services.AddAuthorization();
    services.AddMvc();

    //db context

    var corsBuilder = new CorsPolicyBuilder();
    corsBuilder.AllowAnyHeader();
    corsBuilder.AllowAnyMethod();
    corsBuilder.AllowAnyOrigin(); // For anyone access.
    corsBuilder.AllowCredentials();

    services.AddCors(options =>
    {
        options.AddPolicy("SiteCorsPolicy", corsBuilder.Build());
    });
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
      // middleware configuration

      app.UseCors("SiteCorsPolicy");
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!