Blazorade / Blazorade-MSAL

A Blazor component library that makes it easy to use authentication in your application through MSAL, both in Blazor Server and Blazor WebAssembly applications.
MIT License
17 stars 5 forks source link

Testing if there is an available token #22

Closed HolisticDeveloper closed 2 years ago

HolisticDeveloper commented 2 years ago

Blazorade MSAL looks awesome! I think I'll be able to replace a couple day's worth of work in my app with a few lines of code -- I only wish I had found it last week! ;)

I have a use case where I want to display some content in the app if the user has never linked to an Azure AD account. Is there a good way to handle this? Right now, I am calling BlazoradeMsalService.AcquireTokenSilentAsync() and simply swallowing any exceptions.

MikaBerglund commented 2 years ago

I guess there are several ways to handle this. Do you have any suggestions or preferance?

MikaBerglund commented 2 years ago

Looking more closely at the code I think the simplest way would be to add a HasTokenAsync method to the BlazoradeMsalService class (and make it virtual to support #23). That method would then do what you are doing, i.e. calling AcquireTokenSilentAsync catching any errors and checking that the response contains a token.

However, this will potentially refresh the token behind the scenes in cases where the current token has expired, but MSAL has enough information to refresh the token without interaction.

Basically, this would mean that the "full" name of the method should be something like HasTokenOrCanBeSilentlyRefreshedAsync, but to keep it brief we should probably stick to HasTokenAsync.

There might be a possibility to go and dig deeper and try to find the cached token, but then we would have to do some checks on that to see whether the token is still valid, among other things.

So, would that potential silent token refresh be a problem for you?

MikaBerglund commented 2 years ago

Added a pull request (#25) with a suggested solution. Would that be enough for you @HolisticDeveloper ?