There are too many authentication types (Basic, Windows, Cookie, OAuth) to explain how to use all of them. In this sample, I focus on using Cookie Authentication to secure a website, a Persistent Connection, and a Hub. Authentication is configured on OWIN, you have to add some nuget packages and add code in Startup.cs. I started with a web project using the MVC Template. By default, it creates web forms to register users, input user credentials, configures an anti-forgery token for http requests, creates an entity framework repository for User Identity. For the self host server there is no template, so I created it using the previous project as sample but removed things like the anti-forgery token, MVC, and entity framework.
The important thing to remember is OWIN takes care of authentication and all frameworks on top of OWIN (SignalR, MVC, WebApi, etc) simply consume the user identity provided by OWIN. So, if you can’t see the identity on SignalR, the problem is in your OWIN configuration.
A SignalR Persistent Connection gives you access to the user identity by overriding AuthorizeRequest method. The sample code below allows to create a persistent connection only to authenticated users. you could add more logic to allow only some user roles by using the method request.User.IsInRole(string role)
namespace Common.Connections { public class AuthorizeEchoConnection : PersistentConnection { protected override bool AuthorizeRequest(IRequest request) { return request.User != null && request.User.Identity.IsAuthenticated; } ... } } |
A SignalR Hub gives you access to the user identity using Context.User. If you want to restrict access to a Hub only to authenticated users, add the [Authorize] attribute. Do you want to allow only some user roles? Add [Authorize(Roles="myRole")]. Do you want to allow specific users? Add [Authorize(Users="myUser")]
namespace Common.Hubs { [Authorize] public class AuthorizeEchoHub : Hub { public override Task OnConnected() { return Clients.Caller.hubReceived("Welcome " + Context.User.Identity.Name + "!"); } ... } } |
Full sample code is here. It contains a web host server and a self host server. Then you can use any of the clients to authenticate and establish a SignalR connection:
- JavaScript client connecting as cross-domain
- C# console client
- C# windows phone
- C# windows store app
For more information, read SignalR documentation about security
0 comments