1

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(); } } 
1
  • 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) Commented Nov 16, 2018 at 7:24

3 Answers 3

1

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

Sign up to request clarification or add additional context in comments.

2 Comments

+1 . To OP : if post to http://localhost:5001/api/auth/login",, I get something like Connection id "0HLIBJHR3T2L6" bad request data: "Invalid request line: '\x16\x03\x01\x02\x00\x01\x00\x01\xFC\x03\x03n'\xA3N\x0D\xA1\xB3(\x8E\xBA\xB0b\xCDla\x0A'" Microsoft.AspNetCore.Server.Kestrel.Core.BadHttpRequestException: Invalid request line: '\x16\x03\x01\x02\x00\x01\x00\x01\xFC\x03\x03n'\xA3N\x0D\xA1\xB3(\x8E\xBA\xB0b\xCDla\x0A' . If change the endpoint to be https://localhost:5001/api/auth/login , it will work well. But above all, we should firstly allow the Content-Type
Although I registered the CORS middleware before the http redirection and authentication , problem is still there. It gives out the same error as before
1
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"); } 

Comments

0

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.