Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions samples/AdvancedChatRoom/AdvancedChatRoom.csproj
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<TargetFramework>net11.0</TargetFramework>
<UserSecretsId>advancedchatroom</UserSecretsId>
<RootNamespace>Microsoft.Azure.SignalR.Samples.AdvancedChatRoom</RootNamespace>
</PropertyGroup>
Expand All @@ -10,7 +10,7 @@
</ItemGroup>

<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="7.0.8" />
<PackageReference Include="Microsoft.Azure.SignalR" Version="1.*" />
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="11.0.0" />
<PackageReference Include="Microsoft.Azure.SignalR" Version="1.34.0" />
</ItemGroup>
</Project>
3 changes: 2 additions & 1 deletion samples/AdvancedChatRoom/Controller/JwtController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Security.Cryptography;
using Microsoft.AspNetCore.Mvc;
using Microsoft.IdentityModel.Tokens;

Expand All @@ -14,7 +15,7 @@ namespace Microsoft.Azure.SignalR.Samples.AdvancedChatRoom
[Route("jwt")]
public class JwtController : Controller
{
private static readonly SecurityKey SigningKey = new SymmetricSecurityKey(Guid.NewGuid().ToByteArray());
private static readonly SecurityKey SigningKey = new SymmetricSecurityKey(RandomNumberGenerator.GetBytes(32));

private static readonly JwtSecurityTokenHandler JwtTokenHandler = new JwtSecurityTokenHandler();

Expand Down
2 changes: 1 addition & 1 deletion samples/AdvancedChatRoom/Dockerfile
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
FROM mcr.microsoft.com/dotnet/sdk:6.0 AS build
FROM mcr.microsoft.com/dotnet/sdk:11.0 AS build
WORKDIR /src/AdvancedChatRoom

COPY ./. ./
Expand Down
14 changes: 9 additions & 5 deletions samples/AdvancedChatRoom/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,22 +12,26 @@ Now the sample supports:
* Send to User / Users
* Cookie / JWT based Authentication
* Role / Claim / Policy based Authrization
* JWT authentication refresh without reconnecting

## Run the sample locally

Authentication refresh requires SignalR JavaScript client 11.0.0 or later and Azure SignalR SDK 1.34.0 or later.

Type the following commands to run this app.
```
```powershell
dotnet restore
dotnet user-secrets set Azure:SignalR:ConnectionString "<your connection string>"
$env:Azure__SignalR__ConnectionString = "<your connection string>"
dotnet run
```

## Quick Deploy via Docker image
You can also deploy this sample via existing docker image
## Run via Docker
Build the image from this sample directory:

```
docker build -t advancedchatroom .
docker run -e Azure__SignalR__ConnectionString="<signalr-connection-string>" \
-p 5000:80 mcr.microsoft.com/signalrsamples/advancedchatroom:latest
-p 5000:80 advancedchatroom
```

Open the broswer with url `localhost:5000`, you can see the sample just like Chat Sample but has more operations.
19 changes: 18 additions & 1 deletion samples/AdvancedChatRoom/Startup.cs
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Routing;
using Microsoft.IdentityModel.Tokens;
using Microsoft.IdentityModel.JsonWebTokens;

namespace Microsoft.Azure.SignalR.Samples.AdvancedChatRoom
{
Expand Down Expand Up @@ -53,6 +54,18 @@ public void ConfigureServices(IServiceCollection services)
ValidAudience = JwtController.Audience,
IssuerSigningKey = JwtController.SigningCreds.Key
};
option.Events = new JwtBearerEvents
{
OnTokenValidated = context =>
{
if (context.SecurityToken is JsonWebToken jwt)
{
context.Properties.ExpiresUtc = new DateTimeOffset(jwt.ValidTo, TimeSpan.Zero);
}

return Task.CompletedTask;
}
};
});

services.AddControllers();
Expand All @@ -75,7 +88,11 @@ public void Configure(IApplicationBuilder app)
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
endpoints.MapHub<ChatJwtSampleHub>("/chatjwt");
endpoints.MapHub<ChatJwtSampleHub>("/chatjwt", options =>
{
options.EnableAuthenticationRefresh = true;
options.CloseOnAuthenticationExpiration = true;
});
endpoints.MapHub<ChatCookieSampleHub>("/chatcookie");
});
}
Expand Down
71 changes: 61 additions & 10 deletions samples/AdvancedChatRoom/wwwroot/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -13,13 +13,18 @@
<h2 class="text-center" style="margin-top: 0; padding-top: 30px; padding-bottom: 30px;">Azure SignalR Group Chat</h2>

<div class="container" style="height: calc(100% - 110px);">
<div id="authinfo" hidden>
<div>Connection ID: <span id="connectionid"></span></div>
<div>App JWT expires at (UTC): <span id="jwtexpires"></span></div>
</div>
<div id="messages" style="background-color: whitesmoke; "></div>

<div class="input-prepend input-append" style="padding-bottom: 5px; padding-top: 5px;">
<input type="text" id="message" style="width: 50%; padding: 5px 10px;"
placeholder="Type message and press Enter to send...">
<button class="btn-success" id="echo">Echo</button>
<button class="btn-success" id="sendmessage">Broadcast</button>
<button class="btn-info" id="refreshauth" hidden disabled>Refresh Authentication</button>
</div>

<div class="input-prepend input-append" style="padding-bottom: 5px; padding-top: 5px;">
Expand Down Expand Up @@ -58,7 +63,7 @@ <h2 class="text-center" style="margin-top: 0; padding-top: 30px; padding-bottom:
</div>

<!--Reference the SignalR library. -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/microsoft-signalr/6.0.1/signalr.js"></script>
<script src="https://cdn.jsdelivr.net/npm/@microsoft/signalr@11.0.0/dist/browser/signalr.min.js"></script>

<!--Add script to update the page and send messages.-->
<script type="text/javascript">
Expand Down Expand Up @@ -261,6 +266,7 @@ <h2 class="text-center" style="margin-top: 0; padding-top: 30px; padding-bottom:
}

function onConnectionError(error) {
document.getElementById('refreshauth').disabled = true;
if (error && error.message) {
console.error(error.message);
}
Expand All @@ -269,22 +275,67 @@ <h2 class="text-center" style="margin-top: 0; padding-top: 30px; padding-bottom:
modal.style = 'display: block;';
}

var jwtToken = '';
var connection = new signalR.HubConnectionBuilder()
.withUrl(`/chat${authType}?username=${username}`,
var url = `/${authType}/login?username=${encodeURIComponent(username)}&role=${encodeURIComponent(role)}`;
var jwtExpiresAt;
function updateAuthenticationInfo() {
document.getElementById('connectionid').textContent = connection.connectionId;
document.getElementById('jwtexpires').textContent = jwtExpiresAt.toISOString();
document.getElementById('authinfo').hidden = false;
}

var connectionBuilder = new signalR.HubConnectionBuilder()
.withUrl(`/chat${authType}?username=${encodeURIComponent(username)}`,
{
accessTokenFactory: () => jwtToken
})
.build();
accessTokenFactory: authType === "jwt" ? async () => {
var token = await get(url);
var payload = JSON.parse(atob(token.split('.')[1].replace(/-/g, '+').replace(/_/g, '/')));
if (typeof payload.exp !== "number" || !Number.isFinite(payload.exp)) {
throw new Error("The application JWT is missing a valid expiration.");
}
jwtExpiresAt = new Date(payload.exp * 1000);
return token;
} : undefined
});

if (authType === "jwt") {
connectionBuilder.withAuthenticationRefresh();
}

var url = `/${authType}/login?username=${username}&role=${role}`;
get(url).then((token) => {
jwtToken = token;
var connection = connectionBuilder.build();
var refreshButton = document.getElementById('refreshauth');
if (authType === "jwt") {
refreshButton.hidden = false;
connection.onAuthenticationRefreshed(function () {
updateAuthenticationInfo();
appendMessage('_SYSTEM_', 'Authentication refreshed without reconnecting.');
});
connection.onAuthenticationRefreshFailed(function (context) {
console.error(context.error);
appendMessage('_SYSTEM_', 'Authentication refresh failed.');
});
refreshButton.addEventListener('click', async function () {
refreshButton.disabled = true;
try {
await connection.refreshAuthentication();
} catch (error) {
console.error(error);
} finally {
refreshButton.disabled = connection.state !== signalR.HubConnectionState.Connected;
}
});
}

var login = authType === "cookie" ? get(url) : Promise.resolve();
login.then(() => {
bindConnectionMessage(connection);
return connection.start();
})
.then(function () {
onConnected(connection);
if (authType === "jwt") {
updateAuthenticationInfo();
}
refreshButton.disabled = false;
})
.catch(function (error) {
if (error.message) {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.SignalR.Common;
using Microsoft.Azure.SignalR.Management;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;

namespace NegotiationServer.Controllers
{
Expand All @@ -16,12 +17,14 @@ public class NegotiateController : ControllerBase
private readonly ServiceHubContext _messageHubContext;
private readonly ServiceHubContext _chatHubContext;
private readonly bool _enableDetailedErrors;
private readonly ILogger<NegotiateController> _logger;

public NegotiateController(IHubContextStore store, IConfiguration configuration)
public NegotiateController(IHubContextStore store, IConfiguration configuration, ILogger<NegotiateController> logger)
{
_messageHubContext = store.MessageHubContext;
_chatHubContext = store.ChatHubContext;
_enableDetailedErrors = configuration.GetValue(EnableDetailedErrors, false);
_logger = logger;
}

[HttpPost("message/negotiate")]
Expand All @@ -37,24 +40,65 @@ public Task<ActionResult> ChatHubNegotiate(string user)
return NegotiateBase(user, _chatHubContext);
}

[HttpPost("message/refresh")]
public Task<ActionResult> MessageHubRefresh()
{
return RefreshBase(_messageHubContext);
}

[HttpPost("chat/refresh")]
public Task<ActionResult> ChatHubRefresh()
{
return RefreshBase(_chatHubContext);
}

private async Task<ActionResult> NegotiateBase(string user, ServiceHubContext serviceHubContext)
{
if (string.IsNullOrEmpty(user))
{
return BadRequest("User ID is null or empty.");
}

var negotiateResponse = await serviceHubContext.NegotiateAsync(new()
var negotiateResponse = await serviceHubContext.NegotiateWithTokenLifetimeAsync(new()
{
UserId = user,
EnableDetailedErrors = _enableDetailedErrors
});
}, HttpContext.RequestAborted);

return new JsonResult(new Dictionary<string, string>()
return new JsonResult(new
{
{ "url", negotiateResponse.Url },
{ "accessToken", negotiateResponse.AccessToken }
url = negotiateResponse.Url,
accessToken = negotiateResponse.AccessToken,
tokenLifetimeSeconds = negotiateResponse.TokenLifetimeSeconds
});
}

private async Task<ActionResult> RefreshBase(ServiceHubContext serviceHubContext)
{
var connectionToken = Request.Headers["X-SignalR-Connection-Token"].ToString();
if (string.IsNullOrEmpty(connectionToken))
{
return BadRequest(new { error = "missing_connection_token" });
}

try
{
var result = await serviceHubContext.RefreshConnectionAuthenticationAsync(
connectionToken,
new RefreshConnectionAuthenticationOptions(),
HttpContext.RequestAborted);

return new JsonResult(new
{
accessToken = result.AccessToken,
tokenLifetimeSeconds = result.TokenLifetimeSeconds
});
}
catch (AzureSignalRException ex)
{
_logger.LogError(ex, "Failed to refresh connection authentication.");
return StatusCode(500, new { error = "internal_server_error" });
}
}
}
}
19 changes: 19 additions & 0 deletions samples/Management/NegotiationServer/NegotiationController.http
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
@baseUrl = http://localhost:5000
@connectionToken = replace-with-live-connection-token

### Negotiate a Message connection
POST {{baseUrl}}/message/negotiate?user=alice

### Refresh the live Message connection
POST {{baseUrl}}/message/refresh
X-SignalR-Connection-Token: {{connectionToken}}

### Negotiate a Chat connection
POST {{baseUrl}}/chat/negotiate?user=alice

### Refresh the live Chat connection
POST {{baseUrl}}/chat/refresh
X-SignalR-Connection-Token: {{connectionToken}}

### Missing connection token returns HTTP 400
POST {{baseUrl}}/message/refresh
Loading