0
votes

I got below issue while sending auth header jwt token from angular. Access to XMLHttpRequest at 'http://localhost:52278/api/user/signup' from origin 'http://localhost:4200' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

.Net Core

            var origins = Configuration["CorsUrl"].Split(",");
            services.AddCors(options =>
            {
                options.AddPolicy("BasePolicy",
                builder =>
                {
                    builder
                    .AllowAnyMethod()
                    .WithOrigins(origins)
                    .AllowAnyHeader()
                    .AllowCredentials()
                    .AllowAnyMethod();
                });

            });
        app.UseAuthorization();
        app.UseCors("BasePolicy");
        app.UseHttpsRedirection();

Angular:

    signUpAdmin(data: AdminSignUpModel) {
        return this.httpClient.post('user/signup', data,this.getCommonOptions());
    }

private _token: string = localStorage.getItem('auth_token');

   protected getCommonOptions() {
        const httpOptions = {
            headers: new HttpHeaders({
                'Content-Type': 'application/json',
                'Access-Control-Allow-Origin': '*',
                'Access-Control-Allow-Methods': '*',
                Authorization: `Bearer ${this._token}`,
                
            })
        };
        return httpOptions;
    }
2

2 Answers

0
votes

Access to XMLHttpRequest at 'http://localhost:52278/api/user/signup' from origin 'http://localhost:4200' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

To troubleshoot the issue, please try to specify the allowed origins in code rather than get data from configuration settings, like below.

services.AddCors(options =>
{
    options.AddPolicy("BasePolicy",
    builder =>
    {
        builder
        .AllowAnyMethod()
        .WithOrigins("http://localhost:4200", "https://localhost:44336") 
        .AllowAnyHeader()
        .AllowCredentials()
        .AllowAnyMethod();
    });

});

Please note that the specified URL(s) must not contain a trailing slash (/), such as http://localhost:4200/.

And please modify code to call the UseCors method after UseRouting, but before UseAuthorization.

app.UseRouting();
//...

app.UseCors("BasePolicy");

app.UseAuthorization();

For more information about enabling CORS in ASP.NET Core, please check this doc:

https://docs.microsoft.com/en-us/aspnet/core/security/cors?view=aspnetcore-5.0#cors-with-named-policy-and-middleware

0
votes

So you have your Angular CLI development server running on http://localhost:4200 and you want to access the server running on http://localhost:52278 you need to set up a proxy for API calls in angular.

To create Angular PROXY

  1. Create a file proxy.conf.json at the root of our Angular CLI project.

    The content should look as follows

{
  "/api/*": {
    "target": "http://localhost:52278",
    "secure": false,
    "logLevel": "debug",
    "changeOrigin": true
  }
}

Now All requests made to /api/... from within our application will be forwarded to http://localhost:52278/api/....

  1. Configure angular.json with proxyConfig key under the architect>serve>options that point to the src/proxy.conf.json as below
"architect": {
  "serve": {
    "builder": "@angular-devkit/build-angular:dev-server",
    "options": {
      "browserTarget": "your-application-name:build",
      "proxyConfig": "src/proxy.conf.json"
    },
  1. Now, simply run ng serve and you are done.

Side note: This is NOT FOR PRODUCTION

use it for development there are other, much more sophisticated solutions for your production environment, whether it is to deploy your app directly “into your backend app” or by serving it via Apache 2 or Nginx.