我正在使用ORY Kratos进行身份验证,我的前端SPA(React App)通过Kratos登录服务器进行身份验证,并返回会话cookie。现在我想以某种方式保护我的ASP.NET Core Web Api,使用户只能在请求中附加有效的cookie时才能调用受
在开发工具中,我可以验证Cookie是否连接到请求标头:
这是我目前尝试过的内容:
[Authorize]
属性保护的某些方法。为此,我需要验证每个传入请求中的cookie。因此,我正在寻找一种配置认证并添加自定义逻辑以验证cookie的方法(我需要向Kratos发出API调用以验证它)。我要验证的cookie不是由要验证它的ASP.NET Core应用程序发布的。迄今为止,我找到的所有示例都是在同一台服务器上发放cookie,但我需要验证外部cookie。这就是我的cookie的样子:
![enter image description here](https://istack.dev59.com/lD1Cx.webp)
![enter image description here](https://istack.dev59.com/OuZII.webp)
public void ConfigureServices(IServiceCollection services)
{
// ...
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, options =>
{
options.Cookie.Name = "ory_kratos_session";
options.Cookie.Path = "/";
options.Cookie.Domain = "localhost";
options.Cookie.HttpOnly = true;
options.EventsType = typeof(CustomCookieAuthenticationEvents);
});
services.AddScoped<CustomCookieAuthenticationEvents>();
// ...
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
// ...
app.UseAuthentication();
app.UseAuthorization();
// ...
}
public class CustomCookieAuthenticationEvents : CookieAuthenticationEvents
{
public CustomCookieAuthenticationEvents() {}
public override async Task ValidatePrincipal(CookieValidatePrincipalContext context)
{
// Never gets called
}
}
日志:
info: Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationHandler[7]
Cookies was not authenticated. Failure message: Unprotect ticket failed
info: Microsoft.AspNetCore.Authorization.DefaultAuthorizationService[2]
Authorization failed. These requirements were not met:
DenyAnonymousAuthorizationRequirement: Requires an authenticated user.
info: Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationHandler[12]
AuthenticationScheme: Cookies was challenged.
dbug: Microsoft.AspNetCore.Server.Kestrel[9]
Connection id "0HM6IBAO4PLLL" completed keep alive response.
info: Microsoft.AspNetCore.Hosting.Diagnostics[2]
Request finished HTTP/1.1 GET https://localhost:5001/weatherforecast - - - 302 0 - 75.3183ms
info: Microsoft.AspNetCore.Hosting.Diagnostics[1]
Request starting HTTP/1.1 GET https://localhost:5001/Account/Login?ReturnUrl=%2Fweatherforecast - -