SignalR 404 when connecting using .Net Client - signalr.client

What is the URL do we need to put, when connecting to SignalR core.
When we try to put Url as https://localhost:44308, it says not found. Yes web server is running. Any suffix is required?
HubConnection connection;
connection = new HubConnectionBuilder()
.WithUrl(**Url**)
.Build();
await connection.StartAsync();
bool isClosed = false;
connection.Closed += async (error) =>
{
isClosed = true;
await Task.Delay(new Random().Next(0, 5) * 1000);
await connection.StartAsync();
};
if (isClosed == false)
{
connection.InvokeAsync("NewMessage", "from server", $"{DateTime.Now.ToShortDateString()}").Wait();
}

Changes in Signal Core:
https://localhost:44308 should contain, Hub suffix, so correct URL is:
https://localhost:44308/hub
this is configurable in Startup.cs

Related

SignalR Azure Service with stand alone Identity Server 4 returns 401 on negotiaton

We have a ASP.Net Core application that authenticates against a standalone Identity Server 4. The ASP.Net Core app implements a few SignalR Hubs and is working fine when we use the self hosted SignalR Service. When we try to use the Azure SignalR Service, it always returns 401 in the negotiation requests. The response header also states that
"Bearer error="invalid_token", error_description="The signature key
was not found"
I thought the JWT-Configuration is correct because it works in the self hosted mode but it looks like, our ASP.Net Core application needs information about the signature key (certificate) that our identity server uses to sign the tokens. So I tried to use the same method like our identity server, to create the certificate and resolve it. Without luck :-(
This is what our JWT-Configuration looks like right now:
services.AddAuthentication("Bearer")
.AddJwtBearer("Bearer", options => {
var appSettings = Configuration.Get<AppSettingsModel>();
options.Authority = appSettings.Authority;
options.RefreshOnIssuerKeyNotFound = true;
if (environment.IsDevelopment()) {
options.RequireHttpsMetadata = false;
}
options.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters {
ValidateAudience = false,
IssuerSigningKey = new X509SecurityKey(getSigningCredential()),
IssuerSigningKeyResolver = (string token, SecurityToken securityToken, string kid, TokenValidationParameters validationParameters) =>
new List<X509SecurityKey> { new X509SecurityKey(getSigningCredential()) }
};
options.Events = new JwtBearerEvents {
OnMessageReceived = context => {
var accessToken = "";
var headerToken = context.Request.Headers[HeaderNames.Authorization].ToString().Replace("Bearer ", "");
if (!string.IsNullOrEmpty(headerToken) && headerToken.Length > 0) {
accessToken = headerToken;
}
var queryStringToken = context.Request.Query["access_token"];
if (!string.IsNullOrEmpty(queryStringToken) && queryStringToken.ToString().Length > 0) {
accessToken = queryStringToken;
}
// If the request is for our hub...
var path = context.HttpContext.Request.Path;
if (!string.IsNullOrEmpty(accessToken) && path.StartsWithSegments("/hubs")) {
context.Token = accessToken;
}
return Task.CompletedTask;
}
};
});
Update:
We also have a extended the signalR.DefaultHttpClient in our Angular Client and after playing around a bit, I noticed the application is working fine without it:
export class CustomSignalRHttpClientService extends signalR.DefaultHttpClient {
userSubscription: any;
token: string = "";
constructor(private authService: AuthorizeService) {
super(console); // the base class wants a signalR.ILogger
this.userSubscription = this.authService.accessToken$.subscribe(token => {
this.token = token
});
}
public async send(
request: signalR.HttpRequest
): Promise<signalR.HttpResponse> {
let authHeaders = {
Authorization: `Bearer ${this.token}`
};
request.headers = { ...request.headers, ...authHeaders };
try {
const response = await super.send(request);
return response;
} catch (er) {
if (er instanceof signalR.HttpError) {
const error = er as signalR.HttpError;
if (error.statusCode == 401) {
console.log('customSignalRHttpClient -> 401 -> TokenRefresh')
//token expired - trying a refresh via refresh token
this.token = await this.authService.getAccessToken().toPromise();
authHeaders = {
Authorization: `Bearer ${this.token}`
};
request.headers = { ...request.headers, ...authHeaders };
}
} else {
throw er;
}
}
//re try the request
return super.send(request);
}
}
The problem is, when the token expires while the application is not open (computer is in sleep mode e.g.), the negotiaton process is failing again.
I finally found and solved the problem. The difference of the authentication between "self hosted" and "Azure SignalR Service" is in the negotiation process.
Self Hosted:
SignalR-Javascript client authenticates against our own webserver with
the same token that our Javascript (Angular) app uses. It sends the
token with the negotiation request and all coming requests of the
signalR Http-Client.
Azure SignalR Service:
SignalR-Javascript client sends a negotiation request to our own
webserver and receives a new token for all coming requests against the
Azure SignalR Service.
So our problem was in the CustomSignalRHttpClientService. We changed the Authentication header to our own API-Token for all requests, including the requests against the Azure SignalR Service -> Bad Idea.
So we learned that the Azure SignalR Service is using it's own token. That also means the token can invalidate independently with our own token. So we have to handle 401 Statuscodes in a different way.
This is our new CustomSignalRHttpClientService:
export class CustomSignalRHttpClientService extends signalR.DefaultHttpClient {
userSubscription: any;
token: string = "";
constructor(private authService: AuthorizeService, #Inject(ENV) private env: IEnvironment, private router: Router,) {
super(console); // the base class wants a signalR.ILogger
this.userSubscription = this.authService.accessToken$.subscribe(token => {
this.token = token
});
}
public async send(
request: signalR.HttpRequest
): Promise<signalR.HttpResponse> {
if (!request.url.startsWith(this.env.apiUrl)) {
return super.send(request);
}
try {
const response = await super.send(request);
return response;
} catch (er) {
if (er instanceof signalR.HttpError) {
const error = er as signalR.HttpError;
if (error.statusCode == 401 && !this.router.url.toLowerCase().includes('onboarding')) {
this.router.navigate([ApplicationPaths.Login], {
queryParams: {
[QueryParameterNames.ReturnUrl]: this.router.url
}
});
}
} else {
throw er;
}
}
//re try the request
return super.send(request);
}
}
Our login-Route handles the token refresh (if required). But it could also happen, that our own api-token is still valid, but the Azure SignalR Service token is not. Therefore we handle some reconnection logic inside the service that creates the SignalR Connections like this:
this.router.events.pipe(
filter(event => event instanceof NavigationEnd)
).subscribe(async (page: NavigationEnd) => {
if (page.url.toLocaleLowerCase().includes(ApplicationPaths.Login)) {
await this.restartAllConnections();
}
});
hope this helps somebody

XUnit Integration Testing with Identityserver: Token received from Identityserver is unable to match key

I'm currently trying to implement Integration Testing in an environment with 2 servers:
A .NET Core API server
An IdentityServer4 Authentication Server
Through much struggle, I've managed to get the two to communicate with eachother, however, IdentityServer throws the following error when trying to confirm the JWT token (Through the API):
Bearer was not authenticated. Failure message: IDX10501: Signature
validation failed. Unable to match key: kid:
'8C1D5950D083E20D4B20DE9B37AC71FAEF679469'.
I'll try to keep the code sample brief:
In the XUnit startup, I configure and create clients for both TestServers.
public APITestBase(ITestOutputHelper output)
{
_output = output;
var apicon = new ConfigurationBuilder()
.AddJsonFile("apisettings.json", optional: true, reloadOnChange: true)
.Build();
var authcon = new ConfigurationBuilder()
.AddJsonFile("authsettings.json", optional: true, reloadOnChange: true)
.Build();
_authServer = new TestServer(new WebHostBuilder()
.UseConfiguration(authcon)
.ConfigureLogging(x => x.AddXUnit(_output))
.UseEnvironment("Development")
.UseStartup<Auth.Startup>());
_authClient = _authServer.CreateClient();
_server = new TestServer(new WebHostBuilder()
.UseConfiguration(apicon)
.ConfigureLogging(x => x.AddXUnit(_output))
.UseEnvironment("Test")
.ConfigureServices(
services => {
//Here, I'm adding an httpclienthandler. In the application I will use this as JWTBackChannelHandler. This allows communication between the two servers
services.AddSingleton<HttpMessageHandler>(_authServer.CreateHandler());
})
.UseStartup<Api.Startup>());
_client = _server.CreateClient();
APIConfig = new Cnfg();
apicon.Bind("APIConfig", APIConfig);
//Make users in api
}
Here is the actual test I am trying to run
[Fact]
public async Task ApplyTest()
{
_client.SetBearerToken(await GetAccessToken());
// Act
var response = await _client.GetAsync($"{APIConfig.ApiBaseUrl}api/call/");
response.EnsureSuccessStatusCode();
}
And here is GetAccessToken, which returns the JWT token that the integration uses to identify itself as a user... At least that's the plan.
protected async Task<string> GetAccessToken()
{
var disco = await _authClient.GetDiscoveryDocumentAsync(new DiscoveryDocumentRequest()
{
Address = _authServer.BaseAddress.ToString(),
Policy =
{
ValidateIssuerName = false
}
});
if (!String.IsNullOrEmpty(disco.Error))
{
throw new Exception(disco.Error);
}
var response = await _authClient.RequestPasswordTokenAsync(new PasswordTokenRequest
{
Address = disco.TokenEndpoint,
GrantType = "password",
ClientId = "api",
UserName = "test#test.nl",
Password = "test"
});
return response.AccessToken;
}
The only identifiable difference I can find between a JWT token generated through this function and that of a normal website request is that the Public Key is missing (according to jwt.io).
Finally, because I think this bit might be useful, here's the part of the API's Startup.cs where I enforce the use of the JWTBackChannelHandler
if (Environment.EnvironmentName == "Test")
{
services.AddAuthentication(IdentityServerAuthenticationDefaults.AuthenticationScheme)
.AddIdentityServerAuthentication(IdentityServerAuthenticationDefaults.AuthenticationScheme, o =>
{
o.JwtBackChannelHandler = _identityServerMessageHandler;
o.RequireHttpsMetadata = false;
})
.AddApiKeyAuthenication(o =>
{
o.Keys.Add("****".ToSha256());
o.Keys.Add("****".ToSha256());
});
}
Thank you very much in advance for your help, I've kind of reached the end of my wits with this one. Please let me know if you want any more information and I'll be happy to provide.
After another 2 hours of digging I found out that I needed to add
o.Authority = identityServerOptions.Address.AbsoluteUri;
To the AddIdentityServerAuthentication.
Thank you to those who took the time into digging into my issue for me.

Blazor WebAssembly SignalR Authentication

I would love to see an example on how to add authentication to a SignalR hub connection using the WebAssembly flavor of Blazor. My dotnet version is 3.1.300.
I can follow these steps to get an open, unauthenticated SignalR connection working: https://learn.microsoft.com/en-us/aspnet/core/tutorials/signalr-blazor-webassembly?view=aspnetcore-3.1&tabs=visual-studio
All the tutorials I find seem older or are for a server-hosted type, and don't use the built-in template.
I have added authentication to the rest of the back-end, using the appropriate template and these instructions, including the database:
https://learn.microsoft.com/en-us/aspnet/core/security/blazor/?view=aspnetcore-3.1
But every time I add [Authenticate] to the chat hub, I get an error returned. Is there any way, extending the first tutorial, that we can authenticate the hub that is created there? It would be great to hitch on to the built-in ASP.NET system, but I am fine just passing a token in as an additional parameter and doing it myself, if that is best. In that case I would need to learn how to get the token out of the Blazor WebAssembly, and then look it up somewhere on the server. This seems wrong, but it would basically fill my needs, as an alternative.
There are all sorts of half-solutions out there, or designed for an older version, but nothing to build off the stock tutorial that MS presents.
Update:
Following the hints in this news release https://devblogs.microsoft.com/aspnet/blazor-webassembly-3-2-0-preview-2-release-now-available/, I now can get a token from inside the razor page, and inject it into the header. I guess this is good?? But then how do I get it and make use of it on the server?
Here is a snippet of the razor code:
protected override async Task OnInitializedAsync()
{
var httpClient = new HttpClient();
httpClient.BaseAddress = new Uri(UriHelper.BaseUri);
var tokenResult = await AuthenticationService.RequestAccessToken();
if (tokenResult.TryGetToken(out var token))
{
httpClient.DefaultRequestHeaders.Add("Authorization", $"Bearer {token.Value}");
hubConnection = new HubConnectionBuilder()
.WithUrl(UriHelper.ToAbsoluteUri("/chatHub"), options =>
{
options.AccessTokenProvider = () => Task.FromResult(token.Value);
})
.Build();
}
}
Update 2:
I tried the tip in here: https://github.com/dotnet/aspnetcore/issues/18697
And changed my code to:
hubConnection = new HubConnectionBuilder()
.WithUrl(NavigationManager.ToAbsoluteUri("/chatHub?access_token=" + token.Value))
.Build();
But no joy.
I've come across the same issue.
My solution was 2-sided: I had to fix something in the fronend and in the backend.
Blazor
In your connection builder you should add the AccessTokenProvider:
string accessToken = "eyYourToken";
connection = new HubConnectionBuilder()
.WithUrl("https://localhost:5001/hub/chat", options =>
{
options.AccessTokenProvider = () => Task.FromResult(token.Value);
})
.Build();
options.AccessTokenProvider is of type Func<Task<string>>, thus you can also perform async operations here. Should that be required.
Doing solely this, should allow SignalR to work.
Backend
However! You might still see an error when SignalR attempts to create a WebSocket connection. This is because you are likely using IdentityServer on the backend and this does not support Jwt tokens from query strings. Unfortunately SignalR attempts to authorize websocket requests by a query string parameter called access_token.
Add this code to your startup:
.AddJwtBearer("Bearer", options =>
{
// other configurations omitted for brevity
options.Events = new JwtBearerEvents
{
OnMessageReceived = context =>
{
var accessToken = context.Request.Query["access_token"];
// If the request is for our hub...
var path = context.HttpContext.Request.Path;
if (!string.IsNullOrEmpty(accessToken) &&
(path.StartsWithSegments("/hubs"))) // Ensure that this path is the same as yours!
{
// Read the token out of the query string
context.Token = accessToken;
}
return Task.CompletedTask;
}
};
});
edit 1: Clarified the usage of the Blazor SignalR code
In my case (Blazor WebAssembly, hosted on ASP.NET Core 5.0 using JWT Bearer Token Auth), I had to add the following:
Blazor WASM Client
When building the connection (in my case: in the constructor of some service proxy class), use IAccessTokenProvider and configure the AccessTokenProvider option like so:
public ServiceProxy(HttpClient httpClient, IAccessTokenProvider tokenProvider) {
HubConnection = new HubConnectionBuilder()
.WithUrl(
new Uri(httpClient.BaseAddress, "/hubs/service"),
options => {
options.AccessTokenProvider = async () => {
var result = await tokenProvider.RequestAccessToken();
if (result.TryGetToken(out var token)) {
return token.Value;
}
else {
return string.Empty;
}
};
})
.WithAutomaticReconnect() // optional
.Build();
}
ASP.NET Core Server
Add the following to Startup.ConfigureServices:
services.Configure<JwtBearerOptions>(JwtBearerDefaults.AuthenticationScheme, options => {
// store user's "name" claim in User.Identity.Name
options.TokenValidationParameters.NameClaimType = "name";
// pass JWT bearer token to SignalR connection context
// (from https://learn.microsoft.com/en-us/aspnet/core/signalr/authn-and-authz?view=aspnetcore-5.0)
options.Events = new JwtBearerEvents {
OnMessageReceived = context => {
var accessToken = context.Request.Query["access_token"];
// If the request is for on of our SignalR hubs ...
if (!string.IsNullOrEmpty(accessToken) &&
(context.HttpContext.Request.Path.StartsWithSegments("/hubs/service"))) {
// Read the token out of the query string
context.Token = accessToken;
}
return Task.CompletedTask;
}
};
});
This is my solution and works
[Inject] HttpClient httpClient { get; set; }
[Inject] IAccessTokenProvider tokenProvider { get; set; }
HubConnection hubConnection { get; set; }
(...)
private async Task ConnectToNotificationHub()
{
string url = httpClient.BaseAddress.ToString() + "notificationhub";
var tokenResult = await tokenProvider.RequestAccessToken();
if (tokenResult.TryGetToken(out var token))
{
hubConnection = new HubConnectionBuilder().WithUrl(url, options =>
{
options.Headers.Add("Authorization", $"Bearer {token.Value}");
}).Build();
await hubConnection.StartAsync();
hubConnection.Closed += async (s) =>
{
await hubConnection.StartAsync();
};
hubConnection.On<string>("notification", m =>
{
string msg = m;
});
}
}

SignalR Core not generating(mapping) Client methods

The SignalR Core is generating Hub proxies script, but not adding the "client" methods. (No errors in server or client - only not working)
Generated JS from <script src="http://localhost/signalr/hubs">
proxies['messageHub'] = this.createHubProxy('messageHub');
proxies['messageHub'].client = { };
proxies['messageHub'].server = {
handleMessage: function (receivedString) {
return proxies['messageHub'].invoke.apply(proxies['messageHub'], $.merge(["HandleMessage"], $.makeArray(arguments)));
}
};
Here's the Hub in Server Side:
public class MessageHub : Hub
{
public void HandleMessage(string receivedString)
{
var responseString = string.Empty;
MessageHandler.HandleMessage(receivedString, ref responseString);
Clients.All.sendMessage(responseString);
}
}
The sendMessage methos should be included in the messageHub client proxies in the JS file.
$.connection.messageHub.client.sendMessage is undefined
Only the handleMessage for server proxies was created (and working).
Here's my StartUp.cs inclusions for SignalR:
ConfigureServices:
services.AddMvc(options =>
{
options.Filters.Add(new RoleFilterAttribute());
}).AddJsonOptions(options => options.SerializerSettings.ContractResolver =
new DefaultContractResolver());
services.AddSignalR(options => options.Hubs.EnableDetailedErrors = true)
Configure:
app.UseWebSockets();
app.UseSignalR();
project.json:
"Microsoft.AspNetCore.Mvc": "1.0.0-*",
"Microsoft.AspNetCore.WebSockets": "1.0.0",
"Microsoft.AspNetCore.SignalR.Server": "0.2.0-*",
SOME ADDITIONAL TENTATIVES:
1 - Change method case in Server Side to see if it's mapped:
Clients.All.SendMessage(responseString);
Did not work!
2 - Change the client side to dynamic mapping:
var connection = $.hubConnection('http://localhost/');
var proxy = connection.createHubProxy('messageHub');
connection.start({ withCredentials: false }).done(function () { console.log("CONNECTED") });
proxy.on("sendMessage", function (result) {console.log(result);});
proxy.invoke("handleMessage", msg).done(function(result)console.log(result);});
Again only the handleMessage (server) worked.
Well according to the docs you are missing method name so the send all line should look like this
public void HandleMessage(string receivedString)
{
var responseString = string.Empty;
MessageHandler.HandleMessage(receivedString, ref responseString);
Clients.All.SendMessage("SendMessage",responseString);
}
Also in the following is the correct way
app.UseSignalR(routes =>
{
routes.Hub<MessageHub>("/messageHub");
});
and finally
var connection = $.hubConnection('http://localhost/');
var proxy = connection.createHubProxy('messageHub');
connection.start({ withCredentials: false }).done(function () { console.log("CONNECTED") });
proxy.on("SendMessage", function (result) {console.log(result);});
proxy.invoke("HandleMessage", msg).done(function(result)console.log(result);});
ASP.NET Core SignalR doesn't generate client proxies. There's good advice in the comment to follow the tutorial https://learn.microsoft.com/en-us/aspnet/core/tutorials/signalr?view=aspnetcore-6.0&tabs=visual-studio

Consume WCF service in Titanium

I have written a code to consume the WCF service in my Titanium Project.
Alloy.Globals.wcfservice=function callservice()
{
//fetching data from server.
var xhr = Titanium.Network.createHTTPClient();
xhr.setTimeout(1200);
console.log(xhr.status);
console.log(xhr.statusText);
xhr.onerror = function(e) /* on error in getting data from server */
{
//check response status and act aaccordingly.
if (xhr.status != 200) {
alert("The service is currently unavailable. Please Try Again Later.");
return;
}
};
//on getting response from server.
xhr.onload = function()
{
alert(this.responseText);
var response = XML.parse(this.responseText);
};
//set the url for the service to the get student courses
var request_url = getWebserviceURL() + "GetAvailableAppointmentFromWCF";
console.log(request_url);
xhr.open("POST", request_url);
xhr.send();
};
But I always receive status as 0, "the service is currently unavailable. Please Try Again Later" . What wrong am I doing in this code?