Replace the ConfigureCookieOptions action property with the CookieBuilder

This commit is contained in:
Nate McMaster 2017-06-29 15:49:13 -07:00
parent cfe0e3012e
commit df41fd8ccc
9 changed files with 220 additions and 219 deletions

View File

@ -14,81 +14,45 @@ namespace Microsoft.AspNetCore.Antiforgery
private const string AntiforgeryTokenFieldName = "__RequestVerificationToken";
private const string AntiforgeryTokenHeaderName = "RequestVerificationToken";
private string _cookieName;
private string _formFieldName = AntiforgeryTokenFieldName;
private CookieBuilder _cookieBuilder = new CookieBuilder
{
SameSite = SameSiteMode.Strict,
HttpOnly = true
};
/// <summary>
/// The default cookie prefix, which is ".AspNetCore.Antiforgery.".
/// </summary>
public static readonly string DefaultCookiePrefix = ".AspNetCore.Antiforgery.";
/// <summary>
/// Specifies the name of the cookie that is used by the antiforgery system.
/// Determines the settings used to create the antiforgery cookies.
/// </summary>
/// <remarks>
/// If an explicit name is not provided, the system will automatically generate a
/// <para>
/// If an explicit <see cref="CookieBuilder.Name"/> is not provided, the system will automatically generate a
/// unique name that begins with <see cref="DefaultCookiePrefix"/>.
/// </para>
/// <para>
/// <see cref="CookieBuilder.SameSite"/> defaults to <see cref="SameSiteMode.Strict"/>.
/// <see cref="CookieBuilder.HttpOnly"/> defaults to <c>true</c>.
/// </para>
/// </remarks>
public string CookieName
public CookieBuilder Cookie
{
get
{
return _cookieName;
}
set
{
if (value == null)
{
throw new ArgumentNullException(nameof(value));
}
_cookieName = value;
}
get => _cookieBuilder;
set => _cookieBuilder = value ?? throw new ArgumentNullException(nameof(value));
}
/// <summary>
/// This is obsolete and will be removed in a future version.
/// The recommended alternative is to use ConfigureCookieOptions.
/// The path set on the cookie. If set to <c>null</c>, the "path" attribute on the cookie is set to the current
/// request's <see cref="HttpRequest.PathBase"/> value. If the value of <see cref="HttpRequest.PathBase"/> is
/// <c>null</c> or empty, then the "path" attribute is set to the value of <see cref="CookieOptions.Path"/>.
/// </summary>
[Obsolete("This is obsolete and will be removed in a future version. The recommended alternative is to use ConfigureCookieOptions.")]
public PathString? CookiePath { get; set; }
/// <summary>
/// This is obsolete and will be removed in a future version.
/// The recommended alternative is to use ConfigureCookieOptions.
/// The domain set on the cookie. By default its <c>null</c> which results in the "domain" attribute not being set.
/// </summary>
[Obsolete("This is obsolete and will be removed in a future version. The recommended alternative is to use ConfigureCookieOptions.")]
public string CookieDomain { get; set; }
/// <summary>
/// Configures the <see cref="CookieOptions"/> of the antiforgery cookies. Without additional configuration, the
/// default values antiforgery cookie options are true for <see cref="CookieOptions.HttpOnly"/>, null for
/// <see cref="CookieOptions.Domain"/> and <see cref="SameSiteMode.Strict"/> for <see cref="CookieOptions.SameSite"/>.
/// </summary>
public Action<HttpContext, CookieOptions> ConfigureCookieOptions { get; set; }
/// <summary>
/// Specifies the name of the antiforgery token field that is used by the antiforgery system.
/// </summary>
public string FormFieldName
{
get
{
return _formFieldName;
}
set
{
if (value == null)
{
throw new ArgumentNullException(nameof(value));
}
_formFieldName = value;
}
get => _formFieldName;
set => _formFieldName = value ?? throw new ArgumentNullException(nameof(value));
}
/// <summary>
@ -97,13 +61,6 @@ namespace Microsoft.AspNetCore.Antiforgery
/// </summary>
public string HeaderName { get; set; } = AntiforgeryTokenHeaderName;
/// <summary>
/// Specifies whether SSL is required for the antiforgery system
/// to operate. If this setting is 'true' and a non-SSL request
/// comes into the system, all antiforgery APIs will fail.
/// </summary>
public bool RequireSsl { get; set; }
/// <summary>
/// Specifies whether to suppress the generation of X-Frame-Options header
/// which is used to prevent ClickJacking. By default, the X-Frame-Options
@ -111,5 +68,69 @@ namespace Microsoft.AspNetCore.Antiforgery
/// the X-Frame-Options header will not be generated for the response.
/// </summary>
public bool SuppressXFrameOptionsHeader { get; set; }
#region Obsolete API
/// <summary>
/// <para>
/// This property is obsolete and will be removed in a future version. The recommended alternative is <seealso cref="CookieBuilder.Name"/> on <see cref="Cookie"/>.
/// </para>
/// <para>
/// Specifies the name of the cookie that is used by the antiforgery system.
/// </para>
/// </summary>
/// <remarks>
/// If an explicit name is not provided, the system will automatically generate a
/// unique name that begins with <see cref="DefaultCookiePrefix"/>.
/// </remarks>
[Obsolete("This property is obsolete and will be removed in a future version. The recommended alternative is " + nameof(Cookie) + "." + nameof(CookieBuilder.Name) + ".")]
public string CookieName { get => Cookie.Name; set => Cookie.Name = value; }
/// <summary>
/// <para>
/// This property is obsolete and will be removed in a future version. The recommended alternative is <seealso cref="CookieBuilder.Path"/> on <see cref="Cookie"/>.
/// </para>
/// <para>
/// The path set on the cookie. If set to <c>null</c>, the "path" attribute on the cookie is set to the current
/// request's <see cref="HttpRequest.PathBase"/> value. If the value of <see cref="HttpRequest.PathBase"/> is
/// <c>null</c> or empty, then the "path" attribute is set to the value of <see cref="CookieOptions.Path"/>.
/// </para>
/// </summary>
[Obsolete("This property is obsolete and will be removed in a future version. The recommended alternative is " + nameof(Cookie) + "." + nameof(CookieBuilder.Path) + ".")]
public PathString? CookiePath { get => Cookie.Path; set => Cookie.Path = value; }
/// <summary>
/// <para>
/// This property is obsolete and will be removed in a future version. The recommended alternative is <seealso cref="CookieBuilder.Domain"/> on <see cref="Cookie"/>.
/// </para>
/// <para>
/// The domain set on the cookie. By default its <c>null</c> which results in the "domain" attribute not being set.
/// </para>
/// </summary>
[Obsolete("This property is obsolete and will be removed in a future version. The recommended alternative is " + nameof(Cookie) + "." + nameof(CookieBuilder.Domain) + ".")]
public string CookieDomain { get => Cookie.Domain; set => Cookie.Domain = value; }
/// <summary>
/// <para>
/// This property is obsolete and will be removed in a future version.
/// The recommended alternative is to set <seealso cref="CookieBuilder.SecurePolicy"/> on <see cref="Cookie"/>.
/// </para>
/// <para>
/// <c>true</c> is equivalent to <see cref="CookieSecurePolicy.Always"/>.
/// <c>false</c> is equivalent to <see cref="CookieSecurePolicy.None"/>.
/// </para>
/// <para>
/// Specifies whether SSL is required for the antiforgery system
/// to operate. If this setting is 'true' and a non-SSL request
/// comes into the system, all antiforgery APIs will fail.
/// </para>
/// </summary>
[Obsolete("This property is obsolete and will be removed in a future version. The recommended alternative is to set " + nameof(Cookie) + "." + nameof(CookieBuilder.SecurePolicy) + ".")]
public bool RequireSsl
{
get => Cookie.SecurePolicy == CookieSecurePolicy.Always;
set => Cookie.SecurePolicy = value ? CookieSecurePolicy.Always : CookieSecurePolicy.None;
}
#endregion
}
}
}

