Cross Origin request blocked when http post into .netcore 2.0 webapi from angular 6
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:
Browser cors error indication:
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
add a comment |
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:
Browser cors error indication:
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
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
add a comment |
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:
Browser cors error indication:
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
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:
Browser cors error indication:
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
post asp.net-core cors jwt angular6
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
add a comment |
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
add a comment |
1 Answer
1
active
oldest
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 . To OP : if post tohttp://localhost:5001/api/auth/login",
, I get something likeConnection 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 behttps://localhost:5001/api/auth/login
, it will work well. But above all, we should firstly allow theContent-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
add a comment |
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
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
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
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 . To OP : if post tohttp://localhost:5001/api/auth/login",
, I get something likeConnection 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 behttps://localhost:5001/api/auth/login
, it will work well. But above all, we should firstly allow theContent-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
add a comment |
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 . To OP : if post tohttp://localhost:5001/api/auth/login",
, I get something likeConnection 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 behttps://localhost:5001/api/auth/login
, it will work well. But above all, we should firstly allow theContent-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
add a comment |
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
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
answered Nov 16 '18 at 8:27
TsengTseng
33.6k594124
33.6k594124
+1 . To OP : if post tohttp://localhost:5001/api/auth/login",
, I get something likeConnection 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 behttps://localhost:5001/api/auth/login
, it will work well. But above all, we should firstly allow theContent-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
add a comment |
+1 . To OP : if post tohttp://localhost:5001/api/auth/login",
, I get something likeConnection 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 behttps://localhost:5001/api/auth/login
, it will work well. But above all, we should firstly allow theContent-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
add a comment |
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.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
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
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
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
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