Christophe Gigax
Christophe Gigax

Reputation: 3470

AuthorizationHandler and database dependency injection

We develop an multi-tenant application based on Identity authentication. Each user get a token session, stored in database, to tell if the user is still connected (with expiration time). I store the token (and others informations about the user company) in user Claim. After that Identity detect that the user is still connected (or not), I need to check if the user token is still valid in our database (but only if he's connected), so I implemented AuthorizationHandler.

public TokenValidHandler(MyDatabaseService service)
{
     // No information about the user connection string
}

protected override async void Handle(AuthorizationContext context, TokenValidRequirement requirement)
{
    // Check the token in database
}

And I register my Handler like this :

services.AddAuthorization(options =>
{
     options.AddPolicy("TokenValid",policy => policy.Requirements.Add(new TokenValidRequirement()));
});

 services.AddSingleton<IAuthorizationHandler, TokenValidHandler>();

Because we have an multi-tenant application, when the user quit the application and re-open the site, his connection string is lost (and we don't want to persist database string), so I use informations stored in Claim to recover the database access. If the authentication expired, no informations are available in Claim, so I cannot access to my database.

As I can see, TokenValidHandler is instanciated even if the user is not connected, is that normal ? Because in the case he's not, and I wanted to use dependency injection for my database service, I cannot because informations about the user database access are not here : Identity is not detecting soon enough that the user authentication expired. Any ideas about that ?

Upvotes: 8

Views: 4698

Answers (1)

Hao Kung
Hao Kung

Reputation: 28200

Try registering your handler as scoped, and you will get a new instance per request which is probably what you want.

Upvotes: 7

Related Questions