Skip to content

Make static prerendering support auth. Fixes #11799 #12318

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 5 commits into from
Jul 19, 2019
Merged
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
Original file line number Diff line number Diff line change
Expand Up @@ -359,6 +359,10 @@ public partial interface IHandleEvent
{
System.Threading.Tasks.Task HandleEventAsync(Microsoft.AspNetCore.Components.EventCallbackWorkItem item, object arg);
}
public partial interface IHostEnvironmentAuthenticationStateProvider
{
void SetAuthenticationState(System.Threading.Tasks.Task<Microsoft.AspNetCore.Components.AuthenticationState> authenticationStateTask);
}
[System.AttributeUsageAttribute(System.AttributeTargets.Property, AllowMultiple=false, Inherited=true)]
public sealed partial class InjectAttribute : System.Attribute
{
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.

using System.Threading.Tasks;

namespace Microsoft.AspNetCore.Components
{
/// <summary>
/// An interface implemented by <see cref="AuthenticationStateProvider"/> classes that can receive authentication
/// state information from the host environment.
/// </summary>
public interface IHostEnvironmentAuthenticationStateProvider
{
/// <summary>
/// Supplies updated authentication state data to the <see cref="AuthenticationStateProvider"/>.
/// </summary>
/// <param name="authenticationStateTask">A task that resolves with the updated <see cref="AuthenticationState"/>.</param>
void SetAuthenticationState(Task<AuthenticationState> authenticationStateTask);
}
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm not super sure what this is needed, but the name immediately threw me off path, its too similar to IHostingEnvironment.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could we instead, have an HttpContextAuthenticationStateProvider in MVC, and have the FixedAuthenticationStateProvider contain this extra method that you can call during reconnection?

That way we don't have to carry around an additional interface.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That doesn't work, because StaticComponentRenderer still has to initialize whatever AuthenticationStateProvider you have in DI. If the one you have there is a FixedAuthenticationStateProvider, it wouldn't be able to invoke any methods on it, because it lives in an assembly not referenced from ViewFeatures.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What do you think about adding it to the base class instead?

Copy link
Member Author

@SteveSandersonMS SteveSandersonMS Jul 18, 2019

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's not applicable in general because, say, in client-side Blazor there's no host environment that can tell you what the authentication state is. The AuthenticationStateProvider concept is about providing the authentication state, not receiving it from someone else.

I don't mind renaming IHostEnvironmentAuthenticationStateProvider to something else if you prefer.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We don't want MVC referencing signalr.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We don't want MVC referencing signalr.

Ah yes, now I remember.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah, but this is not about the interface name, its about the functionality. the ABC can simply have a
SetAuthenticationState you can use to set the authstate and that way you don't have to implement your own.

It is about the functionality, yes. Setting the state has no place on the base contract as it’s not a concept that exists generally (at all, not just multiple times). That’s why I’m avoiding putting it there.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@javiercn Do you have any further concerns about this?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No, I think we have a different trade-off balance, so I leave it to your better judgement.

}
10 changes: 7 additions & 3 deletions src/Components/Server/src/Circuits/DefaultCircuitFactory.cs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.JSInterop;
using System.Threading.Tasks;

namespace Microsoft.AspNetCore.Components.Server.Circuits
{
Expand Down Expand Up @@ -50,9 +51,12 @@ public override CircuitHost CreateCircuitHost(
jsRuntime.Initialize(client);
componentContext.Initialize(client);

// You can replace the AuthenticationStateProvider with a custom one, but in that case initialization is up to you
var authenticationStateProvider = scope.ServiceProvider.GetService<AuthenticationStateProvider>();
(authenticationStateProvider as FixedAuthenticationStateProvider)?.Initialize(httpContext.User);
var authenticationStateProvider = scope.ServiceProvider.GetService<AuthenticationStateProvider>() as IHostEnvironmentAuthenticationStateProvider;
if (authenticationStateProvider != null)
{
var authenticationState = new AuthenticationState(httpContext.User); // TODO: Get this from the hub connection context instead
authenticationStateProvider.SetAuthenticationState(Task.FromResult(authenticationState));
}

var uriHelper = (RemoteUriHelper)scope.ServiceProvider.GetRequiredService<IUriHelper>();
var navigationInterception = (RemoteNavigationInterception)scope.ServiceProvider.GetRequiredService<INavigationInterception>();
Expand Down

This file was deleted.

Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.

using System;
using System.Threading.Tasks;

namespace Microsoft.AspNetCore.Components.Server.Circuits
{
/// <summary>
/// An <see cref="AuthenticationStateProvider"/> intended for use in server-side Blazor.
/// </summary>
internal class ServerAuthenticationStateProvider : AuthenticationStateProvider, IHostEnvironmentAuthenticationStateProvider
{
private Task<AuthenticationState> _authenticationStateTask;

public override Task<AuthenticationState> GetAuthenticationStateAsync()
=> _authenticationStateTask
?? throw new InvalidOperationException($"{nameof(GetAuthenticationStateAsync)} was called before {nameof(SetAuthenticationState)}.");

public void SetAuthenticationState(Task<AuthenticationState> authenticationStateTask)
{
_authenticationStateTask = authenticationStateTask ?? throw new ArgumentNullException(nameof(authenticationStateTask));
NotifyAuthenticationStateChanged(_authenticationStateTask);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ public static IServerSideBlazorBuilder AddServerSideBlazor(this IServiceCollecti
services.AddScoped<IJSRuntime, RemoteJSRuntime>();
services.AddScoped<INavigationInterception, RemoteNavigationInterception>();
services.AddScoped<IComponentContext, RemoteComponentContext>();
services.AddScoped<AuthenticationStateProvider, FixedAuthenticationStateProvider>();
services.AddScoped<AuthenticationStateProvider, ServerAuthenticationStateProvider>();

services.TryAddEnumerable(ServiceDescriptor.Singleton<IConfigureOptions<CircuitOptions>, CircuitOptionsJSInteropDetailedErrorsConfiguration>());

Expand Down

This file was deleted.

Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.

using System;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Components.Server.Circuits;
using Xunit;

namespace Microsoft.AspNetCore.Components.Server.Tests.Circuits
{
public class ServerAuthenticationStateProviderTest
{
[Fact]
public async Task CannotProvideAuthenticationStateBeforeInitialization()
{
await Assert.ThrowsAsync<InvalidOperationException>(() =>
new ServerAuthenticationStateProvider()
.GetAuthenticationStateAsync());
}

[Fact]
public async Task SuppliesAuthenticationStateWithFixedUser()
{
// Arrange
var user = new ClaimsPrincipal();
var provider = new ServerAuthenticationStateProvider();

// Act 1
var expectedAuthenticationState1 = new AuthenticationState(user);
provider.SetAuthenticationState(Task.FromResult(expectedAuthenticationState1));

// Assert 1
var actualAuthenticationState1 = await provider.GetAuthenticationStateAsync();
Assert.NotNull(actualAuthenticationState1);
Assert.Same(expectedAuthenticationState1, actualAuthenticationState1);

// Act 2: Show we can update it further
var expectedAuthenticationState2 = new AuthenticationState(user);
provider.SetAuthenticationState(Task.FromResult(expectedAuthenticationState2));

// Assert 2
var actualAuthenticationState2 = await provider.GetAuthenticationStateAsync();
Assert.NotNull(actualAuthenticationState2);
Assert.NotSame(actualAuthenticationState1, actualAuthenticationState2);
Assert.Same(expectedAuthenticationState2, actualAuthenticationState2);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,18 +2,20 @@
@using Microsoft.AspNetCore.Components
@inject IComponentContext ComponentContext

<h1>Hello</h1>
<CascadingAuthenticationState>
<h1>Hello</h1>

<p>
Current state:
<strong id="connected-state">@(ComponentContext.IsConnected ? "connected" : "not connected")</strong>
</p>
<p>
Current state:
<strong id="connected-state">@(ComponentContext.IsConnected ? "connected" : "not connected")</strong>
</p>

<p>
Clicks:
<strong id="count">@count</strong>
<button id="increment-count" @onclick="@(() => count++)">Click me</button>
</p>
<p>
Clicks:
<strong id="count">@count</strong>
<button id="increment-count" @onclick="@(() => count++)">Click me</button>
</p>
</CascadingAuthenticationState>

@code {
int count;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
<base href="~/" />
</head>
<body>
<app>@(await Html.RenderComponentAsync<TestRouter>())</app>
<app>@(await Html.RenderStaticComponentAsync<TestRouter>())</app>

@*
So that E2E tests can make assertions about both the prerendered and
Expand All @@ -19,17 +19,17 @@

<script src="_framework/blazor.server.js" autostart="false"></script>
<script>
// Used by InteropOnInitializationComponent
function setElementValue(element, newValue) {
element.value = newValue;
return element.value;
}
// Used by InteropOnInitializationComponent
function setElementValue(element, newValue) {
element.value = newValue;
return element.value;
}

function start() {
Blazor.start({
logLevel: 1 // LogLevel.Debug
});
}
function start() {
Blazor.start({
logLevel: 1 // LogLevel.Debug
});
}
</script>
</body>
</html>
3 changes: 2 additions & 1 deletion src/Components/test/testassets/TestServer/Startup.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
using System.Threading.Tasks;
using BasicTestApp;
using BasicTestApp.RouterTest;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
Expand Down Expand Up @@ -96,7 +97,7 @@ public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
app.UseEndpoints(endpoints =>
{
endpoints.MapFallbackToPage("/PrerenderedHost");
endpoints.MapBlazorHub();
endpoints.MapBlazorHub<TestRouter>(selector: "app");
});
});

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ public async Task<IEnumerable<string>> PrerenderComponentAsync(
HttpContext httpContext,
Type componentType)
{
InitializeUriHelper(httpContext);
InitializeStandardComponentServices(httpContext);
var loggerFactory = (ILoggerFactory)httpContext.RequestServices.GetService(typeof (ILoggerFactory));
using (var htmlRenderer = new HtmlRenderer(httpContext.RequestServices, loggerFactory, _encoder.Encode))
{
Expand Down Expand Up @@ -62,15 +62,21 @@ public async Task<IEnumerable<string>> PrerenderComponentAsync(
}
}

private void InitializeUriHelper(HttpContext httpContext)
private void InitializeStandardComponentServices(HttpContext httpContext)
{
// We don't know here if we are dealing with the default HttpUriHelper registered
// by MVC or with the RemoteUriHelper registered by AddComponents.
// This might not be the first component in the request we are rendering, so
// we need to check if we already initialized the uri helper in this request.
// we need to check if we already initialized the services in this request.
if (!_initialized)
{
_initialized = true;

var authenticationStateProvider = httpContext.RequestServices.GetService<AuthenticationStateProvider>() as IHostEnvironmentAuthenticationStateProvider;
if (authenticationStateProvider != null)
{
var authenticationState = new AuthenticationState(httpContext.User);
authenticationStateProvider.SetAuthenticationState(Task.FromResult(authenticationState));
}

var helper = (UriHelperBase)httpContext.RequestServices.GetRequiredService<IUriHelper>();
helper.InitializeState(GetFullUri(httpContext.Request), GetContextBaseUri(httpContext.Request));
}
Expand Down