Renaming AntiForgeryConfig-> AntiForgeryOptions.

Adding MvcOptions and updating AntiForgery system to use AntiForgeryConfiguration from MvcOptions
This commit is contained in:
harshgMSFT 2014-05-08 13:06:24 -07:00
parent 7f34c94de7
commit b58083f73a
21 changed files with 207 additions and 155 deletions

View File

@ -1,11 +1,11 @@
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. // Copyright (c) Microsoft Open Technologies, Inc. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.ComponentModel;
using System.Threading.Tasks; using System.Threading.Tasks;
using Microsoft.AspNet.Http; using Microsoft.AspNet.Http;
using Microsoft.AspNet.Mvc.Rendering; using Microsoft.AspNet.Mvc.Rendering;
using Microsoft.AspNet.Security.DataProtection; using Microsoft.AspNet.Security.DataProtection;
using Microsoft.Framework.OptionsModel;
namespace Microsoft.AspNet.Mvc namespace Microsoft.AspNet.Mvc
{ {
@ -20,10 +20,10 @@ namespace Microsoft.AspNet.Mvc
public AntiForgery([NotNull] IClaimUidExtractor claimUidExtractor, public AntiForgery([NotNull] IClaimUidExtractor claimUidExtractor,
[NotNull] IDataProtectionProvider dataProtectionProvider, [NotNull] IDataProtectionProvider dataProtectionProvider,
[NotNull] IAntiForgeryAdditionalDataProvider additionalDataProvider) [NotNull] IAntiForgeryAdditionalDataProvider additionalDataProvider,
[NotNull] IOptionsAccessor<MvcOptions> mvcOptions)
{ {
// TODO: This is temporary till we figure out how to flow configs using DI. var config = mvcOptions.Options.AntiForgeryOptions;
var config = new AntiForgeryConfigWrapper();
var serializer = new AntiForgeryTokenSerializer(dataProtectionProvider.CreateProtector(_purpose)); var serializer = new AntiForgeryTokenSerializer(dataProtectionProvider.CreateProtector(_purpose));
var tokenStore = new AntiForgeryTokenStore(config, serializer); var tokenStore = new AntiForgeryTokenStore(config, serializer);
var tokenProvider = new TokenProvider(config, claimUidExtractor, additionalDataProvider); var tokenProvider = new TokenProvider(config, claimUidExtractor, additionalDataProvider);

View File

@ -1,28 +0,0 @@
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
namespace Microsoft.AspNet.Mvc
{
public sealed class AntiForgeryConfigWrapper : IAntiForgeryConfig
{
public string CookieName
{
get { return AntiForgeryConfig.CookieName; }
}
public string FormFieldName
{
get { return AntiForgeryConfig.AntiForgeryTokenFieldName; }
}
public bool RequireSSL
{
get { return AntiForgeryConfig.RequireSsl; }
}
public bool SuppressXFrameOptionsHeader
{
get { return AntiForgeryConfig.SuppressXFrameOptionsHeader; }
}
}
}

View File

@ -1,15 +1,24 @@
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. // Copyright (c) Microsoft Open Technologies, Inc. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using Microsoft.AspNet.Mvc.Core;
namespace Microsoft.AspNet.Mvc namespace Microsoft.AspNet.Mvc
{ {
/// <summary> /// <summary>
/// Provides programmatic configuration for the anti-forgery token system. /// Provides programmatic configuration for the anti-forgery token system.
/// </summary> /// </summary>
public static class AntiForgeryConfig public class AntiForgeryOptions
{ {
internal const string AntiForgeryTokenFieldName = "__RequestVerificationToken"; private const string AntiForgeryTokenFieldName = "__RequestVerificationToken";
private static string _cookieName; private string _cookieName;
private string _formFieldName = AntiForgeryTokenFieldName;
public AntiForgeryOptions()
{
_cookieName = GetAntiForgeryCookieName();
}
/// <summary> /// <summary>
/// Specifies the name of the cookie that is used by the anti-forgery /// Specifies the name of the cookie that is used by the anti-forgery
@ -19,28 +28,55 @@ namespace Microsoft.AspNet.Mvc
/// If an explicit name is not provided, the system will automatically /// If an explicit name is not provided, the system will automatically
/// generate a name. /// generate a name.
/// </remarks> /// </remarks>
public static string CookieName public string CookieName
{ {
get get
{ {
if (_cookieName == null)
{
_cookieName = GetAntiForgeryCookieName();
}
return _cookieName; return _cookieName;
} }
set set
{ {
if (value == null)
{
throw new ArgumentNullException("value",
Resources.FormatPropertyOfTypeCannotBeNull(
"CookieName", typeof(AntiForgeryOptions)));
}
_cookieName = value; _cookieName = value;
} }
} }
/// <summary>
/// Specifies the name of the anti-forgery token field that is used by the anti-forgery system.
/// </summary>
public string FormFieldName
{
get
{
return _formFieldName;
}
set
{
if (value == null)
{
throw new ArgumentNullException("value",
Resources.FormatPropertyOfTypeCannotBeNull(
"FormFieldName", typeof(AntiForgeryOptions)));
}
_formFieldName = value;
}
}
/// <summary> /// <summary>
/// Specifies whether SSL is required for the anti-forgery system /// Specifies whether SSL is required for the anti-forgery system
/// to operate. If this setting is 'true' and a non-SSL request /// to operate. If this setting is 'true' and a non-SSL request
/// comes into the system, all anti-forgery APIs will fail. /// comes into the system, all anti-forgery APIs will fail.
/// </summary> /// </summary>
public static bool RequireSsl public bool RequireSSL
{ {
get; get;
set; set;
@ -52,14 +88,14 @@ namespace Microsoft.AspNet.Mvc
/// header is generated with the value SAMEORIGIN. If this setting is 'true', /// header is generated with the value SAMEORIGIN. If this setting is 'true',
/// the X-Frame-Options header will not be generated for the response. /// the X-Frame-Options header will not be generated for the response.
/// </summary> /// </summary>
public static bool SuppressXFrameOptionsHeader public bool SuppressXFrameOptionsHeader
{ {
get; get;
set; set;
} }
// TODO: Replace the stub. // TODO: Replace the stub.
private static string GetAntiForgeryCookieName() private string GetAntiForgeryCookieName()
{ {
return AntiForgeryTokenFieldName; return AntiForgeryTokenFieldName;
} }

View File

@ -10,10 +10,10 @@ namespace Microsoft.AspNet.Mvc
// Saves anti-XSRF tokens split between HttpRequest.Cookies and HttpRequest.Form // Saves anti-XSRF tokens split between HttpRequest.Cookies and HttpRequest.Form
internal sealed class AntiForgeryTokenStore : ITokenStore internal sealed class AntiForgeryTokenStore : ITokenStore
{ {
private readonly IAntiForgeryConfig _config; private readonly AntiForgeryOptions _config;
private readonly IAntiForgeryTokenSerializer _serializer; private readonly IAntiForgeryTokenSerializer _serializer;
internal AntiForgeryTokenStore([NotNull] IAntiForgeryConfig config, internal AntiForgeryTokenStore([NotNull] AntiForgeryOptions config,
[NotNull] IAntiForgeryTokenSerializer serializer) [NotNull] IAntiForgeryTokenSerializer serializer)
{ {
_config = config; _config = config;

View File

@ -14,14 +14,14 @@ namespace Microsoft.AspNet.Mvc
{ {
internal sealed class AntiForgeryWorker internal sealed class AntiForgeryWorker
{ {
private readonly IAntiForgeryConfig _config; private readonly AntiForgeryOptions _config;
private readonly IAntiForgeryTokenSerializer _serializer; private readonly IAntiForgeryTokenSerializer _serializer;
private readonly ITokenStore _tokenStore; private readonly ITokenStore _tokenStore;
private readonly ITokenValidator _validator; private readonly ITokenValidator _validator;
private readonly ITokenGenerator _generator; private readonly ITokenGenerator _generator;
internal AntiForgeryWorker([NotNull] IAntiForgeryTokenSerializer serializer, internal AntiForgeryWorker([NotNull] IAntiForgeryTokenSerializer serializer,
[NotNull] IAntiForgeryConfig config, [NotNull] AntiForgeryOptions config,
[NotNull] ITokenStore tokenStore, [NotNull] ITokenStore tokenStore,
[NotNull] ITokenGenerator generator, [NotNull] ITokenGenerator generator,
[NotNull] ITokenValidator validator) [NotNull] ITokenValidator validator)

View File

@ -1,21 +0,0 @@
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
namespace Microsoft.AspNet.Mvc
{
// Provides configuration information about the anti-forgery system.
public interface IAntiForgeryConfig
{
// Name of the cookie to use.
string CookieName { get; }
// Name of the form field to use.
string FormFieldName { get; }
// Whether SSL is mandatory for this request.
bool RequireSSL { get; }
// Skip X-FRAME-OPTIONS header.
bool SuppressXFrameOptionsHeader { get; }
}
}

View File

@ -12,10 +12,10 @@ namespace Microsoft.AspNet.Mvc
internal sealed class TokenProvider : ITokenValidator, ITokenGenerator internal sealed class TokenProvider : ITokenValidator, ITokenGenerator
{ {
private readonly IClaimUidExtractor _claimUidExtractor; private readonly IClaimUidExtractor _claimUidExtractor;
private readonly IAntiForgeryConfig _config; private readonly AntiForgeryOptions _config;
private readonly IAntiForgeryAdditionalDataProvider _additionalDataProvider; private readonly IAntiForgeryAdditionalDataProvider _additionalDataProvider;
internal TokenProvider(IAntiForgeryConfig config, internal TokenProvider(AntiForgeryOptions config,
IClaimUidExtractor claimUidExtractor, IClaimUidExtractor claimUidExtractor,
IAntiForgeryAdditionalDataProvider additionalDataProvider) IAntiForgeryAdditionalDataProvider additionalDataProvider)
{ {

View File

@ -44,8 +44,7 @@
<Compile Include="ActionResults\RedirectToRouteResult.cs" /> <Compile Include="ActionResults\RedirectToRouteResult.cs" />
<Compile Include="ActionResults\ViewResult.cs" /> <Compile Include="ActionResults\ViewResult.cs" />
<Compile Include="AntiForgery\AntiForgery.cs" /> <Compile Include="AntiForgery\AntiForgery.cs" />
<Compile Include="AntiForgery\AntiForgeryConfig.cs" /> <Compile Include="AntiForgery\AntiForgeryOptions.cs" />
<Compile Include="AntiForgery\AntiForgeryConfigWrapper.cs" />
<Compile Include="AntiForgery\AntiForgeryToken.cs" /> <Compile Include="AntiForgery\AntiForgeryToken.cs" />
<Compile Include="AntiForgery\AntiForgeryTokenSerializer.cs" /> <Compile Include="AntiForgery\AntiForgeryTokenSerializer.cs" />
<Compile Include="AntiForgery\AntiForgeryTokenSet.cs" /> <Compile Include="AntiForgery\AntiForgeryTokenSet.cs" />
@ -55,7 +54,6 @@
<Compile Include="AntiForgery\DefaultClaimUidExtractor.cs" /> <Compile Include="AntiForgery\DefaultClaimUidExtractor.cs" />
<Compile Include="AntiForgery\DefaultAntiForgeryAdditionalDataProvider.cs" /> <Compile Include="AntiForgery\DefaultAntiForgeryAdditionalDataProvider.cs" />
<Compile Include="AntiForgery\IAntiForgeryAdditionalDataProvider.cs" /> <Compile Include="AntiForgery\IAntiForgeryAdditionalDataProvider.cs" />
<Compile Include="AntiForgery\IAntiForgeryConfig.cs" />
<Compile Include="AntiForgery\IAntiForgeryTokenSerializer.cs" /> <Compile Include="AntiForgery\IAntiForgeryTokenSerializer.cs" />
<Compile Include="AntiForgery\IClaimUidExtractor.cs" /> <Compile Include="AntiForgery\IClaimUidExtractor.cs" />
<Compile Include="AntiForgery\ITokenGenerator.cs" /> <Compile Include="AntiForgery\ITokenGenerator.cs" />
@ -140,6 +138,7 @@
<Compile Include="IParameterDescriptorFactory.cs" /> <Compile Include="IParameterDescriptorFactory.cs" />
<Compile Include="IUrlHelper.cs" /> <Compile Include="IUrlHelper.cs" />
<Compile Include="JsonOutputFormatter.cs" /> <Compile Include="JsonOutputFormatter.cs" />
<Compile Include="MvcOptions.cs" />
<Compile Include="MvcRouteHandler.cs" /> <Compile Include="MvcRouteHandler.cs" />
<Compile Include="NonActionAttribute.cs" /> <Compile Include="NonActionAttribute.cs" />
<Compile Include="ParameterBindingInfo.cs" /> <Compile Include="ParameterBindingInfo.cs" />

View File

@ -0,0 +1,33 @@
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using Microsoft.AspNet.Mvc.Core;
namespace Microsoft.AspNet.Mvc
{
public class MvcOptions
{
private AntiForgeryOptions _antiForgeryOptions = new AntiForgeryOptions();
public AntiForgeryOptions AntiForgeryOptions
{
get
{
return _antiForgeryOptions;
}
set
{
if (value == null)
{
throw new ArgumentNullException("value",
Resources.FormatPropertyOfTypeCannotBeNull("AntiForgeryOptions",
typeof(MvcOptions)));
}
_antiForgeryOptions = value;
}
}
}
}

View File

@ -139,7 +139,7 @@ namespace Microsoft.AspNet.Mvc.Core
} }
/// <summary> /// <summary>
/// The anti-forgery system has the configuration value AntiForgeryConfig.RequireSsl = true, but the current request is not an SSL request. /// The anti-forgery system has the configuration value AntiForgeryOptions.RequireSsl = true, but the current request is not an SSL request.
/// </summary> /// </summary>
internal static string AntiForgeryWorker_RequireSSL internal static string AntiForgeryWorker_RequireSSL
{ {
@ -147,7 +147,7 @@ namespace Microsoft.AspNet.Mvc.Core
} }
/// <summary> /// <summary>
/// The anti-forgery system has the configuration value AntiForgeryConfig.RequireSsl = true, but the current request is not an SSL request. /// The anti-forgery system has the configuration value AntiForgeryOptions.RequireSsl = true, but the current request is not an SSL request.
/// </summary> /// </summary>
internal static string FormatAntiForgeryWorker_RequireSSL() internal static string FormatAntiForgeryWorker_RequireSSL()
{ {

View File

@ -142,7 +142,7 @@
<value>The provided anti-forgery token was meant for user "{0}", but the current user is "{1}".</value> <value>The provided anti-forgery token was meant for user "{0}", but the current user is "{1}".</value>
</data> </data>
<data name="AntiForgeryWorker_RequireSSL" xml:space="preserve"> <data name="AntiForgeryWorker_RequireSSL" xml:space="preserve">
<value>The anti-forgery system has the configuration value AntiForgeryConfig.RequireSsl = true, but the current request is not an SSL request.</value> <value>The anti-forgery system has the configuration value AntiForgeryOptions.RequireSsl = true, but the current request is not an SSL request.</value>
</data> </data>
<data name="ActionExecutor_WrappedTaskInstance" xml:space="preserve"> <data name="ActionExecutor_WrappedTaskInstance" xml:space="preserve">
<value>The method '{0}' on type '{1}' returned an instance of '{2}'. Make sure to call Unwrap on the returned value to avoid unobserved faulted Task.</value> <value>The method '{0}' on type '{1}' returned an instance of '{2}'. Make sure to call Unwrap on the returned value to avoid unobserved faulted Task.</value>

View File

@ -12,6 +12,7 @@
"Microsoft.AspNet.Security.DataProtection" : "0.1-alpha-*", "Microsoft.AspNet.Security.DataProtection" : "0.1-alpha-*",
"Microsoft.Framework.DependencyInjection": "0.1-alpha-*", "Microsoft.Framework.DependencyInjection": "0.1-alpha-*",
"Microsoft.Framework.Runtime.Interfaces": "0.1-alpha-*", "Microsoft.Framework.Runtime.Interfaces": "0.1-alpha-*",
"Microsoft.Framework.OptionsModel": "0.1-alpha-*",
"Newtonsoft.Json": "5.0.8" "Newtonsoft.Json": "5.0.8"
}, },
"configurations": { "configurations": {

View File

@ -4,6 +4,7 @@
using Microsoft.AspNet.Mvc; using Microsoft.AspNet.Mvc;
using Microsoft.AspNet.Routing; using Microsoft.AspNet.Routing;
using Microsoft.Framework.ConfigurationModel; using Microsoft.Framework.ConfigurationModel;
using Microsoft.Framework.OptionsModel;
namespace Microsoft.Framework.DependencyInjection namespace Microsoft.Framework.DependencyInjection
{ {

View File

@ -0,0 +1,35 @@
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using Xunit;
namespace Microsoft.AspNet.Mvc.Core.Test
{
public class AntiForgeryOptionsTests
{
[Fact]
public void CookieName_SettingNullValue_Throws()
{
// Arrange
var options = new AntiForgeryOptions();
// Act & Assert
var ex = Assert.Throws<ArgumentNullException>(() => options.CookieName = null);
Assert.Equal("The 'CookieName' property of 'Microsoft.AspNet.Mvc.AntiForgeryOptions' must not be null." +
"\r\nParameter name: value", ex.Message);
}
[Fact]
public void FormFieldName_SettingNullValue_Throws()
{
// Arrange
var options = new AntiForgeryOptions();
// Act & Assert
var ex = Assert.Throws<ArgumentNullException>(() => options.FormFieldName = null);
Assert.Equal("The 'FormFieldName' property of 'Microsoft.AspNet.Mvc.AntiForgeryOptions' must not be null." +
"\r\nParameter name: value", ex.Message);
}
}
}

View File

@ -26,7 +26,7 @@ namespace Microsoft.AspNet.Mvc.Core.Test
mockHttpContext mockHttpContext
.Setup(o => o.Request.Cookies) .Setup(o => o.Request.Cookies)
.Returns(requestCookies.Object); .Returns(requestCookies.Object);
var config = new MockAntiForgeryConfig() var config = new AntiForgeryOptions()
{ {
CookieName = _cookieName CookieName = _cookieName
}; };
@ -48,7 +48,7 @@ namespace Microsoft.AspNet.Mvc.Core.Test
// Arrange // Arrange
var mockHttpContext = GetMockHttpContext(_cookieName, string.Empty); var mockHttpContext = GetMockHttpContext(_cookieName, string.Empty);
var config = new MockAntiForgeryConfig() var config = new AntiForgeryOptions()
{ {
CookieName = _cookieName CookieName = _cookieName
}; };
@ -69,7 +69,7 @@ namespace Microsoft.AspNet.Mvc.Core.Test
{ {
// Arrange // Arrange
var mockHttpContext = GetMockHttpContext(_cookieName, "invalid-value"); var mockHttpContext = GetMockHttpContext(_cookieName, "invalid-value");
var config = new MockAntiForgeryConfig() var config = new AntiForgeryOptions()
{ {
CookieName = _cookieName CookieName = _cookieName
}; };
@ -96,7 +96,7 @@ namespace Microsoft.AspNet.Mvc.Core.Test
var expectedToken = new AntiForgeryToken(); var expectedToken = new AntiForgeryToken();
var mockHttpContext = GetMockHttpContext(_cookieName, "valid-value"); var mockHttpContext = GetMockHttpContext(_cookieName, "valid-value");
MockAntiForgeryConfig config = new MockAntiForgeryConfig() var config = new AntiForgeryOptions()
{ {
CookieName = _cookieName CookieName = _cookieName
}; };
@ -130,7 +130,7 @@ namespace Microsoft.AspNet.Mvc.Core.Test
mockHttpContext.Setup(o => o.Request) mockHttpContext.Setup(o => o.Request)
.Returns(requestContext.Object); .Returns(requestContext.Object);
var config = new MockAntiForgeryConfig() var config = new AntiForgeryOptions()
{ {
FormFieldName = "form-field-name" FormFieldName = "form-field-name"
}; };
@ -161,7 +161,7 @@ namespace Microsoft.AspNet.Mvc.Core.Test
mockHttpContext.Setup(o => o.Request) mockHttpContext.Setup(o => o.Request)
.Returns(requestContext.Object); .Returns(requestContext.Object);
var config = new MockAntiForgeryConfig() var config = new AntiForgeryOptions()
{ {
FormFieldName = "form-field-name" FormFieldName = "form-field-name"
}; };
@ -199,7 +199,7 @@ namespace Microsoft.AspNet.Mvc.Core.Test
mockHttpContext.Setup(o => o.Request) mockHttpContext.Setup(o => o.Request)
.Returns(requestContext.Object); .Returns(requestContext.Object);
var config = new MockAntiForgeryConfig() var config = new AntiForgeryOptions()
{ {
FormFieldName = "form-field-name" FormFieldName = "form-field-name"
}; };
@ -241,7 +241,7 @@ namespace Microsoft.AspNet.Mvc.Core.Test
mockSerializer.Setup(o => o.Serialize(token)) mockSerializer.Setup(o => o.Serialize(token))
.Returns("serialized-value"); .Returns("serialized-value");
var config = new MockAntiForgeryConfig() var config = new AntiForgeryOptions()
{ {
CookieName = _cookieName, CookieName = _cookieName,
RequireSSL = requireSsl RequireSSL = requireSsl

View File

@ -25,7 +25,7 @@ namespace Microsoft.AspNet.Mvc.Core.Test
mockHttpContext.Setup(o => o.Request.IsSecure) mockHttpContext.Setup(o => o.Request.IsSecure)
.Returns(false); .Returns(false);
var config = new MockAntiForgeryConfig() var config = new AntiForgeryOptions()
{ {
RequireSSL = true RequireSSL = true
}; };
@ -43,7 +43,7 @@ namespace Microsoft.AspNet.Mvc.Core.Test
Assert.ThrowsAsync<InvalidOperationException>( Assert.ThrowsAsync<InvalidOperationException>(
async () => await worker.ValidateAsync(mockHttpContext.Object)); async () => await worker.ValidateAsync(mockHttpContext.Object));
Assert.Equal( Assert.Equal(
@"The anti-forgery system has the configuration value AntiForgeryConfig.RequireSsl = true, " + @"The anti-forgery system has the configuration value AntiForgeryOptions.RequireSsl = true, " +
"but the current request is not an SSL request.", "but the current request is not an SSL request.",
ex.Message); ex.Message);
} }
@ -56,7 +56,7 @@ namespace Microsoft.AspNet.Mvc.Core.Test
mockHttpContext.Setup(o => o.Request.IsSecure) mockHttpContext.Setup(o => o.Request.IsSecure)
.Returns(false); .Returns(false);
var config = new MockAntiForgeryConfig() var config = new AntiForgeryOptions()
{ {
RequireSSL = true RequireSSL = true
}; };
@ -72,7 +72,7 @@ namespace Microsoft.AspNet.Mvc.Core.Test
var ex = Assert.Throws<InvalidOperationException>( var ex = Assert.Throws<InvalidOperationException>(
() => worker.Validate(mockHttpContext.Object, cookieToken: null, formToken: null)); () => worker.Validate(mockHttpContext.Object, cookieToken: null, formToken: null));
Assert.Equal( Assert.Equal(
@"The anti-forgery system has the configuration value AntiForgeryConfig.RequireSsl = true, " + @"The anti-forgery system has the configuration value AntiForgeryOptions.RequireSsl = true, " +
"but the current request is not an SSL request.", "but the current request is not an SSL request.",
ex.Message); ex.Message);
} }
@ -85,7 +85,7 @@ namespace Microsoft.AspNet.Mvc.Core.Test
mockHttpContext.Setup(o => o.Request.IsSecure) mockHttpContext.Setup(o => o.Request.IsSecure)
.Returns(false); .Returns(false);
var config = new MockAntiForgeryConfig() var config = new AntiForgeryOptions()
{ {
RequireSSL = true RequireSSL = true
}; };
@ -100,7 +100,7 @@ namespace Microsoft.AspNet.Mvc.Core.Test
// Act & assert // Act & assert
var ex = Assert.Throws<InvalidOperationException>(() => worker.GetFormInputElement(mockHttpContext.Object)); var ex = Assert.Throws<InvalidOperationException>(() => worker.GetFormInputElement(mockHttpContext.Object));
Assert.Equal( Assert.Equal(
@"The anti-forgery system has the configuration value AntiForgeryConfig.RequireSsl = true, " + @"The anti-forgery system has the configuration value AntiForgeryOptions.RequireSsl = true, " +
"but the current request is not an SSL request.", "but the current request is not an SSL request.",
ex.Message); ex.Message);
} }
@ -113,7 +113,7 @@ namespace Microsoft.AspNet.Mvc.Core.Test
mockHttpContext.Setup(o => o.Request.IsSecure) mockHttpContext.Setup(o => o.Request.IsSecure)
.Returns(false); .Returns(false);
var config = new MockAntiForgeryConfig() var config = new AntiForgeryOptions()
{ {
RequireSSL = true RequireSSL = true
}; };
@ -128,7 +128,7 @@ namespace Microsoft.AspNet.Mvc.Core.Test
// Act & assert // Act & assert
var ex = Assert.Throws<InvalidOperationException>(() => worker.GetTokens(mockHttpContext.Object, "cookie-token")); var ex = Assert.Throws<InvalidOperationException>(() => worker.GetTokens(mockHttpContext.Object, "cookie-token"));
Assert.Equal( Assert.Equal(
@"The anti-forgery system has the configuration value AntiForgeryConfig.RequireSsl = true, " + @"The anti-forgery system has the configuration value AntiForgeryOptions.RequireSsl = true, " +
"but the current request is not an SSL request.", "but the current request is not an SSL request.",
ex.Message); ex.Message);
} }
@ -137,7 +137,7 @@ namespace Microsoft.AspNet.Mvc.Core.Test
public void GetFormInputElement_ExistingInvalidCookieToken_GeneratesANewCookieAndAnAntiForgeryToken() public void GetFormInputElement_ExistingInvalidCookieToken_GeneratesANewCookieAndAnAntiForgeryToken()
{ {
// Arrange // Arrange
var config = new MockAntiForgeryConfig() var config = new AntiForgeryOptions()
{ {
FormFieldName = "form-field-name" FormFieldName = "form-field-name"
}; };
@ -159,7 +159,7 @@ namespace Microsoft.AspNet.Mvc.Core.Test
public void GetFormInputElement_ExistingInvalidCookieToken_SwallowsExceptions() public void GetFormInputElement_ExistingInvalidCookieToken_SwallowsExceptions()
{ {
// Arrange // Arrange
var config = new MockAntiForgeryConfig() var config = new AntiForgeryOptions()
{ {
FormFieldName = "form-field-name" FormFieldName = "form-field-name"
}; };
@ -189,13 +189,13 @@ namespace Microsoft.AspNet.Mvc.Core.Test
public void GetFormInputElement_ExistingValidCookieToken_GeneratesAnAntiForgeryToken() public void GetFormInputElement_ExistingValidCookieToken_GeneratesAnAntiForgeryToken()
{ {
// Arrange // Arrange
var config = new MockAntiForgeryConfig() var options = new AntiForgeryOptions()
{ {
FormFieldName = "form-field-name" FormFieldName = "form-field-name"
}; };
// Make sure the existing cookie is valid and use the same cookie for the mock Token Provider. // Make sure the existing cookie is valid and use the same cookie for the mock Token Provider.
var context = GetAntiForgeryWorkerContext(config, useOldCookie: true, isOldCookieValid: true); var context = GetAntiForgeryWorkerContext(options, useOldCookie: true, isOldCookieValid: true);
var worker = GetAntiForgeryWorker(context); var worker = GetAntiForgeryWorker(context);
// Act // Act
@ -212,13 +212,13 @@ namespace Microsoft.AspNet.Mvc.Core.Test
public void GetFormInputElement_AddsXFrameOptionsHeader(bool suppressXFrameOptions, string expectedHeaderValue) public void GetFormInputElement_AddsXFrameOptionsHeader(bool suppressXFrameOptions, string expectedHeaderValue)
{ {
// Arrange // Arrange
var config = new MockAntiForgeryConfig() var options = new AntiForgeryOptions()
{ {
SuppressXFrameOptionsHeader = suppressXFrameOptions SuppressXFrameOptionsHeader = suppressXFrameOptions
}; };
// Genreate a new cookie. // Genreate a new cookie.
var context = GetAntiForgeryWorkerContext(config, useOldCookie: false, isOldCookieValid: false); var context = GetAntiForgeryWorkerContext(options, useOldCookie: false, isOldCookieValid: false);
var worker = GetAntiForgeryWorker(context); var worker = GetAntiForgeryWorker(context);
// Act // Act
@ -234,7 +234,7 @@ namespace Microsoft.AspNet.Mvc.Core.Test
{ {
// Arrange // Arrange
// Genreate a new cookie. // Genreate a new cookie.
var context = GetAntiForgeryWorkerContext(new MockAntiForgeryConfig(), useOldCookie: false, isOldCookieValid: false); var context = GetAntiForgeryWorkerContext(new AntiForgeryOptions(), useOldCookie: false, isOldCookieValid: false);
var worker = GetAntiForgeryWorker(context); var worker = GetAntiForgeryWorker(context);
// Act // Act
@ -250,7 +250,7 @@ namespace Microsoft.AspNet.Mvc.Core.Test
{ {
// Arrange // Arrange
// Make sure the existing cookie is invalid. // Make sure the existing cookie is invalid.
var context = GetAntiForgeryWorkerContext(new MockAntiForgeryConfig(), useOldCookie: false, isOldCookieValid: false); var context = GetAntiForgeryWorkerContext(new AntiForgeryOptions(), useOldCookie: false, isOldCookieValid: false);
// This will cause the cookieToken to be null. // This will cause the cookieToken to be null.
context.TokenSerializer.Setup(o => o.Deserialize("serialized-old-cookie-token")) context.TokenSerializer.Setup(o => o.Deserialize("serialized-old-cookie-token"))
@ -273,7 +273,7 @@ namespace Microsoft.AspNet.Mvc.Core.Test
public void GetTokens_ExistingValidCookieToken_GeneratesANewFormToken() public void GetTokens_ExistingValidCookieToken_GeneratesANewFormToken()
{ {
// Arrange // Arrange
var context = GetAntiForgeryWorkerContext(new MockAntiForgeryConfig(), useOldCookie: true, isOldCookieValid: true); var context = GetAntiForgeryWorkerContext(new AntiForgeryOptions(), useOldCookie: true, isOldCookieValid: true);
context.TokenStore = null; context.TokenStore = null;
var worker = GetAntiForgeryWorker(context); var worker = GetAntiForgeryWorker(context);
@ -289,7 +289,7 @@ namespace Microsoft.AspNet.Mvc.Core.Test
public void Validate_FromInvalidStrings_Throws() public void Validate_FromInvalidStrings_Throws()
{ {
// Arrange // Arrange
var context = GetAntiForgeryWorkerContext(new MockAntiForgeryConfig()); var context = GetAntiForgeryWorkerContext(new AntiForgeryOptions());
context.TokenSerializer.Setup(o => o.Deserialize("cookie-token")) context.TokenSerializer.Setup(o => o.Deserialize("cookie-token"))
.Returns(context.TestTokenSet.OldCookieToken); .Returns(context.TestTokenSet.OldCookieToken);
@ -315,7 +315,7 @@ namespace Microsoft.AspNet.Mvc.Core.Test
public void Validate_FromValidStrings_TokensValidatedSuccessfully() public void Validate_FromValidStrings_TokensValidatedSuccessfully()
{ {
// Arrange // Arrange
var context = GetAntiForgeryWorkerContext(new MockAntiForgeryConfig()); var context = GetAntiForgeryWorkerContext(new AntiForgeryOptions());
context.TokenSerializer.Setup(o => o.Deserialize("cookie-token")) context.TokenSerializer.Setup(o => o.Deserialize("cookie-token"))
.Returns(context.TestTokenSet.OldCookieToken); .Returns(context.TestTokenSet.OldCookieToken);
@ -341,7 +341,7 @@ namespace Microsoft.AspNet.Mvc.Core.Test
public async Task Validate_FromStore_Failure() public async Task Validate_FromStore_Failure()
{ {
// Arrange // Arrange
var context = GetAntiForgeryWorkerContext(new MockAntiForgeryConfig()); var context = GetAntiForgeryWorkerContext(new AntiForgeryOptions());
context.TokenProvider.Setup(o => o.ValidateTokens( context.TokenProvider.Setup(o => o.ValidateTokens(
context.HttpContext.Object, context.HttpContext.Object,
@ -363,7 +363,7 @@ namespace Microsoft.AspNet.Mvc.Core.Test
public async Task Validate_FromStore_Success() public async Task Validate_FromStore_Success()
{ {
// Arrange // Arrange
var context = GetAntiForgeryWorkerContext(new MockAntiForgeryConfig()); var context = GetAntiForgeryWorkerContext(new AntiForgeryOptions());
context.TokenProvider.Setup(o => o.ValidateTokens( context.TokenProvider.Setup(o => o.ValidateTokens(
context.HttpContext.Object, context.HttpContext.Object,
@ -383,7 +383,7 @@ namespace Microsoft.AspNet.Mvc.Core.Test
private AntiForgeryWorker GetAntiForgeryWorker(AntiForgeryWorkerContext context) private AntiForgeryWorker GetAntiForgeryWorker(AntiForgeryWorkerContext context)
{ {
return new AntiForgeryWorker( return new AntiForgeryWorker(
config: context.Config, config: context.Options,
serializer: context.TokenSerializer != null ? context.TokenSerializer.Object : null, serializer: context.TokenSerializer != null ? context.TokenSerializer.Object : null,
tokenStore: context.TokenStore != null ? context.TokenStore.Object : null, tokenStore: context.TokenStore != null ? context.TokenStore.Object : null,
generator: context.TokenProvider != null ? context.TokenProvider.Object : null, generator: context.TokenProvider != null ? context.TokenProvider.Object : null,
@ -475,7 +475,7 @@ namespace Microsoft.AspNet.Mvc.Core.Test
}; };
} }
private AntiForgeryWorkerContext GetAntiForgeryWorkerContext(MockAntiForgeryConfig config, bool useOldCookie = false, bool isOldCookieValid = true) private AntiForgeryWorkerContext GetAntiForgeryWorkerContext(AntiForgeryOptions config, bool useOldCookie = false, bool isOldCookieValid = true)
{ {
// Arrange // Arrange
var mockHttpContext = GetHttpContext(); var mockHttpContext = GetHttpContext();
@ -488,7 +488,7 @@ namespace Microsoft.AspNet.Mvc.Core.Test
return new AntiForgeryWorkerContext() return new AntiForgeryWorkerContext()
{ {
Config = config, Options = config,
HttpContext = mockHttpContext, HttpContext = mockHttpContext,
TokenProvider = mockTokenProvider, TokenProvider = mockTokenProvider,
TokenSerializer = mockSerializer, TokenSerializer = mockSerializer,
@ -509,7 +509,7 @@ namespace Microsoft.AspNet.Mvc.Core.Test
private class AntiForgeryWorkerContext private class AntiForgeryWorkerContext
{ {
public MockAntiForgeryConfig Config { get; set; } public AntiForgeryOptions Options { get; set; }
public TestTokenSet TestTokenSet { get; set; } public TestTokenSet TestTokenSet { get; set; }

View File

@ -1,32 +0,0 @@
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
namespace Microsoft.AspNet.Mvc.Core.Test
{
public sealed class MockAntiForgeryConfig : IAntiForgeryConfig
{
public string CookieName
{
get;
set;
}
public string FormFieldName
{
get;
set;
}
public bool RequireSSL
{
get;
set;
}
public bool SuppressXFrameOptionsHeader
{
get;
set;
}
}
}

View File

@ -39,7 +39,7 @@ namespace Microsoft.AspNet.Mvc.Core.Test
mockIdentity.Setup(o => o.IsAuthenticated) mockIdentity.Setup(o => o.IsAuthenticated)
.Returns(false); .Returns(false);
IAntiForgeryConfig config = new MockAntiForgeryConfig(); var config = new AntiForgeryOptions();
var tokenProvider = new TokenProvider( var tokenProvider = new TokenProvider(
config: config, config: config,
@ -69,7 +69,7 @@ namespace Microsoft.AspNet.Mvc.Core.Test
var httpContext = new Mock<HttpContext>().Object; var httpContext = new Mock<HttpContext>().Object;
ClaimsIdentity identity = new MyAuthenticatedIdentityWithoutUsername(); ClaimsIdentity identity = new MyAuthenticatedIdentityWithoutUsername();
IAntiForgeryConfig config = new MockAntiForgeryConfig(); var config = new AntiForgeryOptions();
IClaimUidExtractor claimUidExtractor = new Mock<IClaimUidExtractor>().Object; IClaimUidExtractor claimUidExtractor = new Mock<IClaimUidExtractor>().Object;
var tokenProvider = new TokenProvider( var tokenProvider = new TokenProvider(
@ -104,7 +104,7 @@ namespace Microsoft.AspNet.Mvc.Core.Test
mockAdditionalDataProvider.Setup(o => o.GetAdditionalData(httpContext)) mockAdditionalDataProvider.Setup(o => o.GetAdditionalData(httpContext))
.Returns("additional-data"); .Returns("additional-data");
IAntiForgeryConfig config = new AntiForgeryConfigWrapper(); var config = new AntiForgeryOptions();
IClaimUidExtractor claimUidExtractor = new Mock<IClaimUidExtractor>().Object; IClaimUidExtractor claimUidExtractor = new Mock<IClaimUidExtractor>().Object;
var tokenProvider = new TokenProvider( var tokenProvider = new TokenProvider(
@ -132,7 +132,7 @@ namespace Microsoft.AspNet.Mvc.Core.Test
var httpContext = new Mock<HttpContext>().Object; var httpContext = new Mock<HttpContext>().Object;
ClaimsIdentity identity = new GenericIdentity("some-identity"); ClaimsIdentity identity = new GenericIdentity("some-identity");
var config = new MockAntiForgeryConfig(); var config = new AntiForgeryOptions();
byte[] data = new byte[256 / 8]; byte[] data = new byte[256 / 8];
CryptRand.FillBuffer(new ArraySegment<byte>(data)); CryptRand.FillBuffer(new ArraySegment<byte>(data));
@ -173,7 +173,7 @@ namespace Microsoft.AspNet.Mvc.Core.Test
mockIdentity.Setup(o => o.Name) mockIdentity.Setup(o => o.Name)
.Returns("my-username"); .Returns("my-username");
IAntiForgeryConfig config = new MockAntiForgeryConfig(); var config = new AntiForgeryOptions();
IClaimUidExtractor claimUidExtractor = new Mock<IClaimUidExtractor>().Object; IClaimUidExtractor claimUidExtractor = new Mock<IClaimUidExtractor>().Object;
var tokenProvider = new TokenProvider( var tokenProvider = new TokenProvider(
@ -261,7 +261,7 @@ namespace Microsoft.AspNet.Mvc.Core.Test
AntiForgeryToken sessionToken = null; AntiForgeryToken sessionToken = null;
var fieldtoken = new AntiForgeryToken() { IsSessionToken = false }; var fieldtoken = new AntiForgeryToken() { IsSessionToken = false };
var config = new MockAntiForgeryConfig() var config = new AntiForgeryOptions()
{ {
CookieName = "my-cookie-name" CookieName = "my-cookie-name"
}; };
@ -286,7 +286,7 @@ namespace Microsoft.AspNet.Mvc.Core.Test
var sessionToken = new AntiForgeryToken() { IsSessionToken = true }; var sessionToken = new AntiForgeryToken() { IsSessionToken = true };
AntiForgeryToken fieldtoken = null; AntiForgeryToken fieldtoken = null;
var config = new MockAntiForgeryConfig() var config = new AntiForgeryOptions()
{ {
FormFieldName = "my-form-field-name" FormFieldName = "my-form-field-name"
}; };
@ -312,7 +312,7 @@ namespace Microsoft.AspNet.Mvc.Core.Test
var sessionToken = new AntiForgeryToken() { IsSessionToken = true }; var sessionToken = new AntiForgeryToken() { IsSessionToken = true };
var fieldtoken = new AntiForgeryToken() { IsSessionToken = false }; var fieldtoken = new AntiForgeryToken() { IsSessionToken = false };
var config = new MockAntiForgeryConfig() var config = new AntiForgeryOptions()
{ {
CookieName = "my-cookie-name", CookieName = "my-cookie-name",
FormFieldName = "my-form-field-name" FormFieldName = "my-form-field-name"
@ -449,7 +449,7 @@ namespace Microsoft.AspNet.Mvc.Core.Test
mockAdditionalDataProvider.Setup(o => o.ValidateAdditionalData(httpContext, "some-additional-data")) mockAdditionalDataProvider.Setup(o => o.ValidateAdditionalData(httpContext, "some-additional-data"))
.Returns(false); .Returns(false);
var config = new MockAntiForgeryConfig(); var config = new AntiForgeryOptions();
var tokenProvider = new TokenProvider( var tokenProvider = new TokenProvider(
config: config, config: config,
claimUidExtractor: null, claimUidExtractor: null,
@ -481,7 +481,7 @@ namespace Microsoft.AspNet.Mvc.Core.Test
mockAdditionalDataProvider.Setup(o => o.ValidateAdditionalData(httpContext, "some-additional-data")) mockAdditionalDataProvider.Setup(o => o.ValidateAdditionalData(httpContext, "some-additional-data"))
.Returns(true); .Returns(true);
var config = new MockAntiForgeryConfig(); var config = new AntiForgeryOptions();
var tokenProvider = new TokenProvider( var tokenProvider = new TokenProvider(
config: config, config: config,
claimUidExtractor: null, claimUidExtractor: null,
@ -513,7 +513,7 @@ namespace Microsoft.AspNet.Mvc.Core.Test
mockAdditionalDataProvider.Setup(o => o.ValidateAdditionalData(httpContext, "some-additional-data")) mockAdditionalDataProvider.Setup(o => o.ValidateAdditionalData(httpContext, "some-additional-data"))
.Returns(true); .Returns(true);
var config = new MockAntiForgeryConfig(); var config = new AntiForgeryOptions();
var tokenProvider = new TokenProvider( var tokenProvider = new TokenProvider(
config: config, config: config,
claimUidExtractor: new Mock<IClaimUidExtractor>().Object, claimUidExtractor: new Mock<IClaimUidExtractor>().Object,
@ -544,7 +544,7 @@ namespace Microsoft.AspNet.Mvc.Core.Test
mockClaimUidExtractor.Setup(o => o.ExtractClaimUid(identity)) mockClaimUidExtractor.Setup(o => o.ExtractClaimUid(identity))
.Returns(Convert.ToBase64String(fieldtoken.ClaimUid.GetData())); .Returns(Convert.ToBase64String(fieldtoken.ClaimUid.GetData()));
var config = new MockAntiForgeryConfig(); var config = new AntiForgeryOptions();
var tokenProvider = new TokenProvider( var tokenProvider = new TokenProvider(
config: config, config: config,

View File

@ -6,6 +6,7 @@ using Microsoft.Framework.DependencyInjection.Fallback;
using Microsoft.AspNet.Security.DataProtection; using Microsoft.AspNet.Security.DataProtection;
using Moq; using Moq;
using Xunit; using Xunit;
using Microsoft.Framework.OptionsModel;
namespace Microsoft.AspNet.Mvc.Core.Test namespace Microsoft.AspNet.Mvc.Core.Test
{ {
@ -33,9 +34,12 @@ namespace Microsoft.AspNet.Mvc.Core.Test
var claimExtractor = new Mock<IClaimUidExtractor>(); var claimExtractor = new Mock<IClaimUidExtractor>();
var dataProtectionProvider = new Mock<IDataProtectionProvider>(); var dataProtectionProvider = new Mock<IDataProtectionProvider>();
var additionalDataProvider = new Mock<IAntiForgeryAdditionalDataProvider>(); var additionalDataProvider = new Mock<IAntiForgeryAdditionalDataProvider>();
var optionsAccessor = new Mock<IOptionsAccessor<MvcOptions>>();
optionsAccessor.SetupGet(o => o.Options).Returns(new MvcOptions());
return new AntiForgery(claimExtractor.Object, return new AntiForgery(claimExtractor.Object,
dataProtectionProvider.Object, dataProtectionProvider.Object,
additionalDataProvider.Object); additionalDataProvider.Object,
optionsAccessor.Object);
} }
} }
} }

View File

@ -29,6 +29,8 @@
<Compile Include="ActionResults\RedirectToRouteResultTest.cs" /> <Compile Include="ActionResults\RedirectToRouteResultTest.cs" />
<Compile Include="ActionResults\RedirectResultTest.cs" /> <Compile Include="ActionResults\RedirectResultTest.cs" />
<Compile Include="ActionSelectionConventionTests.cs" /> <Compile Include="ActionSelectionConventionTests.cs" />
<Compile Include="AntiXsrf\AntiForgeryOptionsTests.cs" />
<Compile Include="MvcOptionsTests.cs" />
<Compile Include="AntiXsrf\AntiForgeryTokenSerializerTest.cs" /> <Compile Include="AntiXsrf\AntiForgeryTokenSerializerTest.cs" />
<Compile Include="AntiXsrf\ITokenProvider.cs" /> <Compile Include="AntiXsrf\ITokenProvider.cs" />
<Compile Include="AntiXsrf\ValidateAntiForgeryTokenAttributeTest.cs" /> <Compile Include="AntiXsrf\ValidateAntiForgeryTokenAttributeTest.cs" />
@ -39,7 +41,6 @@
<Compile Include="AntiXsrf\AntiForgeryWorkerTests.cs" /> <Compile Include="AntiXsrf\AntiForgeryWorkerTests.cs" />
<Compile Include="AntiXsrf\BinaryBlobTest.cs" /> <Compile Include="AntiXsrf\BinaryBlobTest.cs" />
<Compile Include="AntiXsrf\ClaimUidExtractorTest.cs" /> <Compile Include="AntiXsrf\ClaimUidExtractorTest.cs" />
<Compile Include="AntiXsrf\MockAntiForgeryConfig.cs" />
<Compile Include="AntiXsrf\MockClaimsIdentity.cs" /> <Compile Include="AntiXsrf\MockClaimsIdentity.cs" />
<Compile Include="AntiXsrf\TokenProviderTests.cs" /> <Compile Include="AntiXsrf\TokenProviderTests.cs" />
<Compile Include="ControllerTests.cs" /> <Compile Include="ControllerTests.cs" />

View File

@ -0,0 +1,23 @@
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using Xunit;
namespace Microsoft.AspNet.Mvc.Core.Test
{
public class MvcOptionsTests
{
[Fact]
public void AntiForgeryOptions_SettingNullValue_Throws()
{
// Arrange
var options = new MvcOptions();
// Act & Assert
var ex = Assert.Throws<ArgumentNullException>(() => options.AntiForgeryOptions = null);
Assert.Equal("The 'AntiForgeryOptions' property of 'Microsoft.AspNet.Mvc.MvcOptions' must not be null." +
"\r\nParameter name: value", ex.Message);
}
}
}