Backoffice SignalR Hub - Returns 401 error with Authorize attribute and unable to get current user

I’m building a backoffice feature using SignalR and need to access the current backoffice user. The problem is that when I add the Authorize attribute to my Hub I get a 401 error returned when a hub connection tries to establish. I am also unable to get the backoffice user using the IBackOfficeSecurityAccessorinstance passed in via the constructor for my Hub.

My setup at the moment is relatively simple:

Authorize(Policy = AuthorizationPolicies.BackOfficeAccess)]
public class MyHub : Hub<IMyHubEvents>

My route is configured as:

$"/{_umbracoPathSegment}/myhub"

I have enabled withCredentialsin my HubConnectionBuilder options as follows:

this.connection = new signalR.HubConnectionBuilder()
        .withUrl("/umbraco/myhub", {
          withCredentials: true,
        })
        .withAutomaticReconnect([0, 2000, 10000, 30000])
        .configureLogging(signalR.LogLevel.Information)
        .build();

Am I missing something else?

Hi,

I think you need to send the login token, to the method to get it to authenticate.

e.g :

this.connection = new signalR.HubConnectionBuilder()
        .withUrl("/umbraco/myhub", {
          accessTokenFactory: () => this.token
        })
        .withAutomaticReconnect([0, 2000, 10000, 30000])
        .configureLogging(signalR.LogLevel.Information)
        .build();

you can get the token from the AUTH_CONTEXT

this.consumeContext(UMB_AUTH_CONTEXT, async (auth) => {
   if (!auth) return;
   const authConfig = auth?.getOpenApiConfiguration();
   this.token = auth.getLatestToken());
});

i tend to setup the hub in the consume. so you can pass the token directly to the method setting up the auth

this.consumeContext(UMB_AUTH_CONTEXT, async (auth) => {
	if (!auth) return;

	const authConfig = auth?.getOpenApiConfiguration();
	if (!authConfig) return;
	this.#setupConnection('/umbraco/myhub', await auth.getLatestToken());
});

@KevinJump This current version of the feature is for Umbraco 13 - I’m not sure that UMB_AUTH_CONTEXT is available? Digging a bit deeper into that now but so far no luck.

I seem to have gotten around the issue by adding the following:

this.connection = new signalR.HubConnectionBuilder()
        .withUrl("/umbraco/myhub", {
          withCredentials: true,
          skipNegotiation: true,
          transport: signalR.HttpTransportType.WebSockets
        })
        .withAutomaticReconnect([0, 2000, 10000, 30000])
        .configureLogging(signalR.LogLevel.Information)
        .build();

The key being the skipNegotiation: true part I think whilst still retaining the withCredentialsto ensure the auth cookie is sent.

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.