File: RequireAntiforgeryTokenAttribute.cs
Web Access
Project: src\aspnetcore\src\Antiforgery\src\Microsoft.AspNetCore.Antiforgery.csproj (Microsoft.AspNetCore.Antiforgery)
// 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.Builder;
using Microsoft.AspNetCore.Http;

namespace Microsoft.AspNetCore.Antiforgery;

/// <summary>
/// An attribute that can be used to indicate whether the antiforgery token must be validated.
/// </summary>
/// <remarks>
/// <para>
/// Validation performed by <see cref="AntiforgeryApplicationBuilderExtensions.UseAntiforgery(IApplicationBuilder)"/>
/// only applies to HTTP POST, PUT, and PATCH requests. Endpoints using other HTTP methods are skipped by the
/// middleware even when this attribute is applied.
/// </para>
/// <para>
/// If you need validation for other HTTP methods, resolve <see cref="IAntiforgery"/> and call
/// <see cref="IAntiforgery.ValidateRequestAsync(HttpContext)"/> or
/// <see cref="IAntiforgery.IsRequestValidAsync(HttpContext)"/> in your handler.
/// </para>
/// </remarks>
/// <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 RequiresValidation { get; } = required;
}