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 ?
Framework level dependency injection is powerful feature of . NET Core. It is easy to configure and easy to use through constructor injection. We used dependency injection with view component to display top menu and to correctly highlight current top level category.
ASP.NET Core supports the dependency injection (DI) software design pattern, which is a technique for achieving Inversion of Control (IoC) between classes and their dependencies. For more information specific to dependency injection within MVC controllers, see Dependency injection into controllers in ASP.NET Core.
The Dependency Injection (DI) Design Pattern The Dependency Resolver in ASP.NET MVC can allow you to register your dependency logic somewhere else (e.g. a container or a bag of clubs). The advantages of using Dependency Injection pattern and Inversion of Control are the following: Reduces class coupling.
Try registering your handler as scoped, and you will get a new instance per request which is probably what you want.
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