How to enable CORS in Blazor Static Web App? - c#

I have tried every other ways to set Access-Control-Allow-Origin : * in my Blazor Static Web App.
I follow this documentation Configure Azure Static Web Apps first to set globalHeaders. It isn't working.
And I try to add Cors in builder services. It isn't working too.
builder.Services.AddScoped (sp => new HttpClient
{ BaseAddress = new Uri(builder.Configuration["API_Prefix"] ??
builder.HostEnvironment.BaseAddress) });
builder.Services.AddCors(options =>
{ options.AddPolicy(name: policyName,
builder =>
{ builder.WithOrigins("https://localhost:5000") // specifying the allowed origin
.WithMethods("GET") // defining the allowed HTTP method
.AllowAnyHeader(); // allowing any header to be sent
});
});
await builder.Build().RunAsync();
And I tried it also in individual HttpClient request in the following.
// create request object
var request = new HttpRequestMessage(HttpMethod.Get, uri);
// add custom http header
request.Headers.Add("Access-Control-Allow-Origin", "*");
request.Headers.Add("Access-Control-Allow-Methods", "GET");
// send request
var httpResponse = await Http.SendAsync(request);
I had used this tutorial to create [Blazor Static Web App].2
This is the error I got in the browser's console. ].3
What am I missing to set the correct configuration?

Restrict Domain consumption of services by CORS browser restriction. But when you hit the service service will get executed but the response wont captured in browser side. By adding following code in API program.cs will allow specific Domains
builder.Services.AddCors(options =>
{
options.AddDefaultPolicy(policy =>
{
policy.WithOrigins("http://192.168.10.127",
"https://localhost:5000",
"https://localhost:5001")
.AllowAnyHeader()
.AllowAnyMethod();
});
});
app.UseCors();
To allow from any Domain follow below code
app.UseCors(options => options.SetIsOriginAllowed(x => _ = true).AllowAnyMethod().AllowAnyHeader().AllowCredentials());

Related

CORS Origin issue using ASP.NET Core 3.1

