Skip to content

[Blazor] Add support for antiforgery #49108

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 10 commits into from
Jul 5, 2023
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
15 changes: 15 additions & 0 deletions src/Antiforgery/src/IAntiforgeryMetadata.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

namespace Microsoft.AspNetCore.Antiforgery.Infrastructure;

/// <summary>
/// A marker interface which can be used to identify antiforgery metadata.
/// </summary>
public interface IAntiforgeryMetadata
{
/// <summary>
/// Gets a value indicating whether the antiforgery token should be validated.
/// </summary>
bool Required { get; }
}
5 changes: 5 additions & 0 deletions src/Antiforgery/src/PublicAPI.Unshipped.txt
Original file line number Diff line number Diff line change
@@ -1 +1,6 @@
#nullable enable
Microsoft.AspNetCore.Antiforgery.Infrastructure.IAntiforgeryMetadata
Microsoft.AspNetCore.Antiforgery.Infrastructure.IAntiforgeryMetadata.Required.get -> bool
Microsoft.AspNetCore.Antiforgery.RequireAntiforgeryTokenAttribute
Microsoft.AspNetCore.Antiforgery.RequireAntiforgeryTokenAttribute.RequireAntiforgeryTokenAttribute(bool required = true) -> void
Microsoft.AspNetCore.Antiforgery.RequireAntiforgeryTokenAttribute.Required.get -> bool
23 changes: 23 additions & 0 deletions src/Antiforgery/src/RequireAntiforgeryTokenAttribute.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using Microsoft.AspNetCore.Antiforgery.Infrastructure;

namespace Microsoft.AspNetCore.Antiforgery;

/// <summary>
/// An attribute that can be used to indicate whether the antiforgery token must be validated.
/// </summary>
/// <param name="required">A value indicating whether the antiforgery token should be validated.</param>
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public class RequireAntiforgeryTokenAttribute(bool required = true) : Attribute, IAntiforgeryMetadata
{
/// <summary>
/// Gets or sets a value indicating whether the antiforgery token should be validated.
/// </summary>
/// <remarks>
/// Defaults to <see langword="true"/>; <see langword="false"/> indicates that
/// the validation check for the antiforgery token can be avoided.
/// </remarks>
public bool Required { get; } = required;
}
44 changes: 41 additions & 3 deletions src/Components/Components/src/Rendering/RenderTreeBuilder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -175,6 +175,11 @@ public void AddAttribute(int sequence, string name)
throw new InvalidOperationException($"Valueless attributes may only be added immediately after frames of type {RenderTreeFrameType.Element}");
}

if (TrackNamedEventHandlers && string.Equals(name, "@onsubmit:name", StringComparison.Ordinal))
{
_entries.AppendAttribute(sequence, name, "");
Copy link
Member

Choose a reason for hiding this comment

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

Is the idea that people would write <... @onsubmit:name> with no value?

Copy link
Member Author

Choose a reason for hiding this comment

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

You can do no value, but more commonly you would do @onsubmit:name="" which gets translated to true, which is what this code avoids. Once the directive for the razor compiler is in, this will just be SetEventHandlerName

}

_entries.AppendAttribute(sequence, name, BoxedTrue);
}

