Angular 2 AspNetCore WebApi CORS issue: Response f

2019-07-05 02:48发布

I am attempting to implement simple token based authentication in an Angular 2 RC6 application against an AspNetCore WebApi project that I've implemented in Visual Studio 2015.

I have put my sample application on github at: https://github.com/tonywr71/Snazzle which is a fully functioning application.

In the application, I click on the Login menu item, put in login and password information then click login.

It successfully returns am authentication token, which I store in isolated storage.

I then click on the Fetch Data menu item, it calls a Sample Controller that has an Authorize attribute on it. It passes the token, which is retrieved from isolated storage and added to the header. But it fails with an error.

The error I am getting is "XMLHttpRequest cannot load http://localhost:5100/api/SampleData/WeatherForecasts. Response for preflight has invalid HTTP status code 401"

WeatherForecasts is a WebApi method that returns some json that is consumed by the Angular 2 client component.

401 is unauthorized, and the reason it is getting an unauthorized is due to the preflight ORIGIN call, because headers are not sent for ORIGIN calls.

When I run it with Postman, there are no issues once the token is added - the method call works. That is because Postman does not need to worry about CORS.

So my question is, how can I get AspNetCore to not check ORIGIN calls for authentication? Or if that's not the correct approach, how am I supposed to achieve this? Is there some middleware that I'm supposed to add?

2条回答
冷血范
2楼-- · 2019-07-05 03:16

You will have to enable CORS on web api side.

To enabled CORS on web api side, you will have to do these steps-

First, add dependency in project.json - "Microsoft.AspNetCore.Cors": "1.0.0",

then enable CORS in startup.cs like this-

app.UseCors(builder => {
    builder.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader();
});

In case if you want to restrict to specific origin then you can do like this-

 app.UseCors(builder => builder.WithOrigins("example.com"));

You can find more information about CORS here

See if this helps.

查看更多
狗以群分
3楼-- · 2019-07-05 03:33

This helped me:

Go to Startup.cs file

Add the following in your ConfigureServices(IServiceCollection services) function

 services.AddCors(options =>
        {
            options.AddPolicy("CorsPolicy",
                builder => builder.AllowAnyOrigin()
                .AllowAnyMethod()
                .AllowAnyHeader()
                .AllowCredentials());
        });

And this in your Configure(IApplicationBuilder app) function :

 app.UseCors("CorsPolicy");
查看更多
登录 后发表回答