Dor Schreiber
Dor Schreiber

Reputation: 71

SignalR with openiddict user claims with react

I'm currently working on a project with a react client and asp.net server. I was tryin to add authorization to the signalR requests in the server using the existing claims that the user use in the api but I couldn't wrap my head around it. I managed to receive the access token from the client but I don't understand how I can receive Context.User.Claims.

I'm adding the client signalR connection and a try from the server:

client:

let newConnection = new HubConnectionBuilder()
      .configureLogging(LogLevel.Debug)
      .withUrl(`${URL}${HubUrl}?access_token=${'SampleAccessToken'}`, {
        // a token factory for the server, not sure why we need it
        // accessTokenFactory: () => 'SampleAccessToken',
        skipNegotiation: true,
        transport: HttpTransportType.WebSockets,
      })
      .build();

Server:

public async Task JoinJobGroup()
    {
        var httpContext = Context.GetHttpContext();
        var tmp = httpContext.Request.Query["access_token"];

        // TODO: Receive the claims form tmp or other solution
        // TODO: Check if claim is valid for operation
        
        await _Context.Groups.AddToGroupAsync(Context.ConnectionId, "JOB_GROUP_NAME");
    }

Upvotes: 1

Views: 627

Answers (1)

Martin Massé
Martin Massé

Reputation: 61

Using the token factory is preferred since it send the current token value. Your code won't work if the token change (Ex. you support refresh token).

The claims should be available in the User Principal if your authentication is correctly configured. Make sure you have added the Authorize attribute to your hub.

Most of the information you are looking for is available here

https://learn.microsoft.com/en-us/aspnet/core/signalr/authn-and-authz?view=aspnetcore-6.0

Upvotes: 0

Related Questions