我将 IdentityServer 4 服务器设置为独立应用程序,使用 net core 3.1、针对 MySql 的 Entity Framework core 和 Net Core Identity 作为用户存储。另外,我有一个 Razor Pages 客户端应用程序,它针对 Identity Server 进行身份验证,用户登录发生在服务器上。所有这些都运行良好。
我现在希望能够在客户端上为任何新用户身份验证或登录失败写入日志条目。我假设某处一定有事件发生。请问我该怎么做?
最佳答案
我有同样的要求,例如在审计日志中存储身份验证失败 - 如果有人试图使用无效 token 访问 api。
我发现 IdentityServerAuthenticationOptions
具有 JwtBearerEvents
属性,可用于通知此类事件。
在我的例子中,它是这样工作的:
.AddAuthentication(AUTH_SCHEME).AddIdentityServerAuthentication(AUTH_SCHEME, options => {
options.ApiName = config.ApiName;
options.Authority = config.Address;
options.JwtBearerEvents = new JwtBearerEvents
{
OnAuthenticationFailed = c =>
{
// Log can bo done here
return Task.CompletedTask;
},
OnTokenValidated = c =>
{
// Log can bo done here
return Task.CompletedTask;
},
OnChallenge = c =>
{
// Log can bo done here
return Task.CompletedTask;
},
OnForbidden = c =>
{
// Log can bo done here
return Task.CompletedTask;
}
};
options.SupportedTokens = SupportedTokens.Jwt;});
我担心它会覆盖正常的 IS 行为,但一切似乎都像以前一样工作。
你可以在那里访问适当的上下文,例如在 JwtBearerChallengeContext
中你可以读取 Error
或 ErrorDescription
字符串甚至整个 HttpContext
。
https://stackoverflow.com/questions/63833623/