ASP.NET Web API微服务+Angular前端-如何管理authcookie



当涉及到Cookie验证(ASP.NET(和使用Angular的独立(CORS(前端时,有人能建议什么是标准做法吗。

我遇到的问题是,当我使用Postman/Swagger登录Web API时,Auth Cookie会被创建。当我通过localhost:4200使用Angular时,不会创建cookie。

对于angular post方法Http标头配置,我使用{withCredentials: true}以下是我为API配置的cookie加CORS:1-中间件

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-注册CORS服务:

builder.Services.AddCors(options =>
{
options.AddPolicy(name: MyAllowSpecificOrigins,
policy =>
{
policy.WithOrigins("http://localhost:4200");
policy.AllowAnyHeader();
policy.AllowAnyMethod();
policy.AllowCredentials();
});
});

3-Cookie配置:


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;

一些用户报告说,当使用Localhost:4200时,不应该在客户端浏览器中创建cookie,例如,我读过这个意见,但无法理解它的确切含义:"随后的请求将由浏览器发送,浏览器将自动携带cookie"也许,我应该只分配一个简单的变量,检查登录的响应是否为200Okay,然后在稍后的代码中使用它作为确认?

那么,有人能告诉我,对我的前端进行身份验证的标准做法是什么吗?

好的,所以我更新了我的Cookie和CORS配置。此外,目前,我的Angular前端使用http,但在未来的版本中,我将使用https进行修复。

因此,目前,我可以确认此配置正在运行。每当我从我的Angular应用程序成功登录时,就会在其中创建一个cookie。这个cookie也会被后端成功读取,从而完成后端所需的安全过程!

我希望我能帮助别人阅读这个话题。别忘了添加

{withCredentials : true}

在Angular应用程序发出的每个HttpRequest的头中。

最新更新