I am encountering a weird CORS issue when using C# ASP.NET Core 3.1 and GraphQL (Version="3.3.2"). In the Startup.cs file, I have setup the UseCors like this:
public void Configure(IApplicationBuilder app, ILoggerFactory loggerFactory)
{
if (Environment.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseCors (x => x
.AllowAnyOrigin ()
.AllowAnyMethod ()
.AllowAnyHeader ());
...
}
And also create a ConfigureCors function like this:
private void ConfigureCors(IServiceCollection services)
{
var requestOrigins = Configuration.GetSection("RequestOrigins")?
.GetChildren()
.Select(url => url.Value)
.ToArray() ?? new string[] {};
services.AddCors(options =>
{
options.AddPolicy(name: AllowSpecificOrigins,
builder =>
{
builder.WithOrigins(requestOrigins)
.AllowAnyHeader()
.AllowCredentials()
.AllowAnyMethod();
});
});
}
Called the ConfigureCors like this:
public void ConfigureServices(IServiceCollection services)
{
ConfigureCors(services);
...
}
In appsetting.{env}.json, I set the RequestOrigins:
"RequestOrigins": [
"http://localhost:8889"
]
When using frontend React to call the mutation like this:
const link = new HttpLink({
uri: 'https://localhost:5001/graphql/v1',
fetchOptions: {
credentials: 'include'
},
headers : {Authorization: `Bearer ${localStorage.getItem('Token')}`}
})
export default new ApolloClient({
link,
cache
});
It will throw the CORS issue:
Access to fetch at 'https://localhost:5001/graphql/v1' from origin 'http://localhost:8889' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'.
However the backend log shows:
info: Microsoft.AspNetCore.Hosting.Diagnostics[1]
Request starting HTTP/1.1 OPTIONS https://localhost:5001/graphql/v1
info: Microsoft.AspNetCore.Cors.Infrastructure.CorsService[4]
CORS policy execution successful.
I am very confused:
Why are the OPTIONS not the POST, since I am calling a graphql mutation?
Why backend shows CORS policy execution successful, but frontend got CORS blocker?
However, if I commented out the Authentication part like this:
const link = new HttpLink({
uri: 'https://localhost:5001/graphql/v1',
//fetchOptions: {
//credentials: 'include'
//},
//headers : {Authorization: `Bearer ${localStorage.getItem('Token')}`}
})
Got the authorization failed error, but not CORS blocker. The token I have validated work in Postman. If I remove the app.UseCors, the CORS blocker comes back which is understandable. My guess is some CORS related configuration I didn't do right, but not sure which part, anyone knows what's going on? Thanks a lot!
based on Microsoft Doc's in this link when ever u add new policy u need to specify that policy to app.UseCors().
and also pay attention to this
The call to UseCors must be placed after UseRouting, but before UseAuthorization. For more information, see Middleware order.

OAuth Implementation in ASP.NET Core using Swagger

I want to implement OAuth in my web application and for that I added the following code in my startup.cs
public static IServiceCollection AddSwaggerDocumentation(this IServiceCollection services)
{
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo { Title = "CombiTime API v1.0", Version = "v1" });
c.AddSecurityDefinition("OAuth2", new OpenApiSecurityScheme
{
Type = SecuritySchemeType.OAuth2,
Flows = new OpenApiOAuthFlows
{
AuthorizationCode = new OpenApiOAuthFlow
{
AuthorizationUrl = new Uri("http://localhost:4200/login"),
TokenUrl = new Uri("http://localhost:4200/connect/token")
}
}
});
c.OperationFilter<AuthorizeOperationFilter>();
c.AddSecurityRequirement(new OpenApiSecurityRequirement{
{
new OpenApiSecurityScheme{
Reference = new OpenApiReference{
Id = "Bearer", //The name of the previously defined security scheme.
Type = ReferenceType.SecurityScheme
}
},new List<string>()
}
});
});
return services;
}
public static IApplicationBuilder UseSwaggerDocumentation(this IApplicationBuilder app)
{
app.UseSwagger();
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "Versioned API v1.0");
c.DocumentTitle = "Title Documentation";
c.DocExpansion(DocExpansion.None);
c.RoutePrefix = string.Empty;
c.OAuthClientId("combitimeapi_swagger");
c.OAuthAppName("Combitime API");
c.OAuthUsePkce();
});
return app;
}
and the AuthorizeOperationFilter Code is as follows :
public void Apply(OpenApiOperation operation, OperationFilterContext context)
{
// Since all the operations in our api are protected, we need not
// check separately if the operation has Authorize attribute
operation.Responses.Add("401", new OpenApiResponse { Description = "Unauthorized" });
operation.Responses.Add("403", new OpenApiResponse { Description = "Forbidden" });
operation.Security = new List<OpenApiSecurityRequirement>
{
new OpenApiSecurityRequirement
{
[
new OpenApiSecurityScheme
{
Reference = new OpenApiReference {Type = ReferenceType.SecurityScheme, Id = "oauth2"}
}
] = new[] {"combitimeapi"}
}
};
}
By using this code, I get an "Authorize" button on my swagger UI and when I click that button I am redirecting to my login page(front end based on angular). So I gave my AuthorizationUrl as http://localhost:4200/login and then when I am redirected to login page, I login with valid credentials, I have used jwt token for login and for that I added the following code in my startup.cs
services.AddAuthentication(x =>
{
x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(x =>
{
x.RequireHttpsMetadata = false;
x.SaveToken = true;
x.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(key),
ValidateIssuer = false,
ValidateAudience = false
};
});
I want to redirect back to the swagger UI after I login with valid credentials but the problem is that I am being redirected to the dashboard after I login. Please help me or let me know what I am doing wrong.
The url that is being formed after I am redirected to login page from swagger is :
http://localhost:4200/login?response_type=code&client_id=combitimeapi_swagger&redirect_uri=http:%2F%2Flocalhost:61574%2Foauth2-redirect.html&state=V2VkIEZlYiAxNyAyMDIxIDIyOjU3OjQ2IEdNVCswNTMwIChJbmRpYSBTdGFuZGFyZCBUaW1lKQ%3D%3D&code_challenge=mT0amBTJgczCZmNSZAYVfjzzpaTiGb68XlyR3RNHuas&code_challenge_method=S256
My front-end is running on port 4200.
My swagger is running on port 61574.
But I am not being redirected to swagger UI after putting in valid credentials
Please help me.
First, let me add some details to your picture:
You have two applications, one with API (based on ASP.NET Core) and one with frontend UI (Angular, but it doesn't matter), and, it's important, with authorization/authentication functions.
You use .NETCore 3.1
You configure an authorization for swagger that means any call from swagger UI page will use given authorization parameters.
So, for API application we have to add a class that has helper methods configuring our swagger:
public static class ServiceCollectionExtensions
{
public static IServiceCollection AddSwaggerDocumentation(this IServiceCollection services)
{
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo { Title = "CombiTime API v1.0", Version = "v1" });
c.AddSecurityDefinition(
"oauth2",
new OpenApiSecurityScheme
{
Type = SecuritySchemeType.OAuth2,
Flows = new OpenApiOAuthFlows
{
AuthorizationCode = new OpenApiOAuthFlow
{
AuthorizationUrl = new Uri("https://lvh.me:4201/connect/authorize"),
TokenUrl = new Uri("https://lvh.me:4201/connect/token"),
Scopes = new Dictionary<string, string> {
{ "combitimeapi", "Demo API" }
}
}
}
});
c.OperationFilter<AuthorizeOperationFilter>();
c.AddSecurityRequirement(
new OpenApiSecurityRequirement
{
{
new OpenApiSecurityScheme{
Reference = new OpenApiReference{
Id = "oauth2", //The name of the previously defined security scheme.
Type = ReferenceType.SecurityScheme
}
},
new List<string>()
}
});
});
return services;
}
public static IApplicationBuilder UseSwaggerDocumentation(this IApplicationBuilder app)
{
app.UseSwagger();
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "Versioned API v1.0");
c.DocumentTitle = "Title Documentation";
c.DocExpansion(DocExpansion.None);
c.RoutePrefix = string.Empty;
c.OAuthClientId("combitimeapi_swagger");
c.OAuthAppName("Combitime API");
c.OAuthScopeSeparator(",");
c.OAuthUsePkce();
});
return app;
}
}
Please, pay attention to the AuthorizationUrl property and to the TokenUrl property. The AuthorizationUrl property should be pointed to our OAuth2 server authorization endpoint. Please, keep in mind that authorization endpoint and logon page are different endpoints. We could get all-known endpoints for our frontend application by visiting the url: https://lvh.me:4201/.well-known/openid-configuration in case our application uses ASP.NET Core with IdentityServer.
Next, Startup.cs of our API application should contain:
public void ConfigureServices(IServiceCollection services)
{
// ... some your code ...
services.AddSwaggerDocumentation();
services.AddAuthentication("Bearer")
.AddIdentityServerAuthentication("Bearer", options =>
{
options.ApiName = "combitimeapi";
options.Authority = "https://lvh.me:4201";
});
// ... some your code ...
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
// ... some your code ...
app.UseSwaggerDocumentation();
app.UseRouting();
app.UseAuthorization();
// ... some your code ...
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
Please, do not forget to add attribute [Authorize] to all your controllers, because your AuthorizeOperationFilter assumes that's done.
Let's look for required changes for our frontend & authorize part. You should configure some certain things, like:
CORS policy
Awailable API clients (one is your Angular UI and another one is API application)
Awailable API resources
Authentication & authorization methods
The class Startup.cs should contain:
public void ConfigureServices(IServiceCollection services)
{
// ... some your code ...
services.AddCors(policies => {
policies.AddDefaultPolicy(builder => {
builder.AllowAnyHeader().AllowAnyMethod().AllowAnyOrigin();
});
});
services.AddIdentityServer()
.AddApiAuthorization<ApplicationUser, ApplicationDbContext>(options => {
options.Clients.AddIdentityServerSPA("forntend", cfg => {});
options.Clients.AddNativeApp("combitimeapi_swagger", cfg => {
cfg
.WithRedirectUri("https://lvh.me:5001/oauth2-redirect.html")
.WithScopes("combitimeapi");
});
options.ApiResources.AddApiResource("combitimeapi", cfg => {
cfg.WithScopes("combitimeapi");
});
})
.AddApiResources();
services
.AddAuthentication(
x =>
{
x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddIdentityServerJwt();
// ... some your code ...
}
I use here .AddIdentityServerJwt() instead of your's .AddJwtBearer(...) because I don't have your keys and other specific options.
The frontend application is configured to use ports 4201 for HTTPS and 4200 for HTTP, the API application is configured to use ports 5001 for HTTPS and 5000 for HTTP.
Now you can run both applications and go to the page https://lvh.me:5001/index.html and press the button 'Authorize' to get a dialog like:
Enter you secret, mark scope and press 'Authorize' and, after you authenticate yourself you will get:
If you do not get a successful result, please check log of the frontend application, usually it contains error that could help you to find out a problem.
Hope text above will help you.
If you look at the OAuth Web-site the case is described as Per-Request Customization
Per-Request Customization
Often times a developer will think that they need to be able to use a
different redirect URL on each authorization request, and will try to
change the query string parameters per request. This is not the
intended use of the redirect URL, and should not be allowed by the
authorization server. The server should reject any authorization
requests with redirect URLs that are not an exact match of a
registered URL.
If a client wishes to include request-specific data in the redirect URL, it can > instead use the “state” parameter to store data that will be included after the > user is redirected. It can either encode the data in the state parameter itself, or use the state parameter as a session ID to store the state on the server.
I hope that helps you in your quest.
Source: https://www.oauth.com/oauth2-servers/redirect-uris/redirect-uri-registration/
There may be more than one problem with the Startup code, more properly in the AddSwaggerGen.
Configuration of the Identity Provider:
Independently of the redirect, are you able to get an access token, or are you getting some kind of error, for example in the request or in the Identity Provider itself?
Please note that the client configuration that you provide in Swagger must match the configuration in the Identity Provider. You seem to be following Scott Brady's example; we can observe that all his Swagger's startup configuration follows the information he has in the Identity Server (here).
Set the token in the calls to the API:
Moreover, even if you are getting the token, I think you are not setting it in the subsequent calls from Swagger to the API itself.
The AddSecurityDefinition and the AddSecurityRequirement or the AuthorizeOperationFilter typically mention at least one scheme with the same identifier, since the first method defines the way that Swagger is authenticating and the second/third define the way that the calls to the API are authenticated (so, they must reference each other). However, you are using different IDs in all the three methods - "OAuth2", "Bearer" and "oauth2" -, so none of them is linked.
I don't fully know your application, but I believe you could actually be using only one of the AddSecurityRequirement or the AuthorizeOperationFilter, since they are both specifying security requirements. The most important would be to reference the ID of the SecurityDefinition (in your case, "OAuth2").
Scott's example, in fact, only uses the AuthorizeCheckOperationFilter and uses the same ID for the OpenApiSecurityScheme that was previously registered in the AddSecurityDefinition - in his case, "oauth2", but any name/string could be used.

Blazor cannot connect to ASP.NET Core WebApi (CORS)

I have a ASP.NET Core Server running on local IP https://192.168.188.31:44302 with Web API Enpoints.
I can connect to said server with VS Code REST Client.
Now I want to conenct to the Web API with Blazor WebAssembly running on https://192.168.188.31:5555.
My Blozor Code:
#page "/login"
#inject HttpClient Http
[ ... some "HTML"-Code ... ]
#code {
private async Task Authenticate()
{
var loginModel = new LoginModel
{
Mail = "some#mail.com",
Password = "s3cr3T"
};
var requestMessage = new HttpRequestMessage()
{
Method = new HttpMethod("POST"),
RequestUri = ClientB.Classes.Uris.AuthenticateUser(),
Content =
JsonContent.Create(loginModel)
};
var response = await Http.SendAsync(requestMessage);
var responseStatusCode = response.StatusCode;
var responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine("responseBody: " + responseBody);
}
public async void LoginSubmit(EditContext editContext)
{
await Authenticate();
Console.WriteLine("Debug: Valid Submit");
}
}
When I now trigger LoginSubmit I get the following error-message in the developer console of Chrome and Firefox: login:1 Access to fetch at 'https://192.168.188.31:44302/user/authenticate' from origin 'https://192.168.188.31:5555' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
I'm new to web development and found that you have to enable CORS on the server-side ASP.NET Core project, so I extended startup.cs with
readonly string MyAllowSpecificOrigins = "_myAllowSpecificOrigins";
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<UserDataContext, UserSqliteDataContext>();
services.AddCors(options =>
{
options.AddPolicy(name: MyAllowSpecificOrigins,
builder =>
{
builder.WithOrigins("https://192.168.188.31:44302",
"https://192.168.188.31:5555",
"https://localhost:44302",
"https://localhost:5555")
.AllowAnyHeader()
.AllowAnyMethod();
});
});
services.AddControllers();
services.AddApiVersioning(x =>
{
...
});
services.AddAuthentication(x =>
...
});
services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies());
services.AddScoped<IViewerService, ViewerService>();
}
public void Configure(IApplicationBuilder app,
IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
Program.IsDevelopment = env.IsDevelopment();
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseCors(MyAllowSpecificOrigins);
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
Log.Initialize();
}
But I still get above error message.
Am I doing something wrong with configuring CORS?
Why is it working as expected with the VS Code REST Client and how am I making the call wrong in the Blazor WASM application?
The issue causing the error message login:1 Access to fetch at 'https://192.168.188.31:44302/user/authenticate' from origin 'https://192.168.188.31:5555' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled. was caused by HttpsRedirection.
To resolve the issue, either deactivate HttpsRedirection by removing the line app.UseHttpsRedirection(); in function Configure or add the proper ports for redirection in function ConfigureServices (recommended way).
In my case, I start my WebAPI at port 44302, so my solution looks like this (you have to adapt it to your port number):
if (Program.IsDevelopment)
{
services.AddHttpsRedirection(options =>
{
options.RedirectStatusCode = StatusCodes.Status308PermanentRedirect;
options.HttpsPort = 44302;
});
}
else
{
services.AddHttpsRedirection(options =>
{
options.RedirectStatusCode = StatusCodes.Status308PermanentRedirect;
options.HttpsPort = 443;
});
}
Also note that it is sufficient to add the IP address of the requesting API to CORS like this:
services.AddCors(options =>
{
options.AddPolicy(name: specificOrigins,
builder =>
{
builder.WithOrigins("https://192.168.188.31:5555",
"http://192.168.188.31:5444")
.AllowAnyHeader()
.AllowAnyMethod();
});
});
Step 1: Please add following code in your WebAPI's Startup.cs to allow CORS with specific origins:
services.AddCors(options =>
{
options.AddDefaultPolicy(builder =>
builder.WithOrigins("https://localhost:44351")
.AllowAnyHeader()
.AllowAnyMethod());
});
Step 2: Now change "https://localhost:44351" in above code with your blazor web assembly application's URL. Refer below screen shot:
Step 3: Now add app.UseCors() in your WebAPI's Configure method after app.UseRouting() and before app.UseRouting(). Please refer below screen shot:
I was also facing same issue and it solved my problem. Hope it will also work for you.
Note: No changes required in Blazor web assembly code to fix the above issue.

