Cross Origin request blocked when http post into .netcore 2.0 webapi from angular 6












0















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();
}
}









share|improve this question

























  • 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
    Nov 16 '18 at 7:24
















0















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();
}
}









share|improve this question

























  • 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
    Nov 16 '18 at 7:24














0












0








0








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();
}
}









share|improve this question
















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();
}
}






post asp.net-core cors jwt angular6






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 16 '18 at 7:53







Ashan Samarasinghe

















asked Nov 16 '18 at 7:22









Ashan SamarasingheAshan Samarasinghe

12




12













  • 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
    Nov 16 '18 at 7:24



















  • 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
    Nov 16 '18 at 7:24

















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
Nov 16 '18 at 7:24





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
Nov 16 '18 at 7:24












1 Answer
1






active

oldest

votes


















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






share|improve this answer
























  • +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: 'x16x03x01x02x00x01x00x01xFCx03x03n'xA3Nx0DxA1xB3(x8ExBAxB0bxCDlax0A'" Microsoft.AspNetCore.Server.Kestrel.Core.BadHttpRequestException: Invalid request line: 'x16x03x01x02x00x01x00x01xFCx03x03n'xA3Nx0DxA1xB3(x8ExBAxB0bxCDlax0A' . 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

    – itminus
    Nov 16 '18 at 8:35













  • Although I registered the CORS middleware before the http redirection and authentication , problem is still there. It gives out the same error as before

    – Ashan Samarasinghe
    Nov 16 '18 at 16:04











Your Answer






StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");

StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});

function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});


}
});














draft saved

draft discarded


















StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53333188%2fcross-origin-request-blocked-when-http-post-into-netcore-2-0-webapi-from-angula%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown

























1 Answer
1






active

oldest

votes








1 Answer
1






active

oldest

votes









active

oldest

votes






active

oldest

votes









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






share|improve this answer
























  • +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: 'x16x03x01x02x00x01x00x01xFCx03x03n'xA3Nx0DxA1xB3(x8ExBAxB0bxCDlax0A'" Microsoft.AspNetCore.Server.Kestrel.Core.BadHttpRequestException: Invalid request line: 'x16x03x01x02x00x01x00x01xFCx03x03n'xA3Nx0DxA1xB3(x8ExBAxB0bxCDlax0A' . 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

    – itminus
    Nov 16 '18 at 8:35













  • Although I registered the CORS middleware before the http redirection and authentication , problem is still there. It gives out the same error as before

    – Ashan Samarasinghe
    Nov 16 '18 at 16:04
















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






share|improve this answer
























  • +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: 'x16x03x01x02x00x01x00x01xFCx03x03n'xA3Nx0DxA1xB3(x8ExBAxB0bxCDlax0A'" Microsoft.AspNetCore.Server.Kestrel.Core.BadHttpRequestException: Invalid request line: 'x16x03x01x02x00x01x00x01xFCx03x03n'xA3Nx0DxA1xB3(x8ExBAxB0bxCDlax0A' . 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

    – itminus
    Nov 16 '18 at 8:35













  • Although I registered the CORS middleware before the http redirection and authentication , problem is still there. It gives out the same error as before

    – Ashan Samarasinghe
    Nov 16 '18 at 16:04














1












1








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






share|improve this answer













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







share|improve this answer












share|improve this answer



share|improve this answer










answered Nov 16 '18 at 8:27









TsengTseng

33.6k594124




33.6k594124













  • +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: 'x16x03x01x02x00x01x00x01xFCx03x03n'xA3Nx0DxA1xB3(x8ExBAxB0bxCDlax0A'" Microsoft.AspNetCore.Server.Kestrel.Core.BadHttpRequestException: Invalid request line: 'x16x03x01x02x00x01x00x01xFCx03x03n'xA3Nx0DxA1xB3(x8ExBAxB0bxCDlax0A' . 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

    – itminus
    Nov 16 '18 at 8:35













  • Although I registered the CORS middleware before the http redirection and authentication , problem is still there. It gives out the same error as before

    – Ashan Samarasinghe
    Nov 16 '18 at 16:04



















  • +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: 'x16x03x01x02x00x01x00x01xFCx03x03n'xA3Nx0DxA1xB3(x8ExBAxB0bxCDlax0A'" Microsoft.AspNetCore.Server.Kestrel.Core.BadHttpRequestException: Invalid request line: 'x16x03x01x02x00x01x00x01xFCx03x03n'xA3Nx0DxA1xB3(x8ExBAxB0bxCDlax0A' . 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

    – itminus
    Nov 16 '18 at 8:35













  • Although I registered the CORS middleware before the http redirection and authentication , problem is still there. It gives out the same error as before

    – Ashan Samarasinghe
    Nov 16 '18 at 16:04

















+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: 'x16x03x01x02x00x01x00x01xFCx03x03n'xA3Nx0DxA1xB3(x8ExBAxB0bxCDlax0A'" Microsoft.AspNetCore.Server.Kestrel.Core.BadHttpRequestException: Invalid request line: 'x16x03x01x02x00x01x00x01xFCx03x03n'xA3Nx0DxA1xB3(x8ExBAxB0bxCDlax0A' . 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

– itminus
Nov 16 '18 at 8:35







+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: 'x16x03x01x02x00x01x00x01xFCx03x03n'xA3Nx0DxA1xB3(x8ExBAxB0bxCDlax0A'" Microsoft.AspNetCore.Server.Kestrel.Core.BadHttpRequestException: Invalid request line: 'x16x03x01x02x00x01x00x01xFCx03x03n'xA3Nx0DxA1xB3(x8ExBAxB0bxCDlax0A' . 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

– itminus
Nov 16 '18 at 8:35















Although I registered the CORS middleware before the http redirection and authentication , problem is still there. It gives out the same error as before

– Ashan Samarasinghe
Nov 16 '18 at 16:04





Although I registered the CORS middleware before the http redirection and authentication , problem is still there. It gives out the same error as before

– Ashan Samarasinghe
Nov 16 '18 at 16:04


















draft saved

draft discarded




















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid



  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.


To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53333188%2fcross-origin-request-blocked-when-http-post-into-netcore-2-0-webapi-from-angula%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







這個網誌中的熱門文章

Xamarin.form Move up view when keyboard appear

Post-Redirect-Get with Spring WebFlux and Thymeleaf

Anylogic : not able to use stopDelay()