Issue
Can anyone suggest what are the standard practices when it comes to Cookie Authentication (ASP.NET) and a separate (CORS) front-end using Angular.
The problem that I have is when I log in in my Web API using Postman/ Swagger - the Auth Cookie gets created. When I use Angular through localhost:4200, no cookie is created.
For angular post method Http headers configuration I use {withCredentials: true}
and these are my configurations for the cookie plus CORS for the API:
1 - Middleware
app.UseCors(builder =>
builder
.WithOrigins("http://localhost:4200")
.AllowAnyHeader()
.AllowCredentials()
.AllowAnyMethod());
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers()
.RequireCors(MyAllowSpecificOrigins);
});
app.MapControllers();
app.Run();
2 - registering the CORS services:
builder.Services.AddCors(options =>
{
options.AddPolicy(name: MyAllowSpecificOrigins,
policy =>
{
policy.WithOrigins("http://localhost:4200");
policy.AllowAnyHeader();
policy.AllowAnyMethod();
policy.AllowCredentials();
});
});
3 - Cookie configuration:
builder.Services.ConfigureApplicationCookie(config =>
{
config.Cookie.Name = "Identity.Cookie";
config.LoginPath = "/User/Login";
config.LogoutPath = "/User/Logout";
config.Cookie.HttpOnly = false;
config.Cookie.SameSite = SameSiteMode.None;
config.Cookie.SecurePolicy = CookieSecurePolicy.SameAsRequest;
Some users reported that no cookie should be created in the client browser when using Localhost:4200, for example I've read this opinion but cannot understand what it means, exactly: "Subsequent requests will be sent by the browser and the browser will automatically bring the cookies." Maybe, I should only assign a simple variable which checks if the response of the login is 200 Okay and then use it as a confirmation, later in the code?
So, can anyone advise what is the standard practice, to authenticate my front-end?
Solution
Okay, so I updated my Cookie and CORS configuration. Also, currently, my Angular Front End is using http, but in future versions I shall fix it with https.
So for now, I can confirm that this configuration is working. Whenever I login from my Angular Application successfully - a cookie is created in it. This cookie then is also successfully read by the backend, thus completing the security process, required by the backend!
I hope I helped someone reading this topic. And don't forget to add
{withCredentials : true}
in the headers of each HttpRequest made from your Angular application.
Answered By - Andrеw
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.