Skip to content
Merged
Changes from 5 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
66 changes: 66 additions & 0 deletions aspnetcore/blazor/fundamentals/signalr.md
Original file line number Diff line number Diff line change
Expand Up @@ -1511,6 +1511,72 @@ app.MapBlazorHub();

[!INCLUDE[](~/blazor/security/includes/httpcontext.md)]

## Impersonation for Windows Authentication

Authenticated hub connections (<xref:Microsoft.AspNetCore.SignalR.Client.HubConnection>) are created with <xref:Microsoft.AspNetCore.Http.Connections.Client.HttpConnectionOptions.UseDefaultCredentials%2A> to indicate the use of default credentials for HTTP requests:

```csharp
protected override async Task OnInitializedAsync()
{
hubConnection = new HubConnectionBuilder()
.WithUrl(NavigationManager.ToAbsoluteUri("/hub"), config =>
{
config.UseDefaultCredentials = true;
})
.WithAutomaticReconnect()
.Build();

hubConnection.On<string>("name", userName =>
{
name = userName;
InvokeAsync(StateHasChanged);
});

await hubConnection.StartAsync();
}
```

For more information, see <xref:signalr/authn-and-authz#windows-authentication>.

The preceding code is sufficient when the app is running in IIS Express as the signed-in user under Windows Authentication, which is likely the user's personal or work account.

When the app is published to IIS, the app runs under the *Application Pool Identity*. The hub connects as the IIS "user" account hosting the app, not the user accessing the page.

Implement *impersonation* with the hub to use the identity of the browsing user.

In the following example:

* The user from the authentication state provider is cast to a <xref:System.Security.Principal.WindowsIdentity>.
* The identity's access token is passed to <xref:System.Security.Principal.WindowsIdentity.RunImpersonatedAsync%2A?displayProperty=nameWithType> with the code that builds and starts the hub.

```csharp
protected override async Task OnInitializedAsync()
{
var user = (WindowsIdentity)
(await AuthenticationStateProvider.GetAuthenticationStateAsync())
.User.Identity;

await WindowsIdentity.RunImpersonatedAsync(user.AccessToken, async () =>
{
hubConnection = new HubConnectionBuilder()
.WithUrl(NavigationManager.ToAbsoluteUri("/hub"), config =>
{
config.UseDefaultCredentials = true;
})
.WithAutomaticReconnect()
.Build();

hubConnection.On<string>("name", userName =>
{
name = userName;
InvokeAsync(StateHasChanged);
});

await hubConnection.StartAsync();
});
}
```

## Additional server-side resources

* [Server-side host and deployment guidance: SignalR configuration](xref:blazor/host-and-deploy/server#signalr-configuration)
Expand Down