I have Three applications.
1)Windows Application
2)Asp.net web form
3)Asp.net MVC
I have a Authentication and Authorization system that implemented using a web service. In simple form the underlying tables are like:
User Table:
Id UserName Password
---------------------------------
Role Table;
Id RoleName
---------------------------------
UserRole
UserId RoleId
---------------------------------
Now I want to implement a chat capability for these apps. My problem is I don’t know how to integrate SignalR
with my custom authentication. Consider this scenario that a user wants to send a message to another user:
public async Task SendMessage(string user1, string user2, string message)
this method works find in first glance. But how can I prevent this scenario:
if
user3
knowsuser1
username and create a request and send a message fromuser1
touser2
?
Since I can’t change my auth service to user Asp.net Identity and integrate it with SignalR How can I be sure that the logged in user send the message and no one can do impersonation?
Could any body help me to get the correct idea and plan?
Thanks
3
Answers
You can implement a custom authorization attribute where you do the necessary checks and reject unauthorised users /accept authorised users. You could then decorate the desired hub classes/methods with the custom authorization attribute.
You should find this answer to a similar question helpful: https://stackoverflow.com/a/14343581/19214431.
You have different kind of client application. So I recommend to use Bearer token for authentication. The client app should add a bearer token to the request that send to server. I don’t know which version of .net do you use but it easy to configure using .net core.
In web app:
In the Windows app
The thing is that the identity server should provide the token the client. I see you implemented your identity server. Using the built-in library like Microsoft.AspNetCore.Identity and Entityframework Core would have made life easier in this case. Also using IdentityServer is an option. Otherwise you need to implement and develop your custom IdentityServer that provide access token to clients.
Authentication and authorization in ASP.NET Core SignalR
Using IdentityServer
Creating And Validating JWT Tokens In C# .NET
I don’t know which version of .net you use
but I try .net core 6.
you can try is The Context object
because Gets the unique ID for the connection, assigned by SignalR. There’s one connection ID for each connection.
https://learn.microsoft.com/en-us/aspnet/core/signalr/hubs?view=aspnetcore-6.0
I try to Save the ID and message then judge if the Items have key is ok.
you can try unique ID be sure that the logged-in user sends the message and no one can do an impersonation.
ChatHub.cs