Usage of AsyncLocal in singleton DI service to override authentication tokens
I am creating a discord client library, which is based around DI and is supposed to be registered into a DI container, like in service worker or aspnetcore apps.
One of it's use cases is of course bots. It's DI services like IUsers etc use an ITokenProvider to retrieve a bot token. Bot is not the only mode of operation, but...
The library will support discord login on the web. It will have an aspnetcore authentication handler that can store user's access and refresh tokens and so you can call discord api as the user.
However, ITokenProvider is singleton and because of different contexts this library can be used, it can't be scoped. My idea was to use AsyncLocal<Token> for a concept of ambient token. When a discord user authenticated request cames in and request handler wants to execute api request on behalf of that user, they can just set the ambient token, call api like from IUsers and then reset the token.
Normally a bot token would still be used.
Does that idea sound good? othervise I could probably have some factory that creates things like IUsers/etc with a different token instead.
One of it's use cases is of course bots. It's DI services like IUsers etc use an ITokenProvider to retrieve a bot token. Bot is not the only mode of operation, but...
The library will support discord login on the web. It will have an aspnetcore authentication handler that can store user's access and refresh tokens and so you can call discord api as the user.
However, ITokenProvider is singleton and because of different contexts this library can be used, it can't be scoped. My idea was to use AsyncLocal<Token> for a concept of ambient token. When a discord user authenticated request cames in and request handler wants to execute api request on behalf of that user, they can just set the ambient token, call api like from IUsers and then reset the token.
Normally a bot token would still be used.
Does that idea sound good? othervise I could probably have some factory that creates things like IUsers/etc with a different token instead.