Expand Down Expand Up @@ -226,7 +231,14 @@ public void AddAttribute(int sequence, string name, string? value)
AssertCanAddAttribute();
if (value != null || _lastNonAttributeFrameType == RenderTreeFrameType.Component)
{
_entries.AppendAttribute(sequence, name, value);
if (TrackNamedEventHandlers && value != null && string.Equals(name, "@onsubmit:name", StringComparison.Ordinal))
{
SetEventHandlerName(value);
}
else
{
_entries.AppendAttribute(sequence, name, value);
}
}
else
{
Expand Down Expand Up @@ -371,6 +383,11 @@ public void AddAttribute(int sequence, string name, object? value)
{
if (boolValue)
{
if (TrackNamedEventHandlers && string.Equals(name, "@onsubmit:name", StringComparison.Ordinal))
{
_entries.AppendAttribute(sequence, name, value);
}

_entries.AppendAttribute(sequence, name, BoxedTrue);
}
else
Expand All @@ -396,8 +413,17 @@ public void AddAttribute(int sequence, string name, object? value)
}
else
{
// The value is either a string, or should be treated as a string.
_entries.AppendAttribute(sequence, name, value.ToString());
var valueAsString = value.ToString();
if (TrackNamedEventHandlers && valueAsString != null && string.Equals(name, "@onsubmit:name", StringComparison.Ordinal))
{
SetEventHandlerName(valueAsString);
}
else
{
// The value is either a string, or should be treated as a string.
_entries.AppendAttribute(sequence, name, valueAsString);
}

}
}
else if (_lastNonAttributeFrameType == RenderTreeFrameType.Component)
Expand Down Expand Up @@ -873,6 +899,18 @@ internal void ProcessDuplicateAttributes(int first)
// This attribute has been overridden. For now, blank out its name to *mark* it. We'll do a pass
// later to wipe it out.
frame = default;
// We are wiping out this frame, which means that if we are tracking named events, we have to adjust the
// indexes of the named event handlers that come after this frame.
if (_seenEventHandlerNames != null && _seenEventHandlerNames.Count > 0)
{
foreach (var (name, eventIndex) in _seenEventHandlerNames)
{
if (eventIndex >= i)
{
_seenEventHandlerNames[name] = eventIndex - 1;
}
}
}
}
else
{
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using Microsoft.AspNetCore.Antiforgery;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Components.Discovery;
using Microsoft.AspNetCore.Http;
Expand Down Expand Up @@ -30,6 +31,9 @@ internal void AddEndpoints(
RoutePatternFactory.Parse(pageDefinition.Route),
order: 0);

// Require antiforgery by default, let the page override it.
builder.Metadata.Add(new RequireAntiforgeryTokenAttribute());

// All attributes defined for the type are included as metadata.
foreach (var attribute in pageDefinition.Metadata)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
using Microsoft.AspNetCore.Components.Binding;
using Microsoft.AspNetCore.Components.Endpoints;
using Microsoft.AspNetCore.Components.Endpoints.DependencyInjection;
using Microsoft.AspNetCore.Components.Endpoints.Forms;
using Microsoft.AspNetCore.Components.Forms;
using Microsoft.AspNetCore.Components.Infrastructure;
using Microsoft.AspNetCore.Components.Routing;
Expand All @@ -30,6 +31,9 @@ public static class RazorComponentsServiceCollectionExtensions
[RequiresUnreferencedCode("Razor Components does not currently support native AOT.", Url = "https://aka.ms/aspnet/nativeaot")]
public static IRazorComponentsBuilder AddRazorComponents(this IServiceCollection services)
{
// Dependencies
services.AddAntiforgery();

services.TryAddSingleton<RazorComponentsMarkerService>();

// Results
Expand Down Expand Up @@ -60,7 +64,7 @@ public static IRazorComponentsBuilder AddRazorComponents(this IServiceCollection
services.TryAddScoped<IFormValueSupplier, DefaultFormValuesSupplier>();
services.TryAddEnumerable(ServiceDescriptor.Scoped<CascadingModelBindingProvider, CascadingQueryModelBindingProvider>());
services.TryAddEnumerable(ServiceDescriptor.Scoped<CascadingModelBindingProvider, CascadingFormModelBindingProvider>());

services.TryAddScoped<AntiforgeryStateProvider, EndpointAntiforgeryStateProvider>();
return new DefaultRazorComponentsBuilder(services);
}

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using Microsoft.AspNetCore.Antiforgery;
using Microsoft.AspNetCore.Components.Forms;
using Microsoft.AspNetCore.Http;

namespace Microsoft.AspNetCore.Components.Endpoints.Forms;

internal class EndpointAntiforgeryStateProvider(IAntiforgery antiforgery, PersistentComponentState state) : DefaultAntiforgeryStateProvider(state)
{
private HttpContext? _context;

internal void SetRequestContext(HttpContext context)
{
_context = context;
}

public override AntiforgeryRequestToken? GetAntiforgeryToken()
{
if (_context == null)
{
return null;
}

// We already have a callback setup to generate the token when the response starts if needed.
// If we need the tokens before we start streaming the response, we'll generate and store them;
// otherwise we'll just retrieve them.
// In case there are no tokens available, we are going to return null and no-op.
var tokens = !_context.Response.HasStarted ? antiforgery.GetAndStoreTokens(_context) : antiforgery.GetTokens(_context);
if (tokens.RequestToken is null)
{
return null;
}

return new AntiforgeryRequestToken(tokens.RequestToken, tokens.FormFieldName);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@
<Compile Include="$(RepoRoot)src\Shared\Components\ProtectedPrerenderComponentApplicationStore.cs" LinkBase="DependencyInjection" />
<Compile Include="$(RepoRoot)src\Shared\ClosedGenericMatcher\ClosedGenericMatcher.cs" LinkBase="Binding" />
<Compile Include="$(ComponentsSharedSourceRoot)src\CacheHeaderSettings.cs" Link="Shared\CacheHeaderSettings.cs" />
<Compile Include="$(ComponentsSharedSourceRoot)src\DefaultAntiforgeryStateProvider.cs" LinkBase="Forms" />

<Compile Include="$(SharedSourceRoot)PropertyHelper\**\*.cs" />

Expand All @@ -44,6 +45,7 @@
</ItemGroup>

<ItemGroup>
<Reference Include="Microsoft.AspNetCore.Antiforgery" />
<Reference Include="Microsoft.AspNetCore.Components.Authorization" />
<Reference Include="Microsoft.AspNetCore.Components.Web" />
<Reference Include="Microsoft.AspNetCore.DataProtection.Extensions" />
Expand Down
56 changes: 50 additions & 6 deletions src/Components/Endpoints/src/RazorComponentEndpointInvoker.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,12 @@
// The .NET Foundation licenses this file to you under the MIT license.

using System.Buffers;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Text;
using System.Text.Encodings.Web;
using Microsoft.AspNetCore.Antiforgery;
using Microsoft.AspNetCore.Antiforgery.Infrastructure;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.WebUtilities;
using Microsoft.Extensions.DependencyInjection;
Expand Down Expand Up @@ -36,13 +39,27 @@ private async Task RenderComponentCore()
_context.Response.ContentType = RazorComponentResultExecutor.DefaultContentType;
_renderer.InitializeStreamingRenderingFraming(_context);

if (!await TryValidateRequestAsync(out var isPost, out var handler))
// Metadata controls whether we require antiforgery protection for this endpoint or we should skip it.
// The default for razor component endpoints is to require the metadata, but it can be overriden by
// the developer.
var antiforgeryMetadata = _context.GetEndpoint()!.Metadata.GetMetadata<IAntiforgeryMetadata>();
var antiforgery = _context.RequestServices.GetRequiredService<IAntiforgery>();
var (valid, isPost, handler) = await ValidateRequestAsync(antiforgeryMetadata?.Required == true ? antiforgery : null);
if (!valid)
{
// If the request is not valid we've already set the response to a 400 or similar
// and we can just exit early.
return;
}

_context.Response.OnStarting(() =>
{
// Generate the antiforgery tokens before we start streaming the response, as it needs
// to set the cookie header.
antiforgery!.GetAndStoreTokens(_context);
return Task.CompletedTask;
});

await EndpointHtmlRenderer.InitializeStandardComponentServicesAsync(
_context,
componentType: _componentType,
Expand Down Expand Up @@ -89,16 +106,21 @@ await EndpointHtmlRenderer.InitializeStandardComponentServicesAsync(
await writer.FlushAsync();
}

private Task<bool> TryValidateRequestAsync(out bool isPost, out string? handler)
private async Task<RequestValidationState> ValidateRequestAsync(IAntiforgery? antiforgery)
{
handler = null;
isPost = HttpMethods.IsPost(_context.Request.Method);
var isPost = HttpMethods.IsPost(_context.Request.Method);
if (isPost)
{
return Task.FromResult(TrySetFormHandler(out handler));
var valid = antiforgery == null || await antiforgery.IsRequestValidAsync(_context);
if (!valid)
{
_context.Response.StatusCode = StatusCodes.Status400BadRequest;
}
var formValid = TrySetFormHandler(out var handler);
return new(valid && formValid, isPost, handler);
}

return Task.FromResult(true);
return new(true, false, null);
}

private bool TrySetFormHandler([NotNullWhen(true)] out string? handler)
Expand Down Expand Up @@ -128,4 +150,26 @@ private static TextWriter CreateResponseWriter(Stream bodyStream)
const int DefaultBufferSize = 16 * 1024;
return new HttpResponseStreamWriter(bodyStream, Encoding.UTF8, DefaultBufferSize, ArrayPool<byte>.Shared, ArrayPool<char>.Shared);
}

[DebuggerDisplay($"{{{nameof(GetDebuggerDisplay)}(),nq}}")]
private readonly struct RequestValidationState(bool isValid, bool isPost, string? handlerName)
{
public bool IsValid => isValid;

public bool IsPost => isPost;

public string? HandlerName => handlerName;

private string GetDebuggerDisplay()
{
return $"{nameof(RequestValidationState)}: {IsValid} {IsPost} {HandlerName}";
}

public void Deconstruct(out bool isValid, out bool isPost, out string? handlerName)
{
isValid = IsValid;
isPost = IsPost;
handlerName = HandlerName;
}
}
}
14 changes: 10 additions & 4 deletions src/Components/Endpoints/src/Rendering/EndpointHtmlRenderer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
using System.Text;
using Microsoft.AspNetCore.Components.Authorization;
using Microsoft.AspNetCore.Components.Endpoints.DependencyInjection;
using Microsoft.AspNetCore.Components.Endpoints.Forms;
using Microsoft.AspNetCore.Components.Forms;
using Microsoft.AspNetCore.Components.HtmlRendering.Infrastructure;
using Microsoft.AspNetCore.Components.Infrastructure;
Expand Down Expand Up @@ -75,19 +76,24 @@ internal static async Task InitializeStandardComponentServicesAsync(
var navigationManager = (IHostEnvironmentNavigationManager)httpContext.RequestServices.GetRequiredService<NavigationManager>();
navigationManager?.Initialize(GetContextBaseUri(httpContext.Request), GetFullUri(httpContext.Request));

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

var formData = httpContext.RequestServices.GetRequiredService<FormDataProvider>() as IHostEnvironmentFormDataProvider;
if (handler != null && form != null && formData != null)
if (handler != null &&
form != null &&
httpContext.RequestServices.GetRequiredService<FormDataProvider>() is IHostEnvironmentFormDataProvider formData)
{
formData.SetFormData(handler, new FormCollectionReadOnlyDictionary(form));
}

if (httpContext.RequestServices.GetService<AntiforgeryStateProvider>() is EndpointAntiforgeryStateProvider antiforgery)
{
antiforgery.SetRequestContext(httpContext);
}

// It's important that this is initialized since a component might try to restore state during prerendering
// (which will obviously not work, but should not fail)
var componentApplicationLifetime = httpContext.RequestServices.GetRequiredService<ComponentStatePersistenceManager>();
Expand Down
6 changes: 6 additions & 0 deletions src/Components/Endpoints/test/EndpointHtmlRendererTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
using System.Text.Encodings.Web;
using System.Text.Json;
using System.Text.RegularExpressions;
using Microsoft.AspNetCore.Components.Endpoints.Forms;
using Microsoft.AspNetCore.Components.Endpoints.Tests.TestComponents;
using Microsoft.AspNetCore.Components.Forms;
using Microsoft.AspNetCore.Components.Infrastructure;
Expand Down Expand Up @@ -1297,6 +1298,11 @@ private static ServiceCollection CreateDefaultServiceCollection()
services.AddSingleton(sp => sp.GetRequiredService<ComponentStatePersistenceManager>().State);
services.AddSingleton<ServerComponentSerializer>();
services.AddSingleton<FormDataProvider, HttpContextFormDataProvider>();
services.AddAntiforgery();
services.AddSingleton<ComponentStatePersistenceManager>();
services.AddSingleton<PersistentComponentState>(sp => sp.GetRequiredService<ComponentStatePersistenceManager>().State);
services.AddSingleton<AntiforgeryStateProvider, EndpointAntiforgeryStateProvider>();

return services;
}

Expand Down
Loading