I have an IdentityServer 4 server set up as a stand-alone app, using net core 3.1, Entity Framework core against MySql and Net Core Identity as a user store. Separately I have a Razor Pages client app, which authenticates against the Identity Server, with user logon taking place on the server. All this is working fine.
I now wish to be able to write a log entry on the client for any new user authentication or failed logon. I assume there must be events raised somewhere. How do I go about this, please?
I had the same requirement, to store for example authentication failure in audit log - if someone tried to access api with invalid token.
What I found is that IdentityServerAuthenticationOptions has JwtBearerEvents property which can be used to be notified about such events.
In my case it worked this way:
.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;});
I was afraid that it will override normal IS behavior, but everything seems to work as it used to.
You have access to proper contexts there, for example in JwtBearerChallengeContext you can read Error or ErrorDescription strings or even whole HttpContext.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With