React .NET Enable CORS - No 'Access-Control-Allow-Origin' header is present on the requested resource

Been attempting to integrate a React front-end with a .NET Framework backend and I am constantly coming into contact with CORS errors. The request I am sending to the server works on Postman. I extracted the code from Postman and put it into my react app (Fetch) and I receive the following error:
Access to fetch at 'http://localhost:33333/Token' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
However, on my .NET backend I added the following filter:
using System;
using System.Web.Mvc;
namespace TheFifth.Cors
{
public class AllowCrossSiteAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
filterContext.RequestContext.HttpContext.Response.AddHeader("Access-Control-Allow-Origin",
"*");
filterContext.RequestContext.HttpContext.Response.AddHeader("Access-Control-Allow-Headers",
"*");
filterContext.RequestContext.HttpContext.Response.AddHeader("Access-Control-Allow-Credentials",
"true");
base.OnActionExecuting(filterContext);
}
}
}
Then referenced the Filter at the top of my Controller
[AllowCrossSite]
public class DA_Object
{
//some code
}
Does anyone know why my .NET backend or my React Frontend is preventing me from communicating across different ports - even though it works on Postman?
Additional Details
var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/x-www-form-urlencoded");
var urlencoded = new URLSearchParams();
urlencoded.append("type", "x");
urlencoded.append("username", "x#x.com");
urlencoded.append("password", "x#");
var requestOptions = {
method: 'POST',
headers: myHeaders,
body: urlencoded,
redirect: 'follow'
};
fetch("http://localhost:33333/api/Token", requestOptions)
.then(response => response.text())
.then(result => console.log(result))
.catch(error => console.log('error', error));
In your startup.cs
in the ConfigureServices method you should have something like this, if you don't have then add it:
services.AddCors(options =>
{
options.AddPolicy(DefaultCorsPolicyName, builder =>
{
//App:CorsOrigins in appsettings.json can contain more than one address with splitted by comma.
builder
.AllowAnyOrigin()
.SetIsOriginAllowedToAllowWildcardSubdomains()
.AllowAnyHeader()
.AllowAnyMethod();
});
});
And in your appsettings.json add http://0.0.0.0:80 like this:
"App": {
...
"CorsOrigins": "http://*.mycompany.com,http://0.0.0.0:80",
...}
Another solution is to add a CORS extention in your browser and enable it, but it's not recommended

