I am learning about signalR security in c#. For signalR there is lot for samples and documents available in google. using this i can understand the signalR concepts. i am trying to create console chat app using authorize. Without authorize attribute i can able to send and receive messages. while using "[authorize]" i am getting below error.
Error: InnerException: System.InvalidOperationException
HResult=-2146233079
Message=There was an error invoking Hub method 'Test.DetermineLength'.
Server Program:
public class Program
{
static void Main(string[] args)
{
string url = #"http://localhost:8080/";
using (WebApp.Start<StartUp>(url))
{
Console.WriteLine(string.Format("Server running at {0}", url));
Console.ReadLine();
}
}
public class StartUp
{
public void Configuration(IAppBuilder app)
{
app.UseCors(CorsOptions.AllowAll);
app.MapSignalR();
}
}
[HubName("Test")]
public class TestHub : Hub
{
[Authorize]
public void DetermineLength(string message)
{
Console.WriteLine(message);
string newMessage = string.Format(#"{0} has a length of: {1}", message, message.Length);
Clients.All.ReceiveLength(newMessage);
}
}
}
Client Program:
public class Program
{
static void Main(string[] args)
{
IHubProxy _hub;
string url = #"http://localhost:8080/";
var connection = new HubConnection(url);
_hub = connection.CreateHubProxy("Test");
connection.Start().Wait();
string line = null;
while ((line = System.Console.ReadLine()) != null)
{
_hub.Invoke("DetermineLength", line).Wait();
_hub.On("ReceiveLength", x => Console.WriteLine(x));
}
}
}
How to perform authorized communications between client and server using siganlR in c#. Help me!
From the SignalR official documentation:
SignalR provides the Authorize attribute to specify which users or roles have access to a hub or method. This attribute is located in the Microsoft.AspNet.SignalR namespace. You apply the Authorize attribute to either a hub or particular methods in a hub. When you apply the Authorize attribute to a hub class, the specified authorization requirement is applied to all of the methods in the hub. This topic provides examples of the different types of authorization requirements that you can apply. Without the Authorize attribute, a connected client can access any public method on the hub.
http://www.asp.net/signalr/overview/security/hub-authorization
Who do you want to authorize that method for? Do you have user defined roles?
You cannot use the method with the Authorize attribute because you don't have any users in your application.
Try defining some roles and see if it works.
Good luck!
Related
I have a problem with the implementation of authorization in my project.
My project is to create a program (chat) in WinForms using SignalR.
I plan to create two applications: client (WinForms) and server (Console).
I currently don't know how to implement user authorization. I have read SignalR documentation and there is an example based on cookies. Unfortunately, I do not know how to implement it in the console because this example is in the web application. I was looking for some tips on the Internet but unfortunatelly there is almost nothing.
class Program
{
static void Main(string[] args)
{
string url = "http://localhost:8085";
using (WebApp.Start<Startup>(url))
{
Console.WriteLine("Server running on {0}", url);
Console.ReadLine();
}
}
}
class Startup
{
public void Configuration(IAppBuilder app)
{
app.UseCors(CorsOptions.AllowAll);
app.MapSignalR();
}
}
}
public class MyHub : Hub
{
public void Send(string name, string message)
{
Clients.All.addMessage(name, message);
}
}
I want to add a remote login feature into the server. The problem is that I don't know how to do it from the console application level. The documentation only shows how to do this in a web application.
I am using signalR in asp.net mvc application,I want to authenticate cross
domain clients by token based authentication.I did not found complete solution for
it.
app.Map("/signalr", map =>
{
map.UseCors(CorsOptions.AllowAll);
map.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions()
{
Provider = new QueryStringOAuthBearerProvider()
});
var hubConfiguration = new HubConfiguration
{
Resolver = GlobalHost.DependencyResolver,
};
map.RunSignalR(hubConfiguration);
});
public class QueryStringOAuthBearerProvider : OAuthBearerAuthenticationProvider
{
public override Task RequestToken(OAuthRequestTokenContext context)
{
var value = context.Request.Query.Get("access_token");
if (!string.IsNullOrEmpty(value))
{
context.Token = value;
}
return Task.FromResult<object>(null);
}
}
public class impAuthHub : Hub
{
[Authorize]
public void SendMessage(string name, string message)
{
Clients.All.newMessage(name, message);
}
}
I dont know how i will get token to pass query string to my startup class?
You will be needed to use OAuth Bearer Token authentication with SignalR. and you need to use Microsoft’s OWIN Security and ASP.NET Identity libraries then include the WebAPI and Individual Accounts security options. This is a Full- Demo
Please find the code base for working sample git , which will help you.
I am Developing a Sample Application in SignalR. My Requirement is i need to receive datas from server to client.But i didn't any pass values from client to server.
Is it possible to use the signalr only for receiving data from server to Client and i did correct?
This is myHubClass:-
public class NameHub : Hub
{
public void send(string Item,string Info)
{
//var name = GlobalHost.ConnectionManager.GetHubContext<NameHub>();
Clients.All.broadcastMessage(Item,Info);
}
}
I need to use the HubClass outside the class.so i created a object for that hub class ,used in my solution.
Sample:-
using (NameHub n = new NameHub())
{
n.Clients.All.broadcastMessage(datePicker, IsLoad);
}
This is my Owin StartupClass:-
public class Startup
{
public void Configuration(IAppBuilder app)
{
app.MapSignalR();
}
}
MyClientSide Code:-
$(function () {
var data = $.connection.NameHub;
data.client.broadcastMessage = function (Item,Info) {
$('div.container').append('<p><strong>'+Item+"="
+ Info + '</strong></p>');
};
Could Anyone Provide me an solution to solve this?
Please ensure i did correctly or wrong?
To get Hub instance outside pipeline:
How to use SignalR hub instance outside of the hubpipleline
Don't forget start client side connection: $.connection.hub.start()
I'm trying to hit my MVC5 SignalR Hub via a separate, tiny client application, to no avail.
Some background:
I have a regular ASP.NET application using SingalR 1.10, that I can hit with my client. Code:
ASP.NET Hub:
namespace SignalrTest
{
public class ScanHub : Hub
{
public void SendScan(string data, string xmlData)
{
Clients.All.broadcastMessage(data, xmlData);
}
}
}
Client:
connection = new HubConnection("http://localhost:2446/");
hubProxy = connection.CreateHubProxy("ScanHub");
connection.Start();
........
private static async Task RunAsync()
{
object[] param = new object[2];
param[0] = _Data;
param[1] = _xmlData;
await hubProxy.Invoke("SendScan", param);
}
and again, that's working fine. My MVC Hub is identical to the other (I've made sure to change the client HubConnection address), and I have my Startup.cs as:
[assembly: OwinStartupAttribute(typeof(SignalrTest.Startup))]
namespace SignalrTest
{
public partial class Startup
{
public void Configuration(IAppBuilder app)
{
app.MapSignalR();
}
}
}
running my client, it fires off with no errors, but I get no response or any indication that anything has occurred on the MVC side.
Can anyone see where I'm going wrong with the MVC app? I'm unclear on whether I need to alter the routing. I'm happy to post any other code that would help resolve my issue. Thankyou in advance.
Are you really using SignalR 1.1? SignalR 1.1 doesn't use OWIN startup classes, and the MapSignalR method shouldn't even compile.
Try throwing your connection on the .NET client into an async method like so and doing a quick test if your connection is good or not.
private async void Connect()
{
connection = new HubConnection("http://localhost:2446/");
hubProxy = connection.CreateHubProxy("ScanHub");
await connection.Start();
//If using WPF you can test like so if not use whatever output method you prefer to see if it connects
if (Connection.State == Microsoft.AspNet.SignalR.Client.ConnectionState.Connected)
{
MessageBox.Show("Connected!");
}
else
{
MessageBox.Show("Fail!");
}
}
I have recently taken an interest in SignalR but have yet to produce a working server, no matter how simple.
I have followed the GitHub Self Host documentation but I receive a nasty 500 Error.
The code I use is the following (basically the GitHub code):
class Program
{
static void Main(string[] args)
{
string host = "http://localhost:2804";
using (WebApplication.Start<InitialConf>(host))
{
Console.WriteLine("Server started on {0}", host);
Console.ReadKey();
}
}
}
class InitialConf
{
public void Configuration(IAppBuilder appBuilder)
{
var config = new HubConfiguration
{
EnableCrossDomain = true
};
// Map to default /signalr route
appBuilder.MapHubs(config);
}
}
class fooHub : Hub
{
public void DisplayTimeOnServer()
{
Console.WriteLine(DateTime.Now.ToString());
}
}
Browsing to http://localhost:2804/signalr produces a 500 Error:
HTTP/1.1 500 Internal Server Error
Content-Length: 0
Server: Microsoft-HTTPAPI/2.0
I receive no exception / error in the application so I'm not sure why it behaves like this.
Anyone have any experiences with these issues? Or perhaps could lead me on to a better documentation on the matter?
Thank you
The problem is that your Hub Class is private.
Just change that to public.
public class fooHub : Hub
{
public void DisplayTimeOnServer()
{
Console.WriteLine(DateTime.Now.ToString());
}
}
Did you try to debug on the server?
And you are missing a function/definition in you Hub to inform your clients:
Clients.All.addMessage(message);
Other that that I suggest that you check the following resources:
Home page of SignalR - tutorial: http://www.asp.net/signalr/overview/getting-started/tutorial-getting-started-with-signalr
Scott's intro: http://www.hanselman.com/blog/AsynchronousScalableWebApplicationsWithRealtimePersistentLongrunningConnectionsWithSignalR.aspx
It seems there is any issue with setting up a route for your connection. After your application is running you should be able to go to /signalr/hubs and see the details about the hubs.