View File

@ -18,10 +18,10 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal
public static void ConfigureOptions(AntiforgeryOptions options, DataProtectionOptions dataProtectionOptions)
{
if (options.CookieName == null)
if (options.Cookie.Name == null)
{
var applicationId = dataProtectionOptions.ApplicationDiscriminator ?? string.Empty;
options.CookieName = AntiforgeryOptions.DefaultCookiePrefix + ComputeCookieName(applicationId);
options.Cookie.Name = AntiforgeryOptions.DefaultCookiePrefix + ComputeCookieName(applicationId);
}
}

View File

@ -111,7 +111,7 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal
var tokens = await _tokenStore.GetRequestTokensAsync(httpContext);
if (tokens.CookieToken == null)
{
_logger.MissingCookieToken(_options.CookieName);
_logger.MissingCookieToken(_options.Cookie.Name);
return false;
}
@ -160,7 +160,7 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal
if (tokens.CookieToken == null)
{
throw new AntiforgeryValidationException(
Resources.FormatAntiforgery_CookieToken_MustBeProvided(_options.CookieName));
Resources.FormatAntiforgery_CookieToken_MustBeProvided(_options.Cookie.Name));
}
if (tokens.RequestToken == null)
@ -265,12 +265,11 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal
private void CheckSSLConfig(HttpContext context)
{
if (_options.RequireSsl && !context.Request.IsHttps)
if (_options.Cookie.SecurePolicy == CookieSecurePolicy.Always && !context.Request.IsHttps)
{
throw new InvalidOperationException(Resources.FormatAntiforgeryWorker_RequireSSL(
nameof(AntiforgeryOptions),
nameof(AntiforgeryOptions.RequireSsl),
"true"));
throw new InvalidOperationException(Resources.FormatAntiforgery_RequiresSSL(
string.Join(".", nameof(AntiforgeryOptions), nameof(AntiforgeryOptions.Cookie), nameof(CookieBuilder.SecurePolicy)),
nameof(CookieSecurePolicy.Always)));
}
}