Post request from Vue application blocked by CORS policy

I'm trying to call my C# web-api from my Vue webapplication but I encounter the following error:
Access to XMLHttpRequest at 'http://www.api.example.com/'
from origin 'http://www.example.com' has been blocked by CORS policy:
Response to preflight request doesn't pass access control check:
No 'Access-Control-Allow-Origin' header is present on the requested resource.
The following code snippet shows how I'm calling the rest-api with use of axios.
import axios from 'axios'
const client = axios.create({
baseURL: 'http://www.api.example.com',
json: true,
withCredentials: true
})
export default {
async execute(method, resource, data) {
return client({
method,
url: resource,
data,
headers: {}
}).then(req => {
return req
})
},
myFunc(data) {
return this.execute('post', '/', data)
}
}
The web-api with the POST request method is as follows:
[EnableCors("VueCorsPolicy")]
[Route("api/[controller]")]
[ApiController]
public class MyController : ControllerBase
{
[HttpPost]
public async Task<int> Post([FromBody] Data data)
{
// stuff
}
}
I have also added a CORS to my "ConfigureServices" method in the Startup.cs file.
services.AddCors(options =>
{
options.AddPolicy("VueCorsPolicy", builder =>
{
builder
.WithOrigins("http://www.example.com")
.AllowAnyHeader()
.AllowAnyMethod()
.AllowCredentials();
});
});
And lastly I have also added to the "Configure" method in the Startup.cs file:
app.UseCors("VueCorsPolicy");
CORS is a security mechanism, that cannot be overcome by simply modifying your code. The server has to be set so that it allows the requests from your source - so, if you control the server you can do it.
However, there are some solutions that help you during development phase, like cors-anywhere.herokuapp.com.
You should add it before the baseURL in your code, like this:
baseURL: 'https://cors-anywhere.herokuapp.com/http://www.api.example.com'.
This is NOT a solution for production, only for development.
You can host your own cors-anywhere app, more on this: https://www.npmjs.com/package/cors-anywhere
.WithOrigins("http://www.thomasleoblok.dk/") this is where your problem is, it should be .WithOrigins("http://www.example.com") since it is example.com you want to allow to make requests, it you want to allow any site you can change it to .WithOrigins("*")
if you are trying locally you must open the origin localhost, otherwise the BE will always return a cors error as localhost != http://www.thomasleoblok.dk/
for testing I suggest you enable AllowAnyOrigin()
example:
services.AddCors(options =>
{
options.AddPolicy("VueCorsPolicy", builder =>
{
builder
.AllowAnyOrigin()
.AllowAnyHeader()
.AllowAnyMethod()
.AllowCredentials();
});
});

Categories

Resources