Search code examples
c#authenticationasp.net-coreidentityserver4

Record user login for audit on IdentityServer4


I have a server running for Identity only for authentication and I want to log every user login. I've read the Identity doc and tried using the IEventSink. It's supposed to be easy, but Login keeps working without calling the EventSink. Do I have to register my class somewhere? What am I missing?

var builder = services
.AddIdentityServer(options =>
{
    options.Events.RaiseSuccessEvents = true;
}
)
.AddInMemoryIdentityResources(Config.GetIdentityResources())
.AddInMemoryApiResources(Config.GetApis())
.AddInMemoryClients(Config.GetClients())
.AddAspNetIdentity<ApplicationUser>()
.AddOperationalStore(options =>
{
    options.ConfigureDbContext = b =>
        b.UseMySql(Configuration.GetConnectionString("DefaultConnection")
    );
    options.EnableTokenCleanup = true;
});

This is the EventSink I created:

public class MyEventSink : IEventSink
{
    public Task PersistAsync(Event evt)
    {
        if (evt.Id.Equals(EventIds.TokenIssuedSuccess))
        {
            var _test = evt as TokenIssuedSuccessEvent;
        }
        throw new System.NotImplementedException(); // shouldn't even login
        return Task.CompletedTask;
    }
}

Solution

  • As @camilo-terevinto pointed out to me, I just wasn't registering my MyEventSink as a service.
    I needed the following line in my startup, so when I set Events.RaiseSuccessEvents = true the IdentityServer knows it is my service it should call:

    services.AddScoped<IEventSink , MyEventSink>();