View File

@ -28,7 +28,7 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal
{
Debug.Assert(httpContext != null);
var requestCookie = httpContext.Request.Cookies[_options.CookieName];
var requestCookie = httpContext.Request.Cookies[_options.Cookie.Name];
if (string.IsNullOrEmpty(requestCookie))
{
// unable to find the cookie.
@ -42,7 +42,7 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal
{
Debug.Assert(httpContext != null);
var cookieToken = httpContext.Request.Cookies[_options.CookieName];
var cookieToken = httpContext.Request.Cookies[_options.Cookie.Name];
// We want to delay reading the form as much as possible, for example in case of large file uploads,
// request token could be part of the header.
@ -69,22 +69,12 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal
Debug.Assert(httpContext != null);
Debug.Assert(token != null);
var options = new CookieOptions
{
HttpOnly = true,
#pragma warning disable 618
Domain = _options.CookieDomain,
#pragma warning restore 618
SameSite = SameSiteMode.Strict,
Secure = _options.RequireSsl
};
var options = _options.Cookie.Build(httpContext);
#pragma warning disable 618
if (_options.CookiePath != null)
if (_options.Cookie.Path != null)
{
options.Path = _options.CookiePath.ToString();
options.Path = _options.Cookie.Path.ToString();
}
#pragma warning restore 618
else
{
var pathBase = httpContext.Request.PathBase.ToString();
@ -94,9 +84,7 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal
}
}
_options.ConfigureCookieOptions?.Invoke(httpContext, options);
httpContext.Response.Cookies.Append(_options.CookieName, token, options);
httpContext.Response.Cookies.Append(_options.Cookie.Name, token, options);
}
}
}

View File

