My Blazor backend app uses a custom AuthenticationStateProvider which persists the authenticated user on both the backend app and the web assembly client app. I can use a BaseAddressAuthorizationMessageHandler when registering an http client which will attach my access token to header, however the SignalR JavaScript client uses WebSockets and I have to attach the access token to the query string. How do I get the access token in a razor component inside my web assembly client app? The cascaded parameter AuthenticationState, HttpContext or the HttpContextAcessor objects do not have it and I read it’s not even safe to use the HttpConext in a razor component. the MS documentation here: blazor8 doesn’t help. This is where I’m stuck:
hubConnection = new HubConnectionBuilder()
.WithUrl(Navigation.ToAbsoluteUri("https://localhost:7288/chathub"), options =>
{
options.AccessTokenProvider = () => Task.FromResult(signalRToken);
options.Headers.Add("BusinessId", MapInitialization!.BusinessId!.Value!.ToString());
options.Headers.Add("BusinessRole", MapInitialization?.SignalRRole!);
options.Headers.Add("DisplayName", MapInitialization?.SignalRDisplayName!);
options.Headers.Add("UserName", MapInitialization?.SignalRUserName!);
}).Build();
I’ve tried injecting the IHttpContextAccessor into my AuthenticationStateProvider class but I can’t seem to find the access token:
public override Task<AuthenticationState> GetAuthenticationStateAsync()
{
if (authenticationStateTask == null)
{
throw new InvalidOperationException($"Do not call {nameof(GetAuthenticationStateAsync)} outside of the DI scope for a Razor component. Typically, this means you can call it only within a Razor component or inside another DI service that is resolved for a Razor component.");
}
...
}
I’ve also tried setting the HttpContext properties with the OnSignedIn callback inside the CookieAuthenticationOptions class from the CookieSignedIn properties but it wasn’t persisting:
cookieOptions.Events.OnSignedIn = context =>
{
var http = context.HttpContext;
http.Items["Properties"] = context.Properties;
http.Features.Set(context.Properties);
return Task.CompletedTask;
};
Can I get the access token in my web assembly client app razor pages to pass into my query string?