SignalR authentication with javascript client

I played with open authentication in MVC5 and SignalR . I use a javascript client to call a simple server method on SignalR and get a response from the server. It works well, but if I add the [Authorize] tag, it will not even call the server method (did not receive a response during debugging).

My assumption was that the server would use an authentication mechanism to challenge the client. Did I miss something? Do I have to manually authenticate the user from the client side, and if so, how can I pass the authentication token?

Here is my hub :

  [HubName("authChatHub")] public class AuthChatHub : Hub { [Authorize] public void Ping() { Clients.Caller.Pong("Connection is FINE!!"); Clients.Caller.Pong(Context.User == null ? "Null user" : Context.User.Identity.IsAuthenticated.ToString()); } } 

Here is my Startup.Auth.cs

  public void ConfigureAuth(IAppBuilder app) { app.UseGoogleAuthentication(); } 

Here's Startup.cs using the code to enable CORS.

 public partial class Startup { public void Configuration(IAppBuilder app) { ConfigureAuth(app); //added this after a suggestion here, not sure if this is the right place. app.Map("/signalr", map => { map.UseCors(CorsOptions.AllowAll); var hubConfiguration = new HubConfiguration { // EnableJSONP = true //empty for now }; map.RunSignalR(hubConfiguration); }); } } 

And finally, this client side code calls the hub method and listens on the RPC server.

 this.sendMessage = () => { this.authChat.server.ping(); }; this.authChat.client.pong = (message) => { console.log(message); }; 
+3
source share
4 answers

You should use form or window validation, as you will use any other asp.net application. After authentication, your calls will work the same way as before you apply the [Authorize] attribute to the hub.

SignalR itself is not involved in authentication.

First you need to go through authentication, and then send the token to the server, I think this link will help you achieve what you want to do.

+1
source

you can add an authentication token to the request string, which will be sent to the server when the java script client initiates a connection to the signalr server.

client side: connection.qs = { 'Token' : 'your token string'};

server side: var Token = IRequest.QueryString["Token"];

+1
source

You can use Toker Token for authentication, and then track the authenticated user with a cookie. Then your SignalR requests will contain cookies and SignalR that recognize the user and process all your [Authorized] configurations

Here is an example

0
source

The Authorize attribute specified in the hub method will make it available only to authenticated users.

When applying the Authorize attribute to a hub class, the specified authorization requirement applies to all methods in the hub

http://www.asp.net/signalr/overview/signalr-20/security/hub-authorization

-1
source

Source: https://habr.com/ru/post/1268385/


All Articles