7

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 ?

Askolein
  • 3,250
  • 3
  • 28
  • 40
Christophe Gigax
  • 3,211
  • 4
  • 25
  • 37
  • I found the solution to use IServiceProvider for the moment, so I get my database service into the Handler method and not via dependency injection, not so clean solution ... – Christophe Gigax Apr 28 '16 at 09:14

1 Answers1

7

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

Hao Kung
  • 28,040
  • 6
  • 84
  • 93
  • 1
    It's true, but what if I've got 5000 handlers registered as scoped, why all of them instantiated any time when I interact any actions? They could have dependencies on other services which should be injected. – Serhii Kyslyi Aug 14 '17 at 12:17