Skip to content

Commit d90ffd7

Browse files
committed
Added Authentication in SignalR hub
1 parent c163e21 commit d90ffd7

File tree

2 files changed

+25
-0
lines changed

2 files changed

+25
-0
lines changed

src/Api/Hubs/BroadcastHub.cs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,10 @@
11
using System.Threading.Tasks;
2+
using Microsoft.AspNetCore.Authorization;
23
using Microsoft.AspNetCore.SignalR;
34

45
namespace Hubs.BroadcastHub
56
{
7+
[Authorize]
68
public class BroadcastHub : Hub
79
{
810
}

src/Api/Startup.cs

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -120,6 +120,29 @@ public void ConfigureServices(IServiceCollection services)
120120
configureOptions.ClaimsIssuer = jwtAppSettingOptions[nameof(JwtIssuerOptions.Issuer)];
121121
configureOptions.TokenValidationParameters = tokEnvironmentalidationParameters;
122122
configureOptions.SaveToken = true;
123+
124+
// We have to hook the OnMessageReceived event in order to
125+
// allow the JWT authentication handler to read the access
126+
// token from the query string when a WebSocket or
127+
// Server-Sent Events request comes in.
128+
// https://docs.microsoft.com/en-us/aspnet/core/signalr/authn-and-authz?view=aspnetcore-2.2
129+
configureOptions.Events = new JwtBearerEvents
130+
{
131+
OnMessageReceived = context =>
132+
{
133+
var accessToken = context.Request.Query["access_token"];
134+
135+
// If the request is for our hub...
136+
var path = context.HttpContext.Request.Path;
137+
if (!string.IsNullOrEmpty(accessToken) &&
138+
(path.StartsWithSegments("/broadcast")))
139+
{
140+
// Read the token out of the query string
141+
context.Token = accessToken;
142+
}
143+
return Task.CompletedTask;
144+
}
145+
};
123146
});
124147

125148
// Add Identity

0 commit comments

Comments
 (0)