Azure / azure-signalr

Azure SignalR Service SDK for .NET
https://aka.ms/signalr-service
MIT License
427 stars 101 forks source link

Getting 401 While sending messages to Specific Connection in REST API #1953

Open DilLip-Chowdary-Codes opened 5 months ago

DilLip-Chowdary-Codes commented 5 months ago

Describe the bug

While we're trying to send a message to specific connectionId, we're receiving the 401 status code

More Details:

Code:

FYI Access token was generated using the SignalR Serverless Quick start with python

    import requests
    import json

    name = "Dillip"

    connection_id = "g9.....rQw02"

    token = "eyJh....-wH6nA8"

    headers = {
        "Authorization": f"Bearer {token}",
        'Content-Type': 'application/json',
    }

    body = {
        'target': 'newMessage',
        'arguments': [ f"Update Name was as {name}" ]
    }

    response = requests.post(
       f"https://<our-service>.service.signalr.net/api/v1/hubs/<hub_name>/connections/{connection_id}",
        json=body,
        headers=headers
    )

    print(response.content, response.status_code)

Exceptions (if any)

We're getting b'' as API response and 401 as status code.

Further technical details

REST API Version: V1

### Tasks
Y-Sindo commented 5 months ago

The access token generated in SignalR Serverless Quick start with python negotiate function is for SignalR client connection only. Specifically, the aud claim in the access token should be the same as your HTTP request URL, not including the trailing slash and query parameters. , that is https://<our-service>.service.signalr.net/api/v1/hubs/<hub_name>/connections/{connection_id}.

BTW, you could use SignalR function extensions in Python to send messages to a connection, like this:

def main(req: func.HttpRequest, signalROutput: func.Out[str]) -> func.HttpResponse:
    message = req.get_json()
    signalROutput.set(json.dumps({
        #message will only be sent to this user ID
        'connectionId': 'connectionId',
        'target': 'newMessage',
        'arguments': [ message ]
    }))
DilLip-Chowdary-Codes commented 5 months ago

@Y-Sindo Thanks for the update it helped us :heart:

BTW, you could use SignalR function extensions in Python to send messages to a connection, like this:

But we need to send message as part of our business logic, so we can't choose this.