@ -15,248 +15,224 @@ namespace Microsoft.AspNetCore.Antiforgery
/// </summary>
internal static string AntiforgeryTokenValidator_AuthenticatedUserWithoutUsername
{
get { return GetString("AntiforgeryTokenValidator_AuthenticatedUserWithoutUsername"); }
get => GetString("AntiforgeryTokenValidator_AuthenticatedUserWithoutUsername");
}
/// <summary>
/// The provided identity of type '{0}' is marked {1} = {2} but does not have a value for {3}. By default, the antiforgery system requires that all authenticated identities have a unique {3}. If it is not possible to provide a unique {3} for this identity, consider extending {4} by overriding the {5} or a custom type that can provide some form of unique identifier for the current user.
/// </summary>
internal static string FormatAntiforgeryTokenValidator_AuthenticatedUserWithoutUsername(object p0, object p1, object p2, object p3, object p4, object p5)
{
return string.Format(CultureInfo.CurrentCulture, GetString("AntiforgeryTokenValidator_AuthenticatedUserWithoutUsername"), p0, p1, p2, p3, p4, p5);
}
=> string.Format(CultureInfo.CurrentCulture, GetString("AntiforgeryTokenValidator_AuthenticatedUserWithoutUsername"), p0, p1, p2, p3, p4, p5);
/// <summary>
/// The provided antiforgery token failed a custom data check.
/// </summary>
internal static string AntiforgeryToken_AdditionalDataCheckFailed
{
get { return GetString("AntiforgeryToken_AdditionalDataCheckFailed"); }
get => GetString("AntiforgeryToken_AdditionalDataCheckFailed");
}
/// <summary>
/// The provided antiforgery token failed a custom data check.
/// </summary>
internal static string FormatAntiforgeryToken_AdditionalDataCheckFailed()
{
return GetString("AntiforgeryToken_AdditionalDataCheckFailed");
}
=> GetString("AntiforgeryToken_AdditionalDataCheckFailed");
/// <summary>
/// The provided antiforgery token was meant for a different claims-based user than the current user.
/// </summary>
internal static string AntiforgeryToken_ClaimUidMismatch
{
get { return GetString("AntiforgeryToken_ClaimUidMismatch"); }
get => GetString("AntiforgeryToken_ClaimUidMismatch");
}
/// <summary>
/// The provided antiforgery token was meant for a different claims-based user than the current user.
/// </summary>
internal static string FormatAntiforgeryToken_ClaimUidMismatch()
{
return GetString("AntiforgeryToken_ClaimUidMismatch");
}
=> GetString("AntiforgeryToken_ClaimUidMismatch");
/// <summary>
/// The antiforgery token could not be decrypted.
/// </summary>
internal static string AntiforgeryToken_DeserializationFailed
{
get { return GetString("AntiforgeryToken_DeserializationFailed"); }
get => GetString("AntiforgeryToken_DeserializationFailed");
}
/// <summary>
/// The antiforgery token could not be decrypted.
/// </summary>
internal static string FormatAntiforgeryToken_DeserializationFailed()
{
return GetString("AntiforgeryToken_DeserializationFailed");
}
=> GetString("AntiforgeryToken_DeserializationFailed");
/// <summary>
/// The antiforgery cookie token and request token do not match.
/// </summary>
internal static string AntiforgeryToken_SecurityTokenMismatch
{
get { return GetString("AntiforgeryToken_SecurityTokenMismatch"); }
get => GetString("AntiforgeryToken_SecurityTokenMismatch");
}
/// <summary>
/// The antiforgery cookie token and request token do not match.
/// </summary>
internal static string FormatAntiforgeryToken_SecurityTokenMismatch()
{
return GetString("AntiforgeryToken_SecurityTokenMismatch");
}
=> GetString("AntiforgeryToken_SecurityTokenMismatch");
/// <summary>
/// Validation of the provided antiforgery token failed. The cookie token and the request token were swapped.
/// </summary>
internal static string AntiforgeryToken_TokensSwapped
{
get { return GetString("AntiforgeryToken_TokensSwapped"); }
get => GetString("AntiforgeryToken_TokensSwapped");
}
/// <summary>
/// Validation of the provided antiforgery token failed. The cookie token and the request token were swapped.
/// </summary>
internal static string FormatAntiforgeryToken_TokensSwapped()
{
return GetString("AntiforgeryToken_TokensSwapped");
}
=> GetString("AntiforgeryToken_TokensSwapped");
/// <summary>
/// The provided antiforgery token was meant for user "{0}", but the current user is "{1}".
/// </summary>
internal static string AntiforgeryToken_UsernameMismatch
{
get { return GetString("AntiforgeryToken_UsernameMismatch"); }
get => GetString("AntiforgeryToken_UsernameMismatch");
}
/// <summary>
/// The provided antiforgery token was meant for user "{0}", but the current user is "{1}".
/// </summary>
internal static string FormatAntiforgeryToken_UsernameMismatch(object p0, object p1)
{
return string.Format(CultureInfo.CurrentCulture, GetString("AntiforgeryToken_UsernameMismatch"), p0, p1);
}
=> string.Format(CultureInfo.CurrentCulture, GetString("AntiforgeryToken_UsernameMismatch"), p0, p1);
/// <summary>
/// The antiforgery system has the configuration value {0}.{1} = {2}, but the current request is not an SSL request.
/// </summary>
internal static string AntiforgeryWorker_RequireSSL
{
get { return GetString("AntiforgeryWorker_RequireSSL"); }
}
/// <summary>
/// The antiforgery system has the configuration value {0}.{1} = {2}, but the current request is not an SSL request.
/// </summary>
internal static string FormatAntiforgeryWorker_RequireSSL(object p0, object p1, object p2)
{
return string.Format(CultureInfo.CurrentCulture, GetString("AntiforgeryWorker_RequireSSL"), p0, p1, p2);
}
/// <summary>
/// The required antiforgery cookie "{0}" is not present.
/// The antiforgery cookie token is invalid.
/// </summary>
internal static string Antiforgery_CookieToken_IsInvalid
{
get { return GetString("Antiforgery_CookieToken_IsInvalid"); }
get => GetString("Antiforgery_CookieToken_IsInvalid");
}
/// <summary>
/// The antiforgery cookie token is invalid.
/// </summary>
internal static string FormatAntiforgery_CookieToken_IsInvalid()
=> GetString("Antiforgery_CookieToken_IsInvalid");
/// <summary>
/// The required antiforgery cookie "{0}" is not present.
/// </summary>
internal static string Antiforgery_CookieToken_MustBeProvided
{
get { return GetString("Antiforgery_CookieToken_MustBeProvided"); }
get => GetString("Antiforgery_CookieToken_MustBeProvided");
}
/// <summary>
/// The required antiforgery cookie "{0}" is not present.
/// </summary>
internal static string FormatAntiforgery_CookieToken_MustBeProvided(object p0)
{
return string.Format(CultureInfo.CurrentCulture, GetString("Antiforgery_CookieToken_MustBeProvided"), p0);
}
=> string.Format(CultureInfo.CurrentCulture, GetString("Antiforgery_CookieToken_MustBeProvided"), p0);
/// <summary>
/// The required antiforgery cookie token must be provided.
/// </summary>
internal static string Antiforgery_CookieToken_MustBeProvided_Generic
{
get { return GetString("Antiforgery_CookieToken_MustBeProvided_Generic"); }
get => GetString("Antiforgery_CookieToken_MustBeProvided_Generic");
}
/// <summary>
/// The required antiforgery cookie token must be provided.
/// </summary>
internal static string FormatAntiforgery_CookieToken_MustBeProvided_Generic()
{
return GetString("Antiforgery_CookieToken_MustBeProvided_Generic");
}
=> GetString("Antiforgery_CookieToken_MustBeProvided_Generic");
/// <summary>
/// The required antiforgery form field "{0}" is not present.
/// </summary>
internal static string Antiforgery_FormToken_MustBeProvided
{
get { return GetString("Antiforgery_FormToken_MustBeProvided"); }
get => GetString("Antiforgery_FormToken_MustBeProvided");
}
/// <summary>
/// The required antiforgery form field "{0}" is not present.
/// </summary>
internal static string FormatAntiforgery_FormToken_MustBeProvided(object p0)
{
return string.Format(CultureInfo.CurrentCulture, GetString("Antiforgery_FormToken_MustBeProvided"), p0);
}
=> string.Format(CultureInfo.CurrentCulture, GetString("Antiforgery_FormToken_MustBeProvided"), p0);
/// <summary>
/// The required antiforgery header value "{0}" is not present.
/// </summary>
internal static string Antiforgery_HeaderToken_MustBeProvided
{
get { return GetString("Antiforgery_HeaderToken_MustBeProvided"); }
get => GetString("Antiforgery_HeaderToken_MustBeProvided");
}
/// <summary>
/// The required antiforgery header value "{0}" is not present.
/// </summary>
internal static string FormatAntiforgery_HeaderToken_MustBeProvided(object p0)
{
return string.Format(CultureInfo.CurrentCulture, GetString("Antiforgery_HeaderToken_MustBeProvided"), p0);
}
=> string.Format(CultureInfo.CurrentCulture, GetString("Antiforgery_HeaderToken_MustBeProvided"), p0);
/// <summary>
/// The required antiforgery request token was not provided in either form field "{0}" or header value "{1}".
/// </summary>
internal static string Antiforgery_RequestToken_MustBeProvided
{
get { return GetString("Antiforgery_RequestToken_MustBeProvided"); }
get => GetString("Antiforgery_RequestToken_MustBeProvided");
}
/// <summary>
/// The required antiforgery request token was not provided in either form field "{0}" or header value "{1}".
/// </summary>
internal static string FormatAntiforgery_RequestToken_MustBeProvided(object p0, object p1)
{
return string.Format(CultureInfo.CurrentCulture, GetString("Antiforgery_RequestToken_MustBeProvided"), p0, p1);
}
=> string.Format(CultureInfo.CurrentCulture, GetString("Antiforgery_RequestToken_MustBeProvided"), p0, p1);
/// <summary>
/// The required antiforgery request token must be provided.
/// </summary>
internal static string Antiforgery_RequestToken_MustBeProvided_Generic
{
get { return GetString("Antiforgery_RequestToken_MustBeProvided_Generic"); }
get => GetString("Antiforgery_RequestToken_MustBeProvided_Generic");
}
/// <summary>
/// The required antiforgery request token must be provided.
/// </summary>
internal static string FormatAntiforgery_RequestToken_MustBeProvided_Generic()
=> GetString("Antiforgery_RequestToken_MustBeProvided_Generic");
/// <summary>
/// The antiforgery system has the configuration value {optionName} = {value}, but the current request is not an SSL request.
/// </summary>
internal static string Antiforgery_RequiresSSL
{
return GetString("Antiforgery_RequestToken_MustBeProvided_Generic");
get => GetString("Antiforgery_RequiresSSL");
}
/// <summary>
/// The antiforgery system has the configuration value {optionName} = {value}, but the current request is not an SSL request.
/// </summary>
internal static string FormatAntiforgery_RequiresSSL(object optionName, object value)
=> string.Format(CultureInfo.CurrentCulture, GetString("Antiforgery_RequiresSSL", "optionName", "value"), optionName, value);
/// <summary>
/// Value cannot be null or empty.
/// </summary>
internal static string ArgumentCannotBeNullOrEmpty
{
get { return GetString("ArgumentCannotBeNullOrEmpty"); }
get => GetString("ArgumentCannotBeNullOrEmpty");
}
/// <summary>
/// Value cannot be null or empty.
/// </summary>
internal static string FormatArgumentCannotBeNullOrEmpty()
{
return GetString("ArgumentCannotBeNullOrEmpty");
}
=> GetString("ArgumentCannotBeNullOrEmpty");
private static string GetString(string name, params string[] formatterNames)
{

View File

@ -139,10 +139,6 @@
<data name="AntiforgeryToken_UsernameMismatch" xml:space="preserve">
<value>The provided antiforgery token was meant for user "{0}", but the current user is "{1}".</value>
</data>
<data name="AntiforgeryWorker_RequireSSL" xml:space="preserve">
<value>The antiforgery system has the configuration value {0}.{1} = {2}, but the current request is not an SSL request.</value>
<comment>0 = nameof(AntiforgeryOptions), 1 = nameof(RequireSsl), 2 = bool.TrueString</comment>
</data>
<data name="Antiforgery_CookieToken_IsInvalid" xml:space="preserve">
<value>The antiforgery cookie token is invalid.</value>
</data>
@ -164,6 +160,9 @@
<data name="Antiforgery_RequestToken_MustBeProvided_Generic" xml:space="preserve">
<value>The required antiforgery request token must be provided.</value>
</data>
<data name="Antiforgery_RequiresSSL" xml:space="preserve">
<value>The antiforgery system has the configuration value {optionName} = {value}, but the current request is not an SSL request.</value>
</data>
<data name="ArgumentCannotBeNullOrEmpty" xml:space="preserve">
<value>Value cannot be null or empty.</value>
</data>

View File

@ -28,7 +28,7 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal
var options = services.GetRequiredService<IOptions<AntiforgeryOptions>>();
// Act
var cookieName = options.Value.CookieName;
var cookieName = options.Value.Cookie.Name;
// Assert
Assert.Equal(expectedCookieName, cookieName);
@ -41,8 +41,8 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal
var serviceCollection = new ServiceCollection();
serviceCollection.Configure<AntiforgeryOptions>(o =>
{
Assert.Null(o.CookieName);
o.CookieName = "antiforgery";
Assert.Null(o.Cookie.Name);
o.Cookie.Name = "antiforgery";
});
serviceCollection.AddAntiforgery();
serviceCollection
@ -53,7 +53,7 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal
var options = services.GetRequiredService<IOptions<AntiforgeryOptions>>();
// Act
var cookieName = options.Value.CookieName;
var cookieName = options.Value.Cookie.Name;
// Assert
Assert.Equal("antiforgery", cookieName);

View File

@ -28,9 +28,12 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal
{
// Arrange
var httpContext = GetHttpContext();
var options = new AntiforgeryOptions()
var options = new AntiforgeryOptions
{
#pragma warning disable CS0618
// obsolete property still forwards to correctly to the new API
RequireSsl = true
#pragma warning restore CS0618
};
var antiforgery = GetAntiforgery(httpContext, options);
@ -38,7 +41,7 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal
var exception = await Assert.ThrowsAsync<InvalidOperationException>(
() => antiforgery.ValidateRequestAsync(httpContext));
Assert.Equal(
@"The antiforgery system has the configuration value AntiforgeryOptions.RequireSsl = true, " +
@"The antiforgery system has the configuration value AntiforgeryOptions.Cookie.SecurePolicy = Always, " +
"but the current request is not an SSL request.",
exception.Message);
}
@ -50,7 +53,7 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal
var httpContext = GetHttpContext();
var options = new AntiforgeryOptions()
{
RequireSsl = true
Cookie = { SecurePolicy = CookieSecurePolicy.Always }
};
var antiforgery = GetAntiforgery(httpContext, options);
@ -59,7 +62,7 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal
var exception = await Assert.ThrowsAsync<InvalidOperationException>(
() => antiforgery.IsRequestValidAsync(httpContext));
Assert.Equal(
@"The antiforgery system has the configuration value AntiforgeryOptions.RequireSsl = true, " +
@"The antiforgery system has the configuration value AntiforgeryOptions.Cookie.SecurePolicy = Always, " +
"but the current request is not an SSL request.",
exception.Message);
}
@ -71,7 +74,7 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal
var httpContext = GetHttpContext();
var options = new AntiforgeryOptions()
{
RequireSsl = true
Cookie = { SecurePolicy = CookieSecurePolicy.Always }
};
var antiforgery = GetAntiforgery(httpContext, options);
@ -80,7 +83,7 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal
var exception = Assert.Throws<InvalidOperationException>(
() => antiforgery.GetAndStoreTokens(httpContext));
Assert.Equal(
@"The antiforgery system has the configuration value AntiforgeryOptions.RequireSsl = true, " +
@"The antiforgery system has the configuration value AntiforgeryOptions.Cookie.SecurePolicy = Always, " +
"but the current request is not an SSL request.",
exception.Message);
}
@ -92,7 +95,7 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal
var httpContext = GetHttpContext();
var options = new AntiforgeryOptions()
{
RequireSsl = true
Cookie = { SecurePolicy = CookieSecurePolicy.Always }
};
var antiforgery = GetAntiforgery(httpContext, options);
@ -101,7 +104,7 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal
var exception = Assert.Throws<InvalidOperationException>(
() => antiforgery.GetTokens(httpContext));
Assert.Equal(
@"The antiforgery system has the configuration value AntiforgeryOptions.RequireSsl = true, " +
@"The antiforgery system has the configuration value AntiforgeryOptions.Cookie.SecurePolicy = Always, " +
"but the current request is not an SSL request.",
exception.Message);
}
@ -113,7 +116,7 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal
var httpContext = GetHttpContext();
var options = new AntiforgeryOptions()
{
RequireSsl = true
Cookie = { SecurePolicy = CookieSecurePolicy.Always }
};
var antiforgery = GetAntiforgery(httpContext, options);
@ -122,7 +125,7 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal
var exception = Assert.Throws<InvalidOperationException>(
() => antiforgery.SetCookieTokenAndHeader(httpContext));
Assert.Equal(
@"The antiforgery system has the configuration value AntiforgeryOptions.RequireSsl = true, " +
@"The antiforgery system has the configuration value AntiforgeryOptions.Cookie.SecurePolicy = Always, " +
"but the current request is not an SSL request.",
exception.Message);
}
@ -745,7 +748,7 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal
// Arrange
var context = CreateMockContext(new AntiforgeryOptions()
{
CookieName = "cookie-name",
Cookie = { Name = "cookie-name" },
FormFieldName = "form-field-name",
HeaderName = null,
});
@ -769,7 +772,7 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal
// Arrange
var context = CreateMockContext(new AntiforgeryOptions()
{
CookieName = "cookie-name",
Cookie = { Name = "cookie-name" },
FormFieldName = "form-field-name",
HeaderName = null,
});
@ -793,7 +796,7 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal
// Arrange
var context = CreateMockContext(new AntiforgeryOptions()
{
CookieName = "cookie-name",
Cookie = { Name = "cookie-name" },
FormFieldName = "form-field-name",
HeaderName = "header-name",
});
@ -819,7 +822,7 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal
// Arrange
var context = CreateMockContext(new AntiforgeryOptions()
{
CookieName = "cookie-name",
Cookie = { Name = "cookie-name" },
FormFieldName = "form-field-name",
HeaderName = "header-name",
});

