javascript xmlhttp error on signalr in asp.net core - asp.net-core

In my application 2 projects and mvc client run at port(5002) and web api project run at port (5001). I have implemented signalr in mvc client. Now showing error log in console as below:
and i have also added configuration to my api project for core policy like:
services.AddCors(options =>
{
options.AddPolicy("signalr",
builder =>
{
builder.WithOrigins("https://localhost:5002")
.AllowAnyHeader()
.AllowAnyMethod();
});
});
And now also showing same error. Please suggest.

You need to configure your CORS like this:
services.AddCors(options =>
{
options.AddPolicy("signalr", builder => builder.WithOrigins("https://localhost:5002")
.AllowAnyHeader()
.AllowAnyMethod()
.AllowCredentials()
.SetIsOriginAllowed((host) => true));
});
The lambda function that you pass to the .SetIsOriginAllowed() method returns true if an origin is allowed, so always returning true allows any origin to send requests to the api. The allow origin access control http header returned when using this method contains the origin that sent the request, not a wildcard, e.g. Access-Control-Allow-Origin: http://localhost:4200.

Related

ASP.NET Core 6 CORS and Angular 14 problem with published mode

I have an ASP.NET Core 6 project which client side is angular 14 .
I had enable CORS as code below :
var builder = WebApplication.CreateBuilder(args);
var MyAllowSpecificOrigins = "_myAllowSpecificOrigins";
builder.Services.AddCors(options =>
{
options.AddPolicy(name: MyAllowSpecificOrigins,
builder =>
{
builder.WithOrigins("https://consultation.programmerbox.ir",
"http://localhost:4200")
.AllowAnyHeader()
.AllowAnyMethod();
});
});
var app = builder.Build();
app.UseCors(MyAllowSpecificOrigins);
when i call the api with postman -> api return value as well as possible, when i call api in client project(development localhost) -> api return value as well as possible , but when publish both client and backend code in diffrent domain i get this error :
Access to XMLHttpRequest at 'https://api.consultation.programmerbox.ir/api/account/sendVerificationCode' from origin 'https://consultation.programmerbox.ir' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.
client domain is : https://consultation.programmerbox.ir
and backend domain is : https://api.consultation.programmerbox.ir/
I would be very grateful if you could guide me in this field, I am new in this field
With best regards
picture 1
picture 2

How to implement cross domain request for Office 365 OAuth2 login authentication?

