I'm building a .Net 9 Blazor Standalone WASM app using the out of box Blazor WebAssembly Authentication Library, patterned after the Blazor templates in VS2022, and configured for Auth0 as IdP. Pretty vanilla - basic login/logout and authorization operations works great.
Now for the interesting bit. In my app users may be granted access to another user's information based on role. For this feature I call back to Auth0 to request new id_token and acess_token. In this way <AuthorizeView>
can trim the UI based on id_token roles, while the access_token is used for API calls. I'm making the request for updated tokens with the builtin IAccessTokenProvider.RequestAccessToken()
method as shown here:
public async Task RefreshTokensAsync()
{
var tokenResult = await accessTokenProvider.RequestAccessToken(
new AccessTokenRequestOptions
{
// add these scopes so that refresh_token grant returns all three tokens:
// id, access, and refresh
Scopes = new[] { "openid profile offline_access" }
});
if (tokenResult.TryGetToken(out var token))
{
// TODO can we notify framework of changed authstate here?
return;
}
}
Above also works well in so far as I get the new tokens back from Auth0, updated as desired by Auth0 Actions. BUT, using the Inspect the User sample code, the UI does not update (I see no change to the roles displayed for the id_token or access_token. If I navigate away from the page and back, the access_token UI does update, but the id_token still does not. Refreshing the app altogether updates everything as expected, but that's bad UX. It seems to me that I need to notify the framework that authstate has changed, but I'd really like to avoid creating a CustomAuthStateProvider if possible because I don't trust I'll do as good a job interacting with the IdP manually.
Is it possible to just call NotifyAuthenticationStateChanged
on the framework's AuthenticationStateProvider
without creating a CustomAuthStateProvider? Or trigger the update in some other way?
Maybe there's more appropriate way to request the refreshed tokens than calling RefreshAccessToken
.
Thanks
Using accessTokenProvider.RequestAccessToken
with new scope only grant a new accesstoken, not idtoken.
"UI does not update the accesstoken."
You need to assign the new value to that UI parameter "AccessToken" and call StateHasChanged
public AccessToken AccessToken { get; set; }
...
if (tokenResult.TryGetToken(out var token))
{
AccessToken = token;
StateHasChanged();
}
"Is it possible to just call NotifyAuthenticationStateChanged?"
As far as I know the answer is NO. WASM uses a internal stateprovider which from package "Microsoft.AspNetCore.Components.WebAssembly.Authentication" which cannot be access directly. You have to do Custom state provider for refreshing demand.