View File

@ -21,9 +21,9 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal
{
// Arrange
var httpContext = GetHttpContext(new RequestCookieCollection());
var options = new AntiforgeryOptions()
var options = new AntiforgeryOptions
{
CookieName = _cookieName
Cookie = { Name = _cookieName }
};
var tokenStore = new DefaultAntiforgeryTokenStore(new TestOptionsManager(options));
@ -40,9 +40,9 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal
{
// Arrange
var httpContext = GetHttpContext(_cookieName, string.Empty);
var options = new AntiforgeryOptions()
var options = new AntiforgeryOptions
{
CookieName = _cookieName
Cookie = { Name = _cookieName }
};
var tokenStore = new DefaultAntiforgeryTokenStore(new TestOptionsManager(options));
@ -61,9 +61,9 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal
var expectedToken = "valid-value";
var httpContext = GetHttpContext(_cookieName, expectedToken);
var options = new AntiforgeryOptions()
var options = new AntiforgeryOptions
{
CookieName = _cookieName
Cookie = { Name = _cookieName }
};
var tokenStore = new DefaultAntiforgeryTokenStore(new TestOptionsManager(options));
@ -82,9 +82,9 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal
var httpContext = GetHttpContext(new RequestCookieCollection());
httpContext.Request.Form = FormCollection.Empty;
var options = new AntiforgeryOptions()
var options = new AntiforgeryOptions
{
CookieName = "cookie-name",
Cookie = { Name = "cookie-name" },
FormFieldName = "form-field-name",
};
@ -110,9 +110,9 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal
}); // header value has priority.
httpContext.Request.Headers.Add("header-name", "header-value");
var options = new AntiforgeryOptions()
var options = new AntiforgeryOptions
{
CookieName = "cookie-name",
Cookie = { Name = "cookie-name" },
FormFieldName = "form-field-name",
HeaderName = "header-name",
};
@ -138,9 +138,9 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal
{ "form-field-name", "form-value" },
});
var options = new AntiforgeryOptions()
var options = new AntiforgeryOptions
{
CookieName = "cookie-name",
Cookie = { Name = "cookie-name" },
FormFieldName = "form-field-name",
HeaderName = "header-name",
};
@ -166,9 +166,9 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal
// Will not be accessed
httpContext.Request.Form = null;
var options = new AntiforgeryOptions()
var options = new AntiforgeryOptions
{
CookieName = "cookie-name",
Cookie = { Name = "cookie-name" },
FormFieldName = "form-field-name",
HeaderName = "header-name",
};
@ -193,9 +193,9 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal
// Will not be accessed
httpContext.Request.Form = null;
var options = new AntiforgeryOptions()
var options = new AntiforgeryOptions
{
CookieName = "cookie-name",
Cookie = { Name = "cookie-name" },
FormFieldName = "form-field-name",
HeaderName = "header-name",
};
@ -218,9 +218,9 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal
httpContext.Request.ContentType = "application/x-www-form-urlencoded";
httpContext.Request.Form = FormCollection.Empty;
var options = new AntiforgeryOptions()
var options = new AntiforgeryOptions
{
CookieName = "cookie-name",
Cookie = { Name = "cookie-name" },
FormFieldName = "form-field-name",
HeaderName = "header-name",
};
@ -236,9 +236,9 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal
}
[Theory]
[InlineData(true, true)]
[InlineData(false, null)]
public void SaveCookieToken(bool requireSsl, bool? expectedCookieSecureFlag)
[InlineData(CookieSecurePolicy.Always, true)]
[InlineData(CookieSecurePolicy.None, null)]
public void SaveCookieToken(CookieSecurePolicy policy, bool? expectedCookieSecureFlag)
{
// Arrange
var token = "serialized-value";
@ -255,8 +255,11 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal
var options = new AntiforgeryOptions()
{
CookieName = _cookieName,
RequireSsl = requireSsl
Cookie =
{
Name = _cookieName,
SecurePolicy = policy
},
};
var tokenStore = new DefaultAntiforgeryTokenStore(new TestOptionsManager(options));
@ -294,8 +297,10 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal
httpContext
.SetupGet(hc => hc.Request.Path)
.Returns("/index.html");
var options = new AntiforgeryOptions();
options.CookieName = _cookieName;
var options = new AntiforgeryOptions
{
Cookie = { Name = _cookieName }
};
var tokenStore = new DefaultAntiforgeryTokenStore(new TestOptionsManager(options));
// Act
@ -328,9 +333,14 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal
httpContext
.SetupGet(hc => hc.Request.Path)
.Returns("/index.html");
var options = new AntiforgeryOptions();
options.CookieName = _cookieName;
options.ConfigureCookieOptions = (context, cookieOptions) => cookieOptions.Path = expectedCookiePath;
var options = new AntiforgeryOptions
{
Cookie =
{
Name = _cookieName,
Path = expectedCookiePath
}
};
var tokenStore = new DefaultAntiforgeryTokenStore(new TestOptionsManager(options));
// Act
@ -362,9 +372,14 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal
httpContext
.SetupGet(hc => hc.Request.Path)
.Returns("/index.html");
var options = new AntiforgeryOptions();
options.CookieName = _cookieName;
options.ConfigureCookieOptions = (context, cookieOptions) => cookieOptions.Domain = expectedCookieDomain;
var options = new AntiforgeryOptions
{
Cookie =
{
Name = _cookieName,
Domain = expectedCookieDomain
}
};
var tokenStore = new DefaultAntiforgeryTokenStore(new TestOptionsManager(options));
// Act
@ -407,10 +422,10 @@ namespace Microsoft.AspNetCore.Antiforgery.Internal
public void Append(string key, string value, CookieOptions options)
{
this.Key = key;
this.Value = value;
this.Options = options;
this.Count++;
Key = key;
Value = value;
Options = options;
Count++;
}
public void Append(string key, string value)