I have used Office 365 OAuth2 login authentication for an ASP.NET Core API. This is working fine when accessing this API directly from browser. But, when I am calling this API from ajax request / other another web application, below Cors policy error occurred.
Access to XMLHttpRequest at 'https://login.microsoftonline.com/organizations/oauth2/v2.0/authorize?client_id=e0745314-9236-4fr2c-a2fg0-c19cjfsfrrrb6b&scope=api%3A%2F%2Fe0745314-9236-4fr2c-a2fg0-c19cjfsfrrrb6b%2Ftestapi&response_type=code&redirect_uri=https%3A%2F%2Flocalhost%3A44332%2Fsignin-oidc&state=CfDJ8Kp1w7Ui3OZMswaNrHvqNR2MF9qKa9w3PILEMBv8s_zxSa3sMK1pQLr2EuNexhz8eM6
iDdbO2ciuxInNPCtbO1KJ31O_zXvOA_sMXHbAhzzkXKN9QDmrHMUOiQQdjXjam4EqKlopDpcE2vUxcus
4WehJCUfCqdQZjMuzZS7ovrxslRX2ueRNFqpSDichJCf_iduXgFV1bNLRM8gK0TmjUrdkdYtyji7BNsNdPP
o9Fhad' (redirected from 'https://localhost:44332/api/login/account') **from origin 'null'** has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
I have tried to fix this issue using the following method in startup file. But, still I get this issue.
ConfigureServices:
services.AddCors(o => o.AddPolicy("CorsPolicy", builder =>
{
builder.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader();
}));
Configure:
app.UseCors("CorsPolicy");
**Client Application** : http://localhost:5000
**API** : http://localhost:44332
**Login provider** : Office 365
Please suggest me the standard way to implement cross origin and redirect to respective client application (http://localhost:5000) URL after getting authorization from Office 365?
Note : While redirect from API to Microsoft login "origin" become "null".
The server must allow the credentials. To allow cross-origin credentials, call AllowCredentials:
services.AddCors(o => o.AddPolicy("CorsPolicy", builder =>
{
builder.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials();
}));

Issue with SignalR core and cross domain requests

We are using SignalR core with CORS cross domain requests. The client is unable to connect to server. 401 Unauthorized No Access-Control-Allow-Origin' header is present on the requested resource. Error: Failed to start the connection. Note we are using the most recent signalr core (alpha version for asp.net core 2.0).
Please note within the same client app, i'm able to access CORS Web API methods. It's isolated to SignalR hub/client.
We are using Windows authentication in IIS. Anonymous seems to be working.
Server startup.cs:
ConfigureServices() method
services.AddCors();
services.AddSignalR();
Configure method
app.UseCors(x => x.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader().AllowCredentials());
app.UseSignalR(routes =>
{
routes.MapHub<TestHub>("test");
});
app.UseMvc();
javascript client:
let connection = new signalR.HubConnection(CORS_WEB_API_URL + '/test');
connection.on('send', data => {
console.log(data);
});
connection.start();
Please advise.
I know this is an old post, however, the answer is that with SignalR you cannot use wildcards in the CORS allow origin.
Needs to be specific. For development I use this:
services.AddCors(options => options.AddPolicy("CorsDev", builder =>
{
builder
.AllowAnyMethod()
.AllowAnyHeader()
.WithOrigins(AppSettings.SPAHost, "http://localhost:8099")
.AllowCredentials();
}));
Then in Configure in startup.cs
app.UseCors("CorsDev");
Hope this helps someone.
Just replace .AllowAnyOrigin() with .WithOrigins("*")
ConfigureServices:
services.AddCors(options => options.AddPolicy("CorsPolicy", builder =>
{
builder
.AllowAnyMethod()
.AllowAnyHeader()
.WithOrigins("*")
.AllowCredentials();
}));
Configure
app.UseCors("CorsPolicy");
Tested with
<PackageReference Include="Microsoft.AspNetCore.SignalR" Version="1.0.2" />

Asp.NET Core: cross-origin request to services (preflight) returns code 204 instead of 200

I have Asp.NET Core Web API application and trying to implement authorization but came across with CORS problem - my dev services and ui host on different ports of localhost.
On login page I get token and redirects to next page. At this time data requests to services start. But server responses with status 204: No Content for preflight request...
Although, preflight response returns Access-Control-Allow-Origin: * ...
The Startup.cs looks like:
public void ConfigureServices(IServiceCollection services)
{
// ...
services.AddCors(options =>
{
options.AddPolicy("Policy",
builder => builder.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader() );
});
services.AddAuthorization();
services.AddMvc() // ...
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
app.UseCors("Policy");
app.UseMvc();
}
Do I miss something on server side? (on client side angular's interceptor just adds Authorization header with token)
P.S. I use VS Code on OSX for developing (although it's not important as I guess)
UPDATE:
as #tpeczek adviced, I've change cors configuration to:
options.AddPolicy("Policy",
builder => builder.WithOrigins("http://localhost:80", "http://localhost")
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials() );
but can't get rid of error
UPDATE 2:
The error I get is
XMLHttpRequest cannot load localhost:5000/api/<method-name>;. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'localhost'; is therefore not allowed access. The response had HTTP status code 500.
But once I remove [Authorize] attribute from controller it works fine. So the problem is in token checking?
UPDATE 3:
The problem was in accidentally removed functionality :- ( Works now
The 204 NO CONTENT status code is perfectly valid for CORS preflight response (see here).
Your problem results from fact that you request contains Authorization header which makes it a "credentialed request". In such case you can't use wildcard for Access-Control-Allow-Origin and you must specify Access-Control-Allow-Credentials (you can read more here)
services.AddCors(options =>
{
options.AddPolicy("Policy", builder => builder
.WithOrigins("<Origin One>", "<Origin Two>", ...)
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials()
);
});

JWT Authentication

My team is building a web api in .net core. We use token authentication to authenticate any client, the token comes form the Azure AD.
We put this code in Startup.cs
app.UseJwtBearerAuthentication(options => {
options.AutomaticAuthenticate = true;
options.AutomaticChallenge = true;
options.Authority = "https://login.windows.net/1da3434a9-e5a6-4e9e-80c3-aca8ed37cb03";
options.Audience = "https://test.onmicrosoft.com/test_api";
options.RequireHttpsMetadata = false;
});
services.AddCors(options =>
{
// Define one or more CORS policies
options.AddPolicy("AllowAll",
builder =>
{
builder.AllowAnyOrigin()
.AllowAnyHeader()
.AllowAnyMethod()
.AllowCredentials();
});
});
This one only work when we allow anonymous access. I checked the token, and the token is valid. But every time we hit controller it will throw cors error. even though we enable cors
The sequence of adding middleware does matter!
To enable CORS for your entire application add the CORS middleware to
your request pipeline using the UseCors extension method. Note that
the CORS middleware must proceed any defined endpoints in your app
that you want to support cross-origin requests (ex. before any call to
UseMvc).
You should put services.AddCors above almost everything that might redirect your users via 401.
You cannot combine AllowCredentials & AllowAnyOrigin. Pick a specific origin and your request will likely work.