7

I am using WebApi and token based authentication for my api controllers.(Authorization :bearer xyzabc..) I now have a signalR hub and would like to authenticate clients by the same token they have on the client side.

How would i do that ? This link shows how to send token through url parameter, but i am not sure how i can use that token and authenticate the user on server side.

Community
  • 1
  • 1
Koder
  • 1,794
  • 3
  • 22
  • 41

3 Answers3

2

I solved this by passing the token as a parameter of my Hub method instead of header. but i imagine it is possible to do it using headers too (just extracting the token from Context.Headers or something).

Either way, after getting the token in your hub method, just use this code.

    public Task SendMessage(string message, string token)
    {
        var ticket = Startup.OAuthOptions.AccessTokenFormat.Unprotect(token);
        bool isAuth = ticket.Identity.IsAuthenticated;
       //You can retrieve other details like username and userid from ticket
       ...rest of your code..
    }
Koder
  • 1,794
  • 3
  • 22
  • 41
0

I wouldn't send the token every time. I'd establish your context user principal on the OnConnected virtual method and read from a query string passed from a token.

In my case. I just created an abstract class that inherited from the Hub class and then stuffed my oauth claims generation logic there. Then my regular concrete hubs just inherited from my base custom hub class.

Another option would be to use either a custom authorize attribute or another hub pipeline module.

I think these tactics might keep your code DRY and extendable.

Max Alexander
  • 5,471
  • 6
  • 38
  • 52
0

I've discovered that when you call the default /Token handler from Web API from something like JQuery, the browser is also sent a cookie which is used to authenticate you with SignalR.

You ought to be able to use the [Authorize] attribute as well as "Context.User.Identity" in your SignalR hub methods to get the current user as long as you've called /Token with valid credentials from the browser before connecting to the hub.

Hayden McAfee
  • 506
  • 1
  • 4
  • 18