1
votes

I'm trying to use Jwt authentication to my angular 6 app. Although i added cors middleware into my .netcore 2 webapi i repeatedly get this error saying

"Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:5000/api/auth/login. (Reason: CORS request did not succeed)."

Angular6 http post:

angular6 http post

Browser cors error indication:

Browser cors error indication

Cors middleware in .netcore2 webapi:

Cors middleware in .netcore2 webapi

http post-angular

export class LoginComponent {
  invalidLogin: boolean;

  constructor(private router: Router, private http: HttpClient) { }

  login(form: NgForm) {
    let credentials = JSON.stringify(form.value);
    this.http.post("http://localhost:5000/api/auth/login", credentials, {
      headers: new HttpHeaders({
        "Content-Type": "application/json"
      })
    }).subscribe(response => {
      let token = (<any>response).token;
      localStorage.setItem("jwt", token);
      this.invalidLogin = false;
      this.router.navigate([""]);
    }, err => {
      this.invalidLogin = true;
    });
  }
}

Cors middleware in Startup.cs file

 public void ConfigureServices(IServiceCollection services)
            {
               services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
                    .AddJwtBearer(options =>
                    {
                        options.TokenValidationParameters = new TokenValidationParameters
                        {
                            ValidateIssuer = true,
                            ValidateAudience = true,
                            ValidateLifetime = true,
                            ValidateIssuerSigningKey = true,

                            ValidIssuer = "http://localhost:5000",
                            ValidAudience = "http://localhost:5000",
                            IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("superSecretKey@345"))
                        };
                    }); 

services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

                 services.AddCors(cfg=>cfg.AddPolicy("ClientDomain",builder=>builder.WithOrigins("http://localhost:4200")));
            }


            public void Configure(IApplicationBuilder app,IHostingEnvironment env)
            {
                if (env.IsDevelopment())
                {
                    app.UseDeveloperExceptionPage();
                }
                else
                {
                    app.UseHsts();
                }

                app.UseHttpsRedirection();
                app.UseAuthentication();
                app.UseCors("ClientDomain");
                app.UseMvc();
            }
        }
3
Please don't post pictures of code, add the code with code formatting to the question. (You can paste it in the editor, select it and then click the Code button) - juunas

3 Answers

1
votes

The issues seems to be that you are sending an HTTP Request, but your Cors Middleware is registered late in the pipeline and never called on HTTP Requests, because of

app.UseHttpsRedirection();
app.UseAuthentication();

In other words: When your request is on http, the UseHttpsRedirection middleware, will short-circuit the pipeline and returns a response, w/o the required CORS headers during a preflight. Same applies if you do it via https, but the user is not authorized.

In order to allow CORS on http (or before the redirection) and also for unauthorized users, you have to register the middleware before the lines above

// now CORS is handled before https redirection & before authentication
app.UseCors("ClientDomain");
app.UseHttpsRedirection();
app.UseAuthentication();
app.UseMvc();

Always keep in mind that middlewares are called in the order of their registration (UseXxx calls).

Trivia: When you get an exception for any middlewares, the exception middleware will CLEAR the headers. Hence, methods that throw exception will not contain the cors headers, even if the cors middleware registration is correct

1
votes
public void ConfigureServices(IServiceCollection services)
{
 services.AddCors(options =>
            {
                options.AddPolicy("AllowAll", p =>
                {
                    p.AllowAnyOrigin()
                        .AllowAnyHeader()
                        .AllowAnyMethod();
                });
            });
}


public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{

  app.UseCors("AllowAll");
}
0
votes

All you need to do is:

1) Install package Microsoft.AspNetCore.Cors from nuget

2) Put code services.AddCors() inside ConfigureServices() method of Startup.cs

3) Put code

app.UseCors(builder=>builder.WithOrigins("http://localhost:4200").AllowAnyMethod().AllowAnyHeader());

inside Configure() method of Startup.cs before http redirection and Authentication if any.