Add an IAntiforgery interface and simplify API

This commit is contained in:
Ryan Nowak 2015-06-24 15:52:39 -07:00
Родитель 9eeb1de68f
Коммит b3e92da7d8
13 изменённых файлов: 237 добавлений и 168 удалений

Просмотреть файл

@ -11,13 +11,13 @@ namespace AntiforgerySample
{
public class FormPostSampleMiddleware
{
private readonly Antiforgery _antiforgery;
private readonly IAntiforgery _antiforgery;
private readonly AntiforgeryOptions _options;
private readonly RequestDelegate _next;
public FormPostSampleMiddleware(
RequestDelegate next,
Antiforgery antiforgery,
IAntiforgery antiforgery,
IOptions<AntiforgeryOptions> options)
{
_next = next;
@ -39,20 +39,19 @@ namespace AntiforgerySample
</body>
</html>";
var tokenSet = _antiforgery.GetTokens(context, oldCookieToken: null);
context.Response.Cookies.Delete(_options.CookieName);
context.Response.Cookies.Append(_options.CookieName, tokenSet.CookieToken);
var tokenSet = _antiforgery.GetAndStoreTokens(context);
await context.Response.WriteAsync(string.Format(page, _options.FormFieldName, tokenSet.FormToken));
}
else if (context.Request.Method == "POST")
{
// This will throw if invalid.
await _antiforgery.ValidateAsync(context);
await _antiforgery.ValidateRequestAsync(context);
var page =
@"<html>
<body>
<h1>Everything is fine</h1>
<h2><a href=""/"">Try Again</a></h2>
</form>
</body>
</html>";

Просмотреть файл

@ -15,7 +15,7 @@ namespace Microsoft.AspNet.Antiforgery
/// Provides access to the anti-forgery system, which provides protection against
/// Cross-site Request Forgery (XSRF, also called CSRF) attacks.
/// </summary>
public class Antiforgery
public class DefaultAntiforgery : IAntiforgery
{
private readonly IHtmlEncoder _htmlEncoder;
private readonly AntiforgeryOptions _options;
@ -23,7 +23,7 @@ namespace Microsoft.AspNet.Antiforgery
private readonly IAntiforgeryTokenSerializer _tokenSerializer;
private readonly IAntiforgeryTokenStore _tokenStore;
public Antiforgery(
public DefaultAntiforgery(
IOptions<AntiforgeryOptions> antiforgeryOptionsAccessor,
IAntiforgeryTokenGenerator tokenGenerator,
IAntiforgeryTokenSerializer tokenSerializer,
@ -37,74 +37,42 @@ namespace Microsoft.AspNet.Antiforgery
_htmlEncoder = htmlEncoder;
}
/// <summary>
/// Generates an anti-forgery token for this request. This token can
/// be validated by calling the Validate() method.
/// </summary>
/// <param name="context">The HTTP context associated with the current call.</param>
/// <returns>An HTML string corresponding to an &lt;input type="hidden"&gt;
/// element. This element should be put inside a &lt;form&gt;.</returns>
/// <remarks>
/// This method has a side effect:
/// A response cookie is set if there is no valid cookie associated with the request.
/// </remarks>
/// <inheritdoc />
public string GetHtml([NotNull] HttpContext context)
{
CheckSSLConfig(context);
var cookieToken = GetCookieTokenDoesNotThrow(context);
var tokenSet = GetTokens(context, cookieToken);
cookieToken = tokenSet.CookieToken;
var formToken = tokenSet.FormToken;
SaveCookieTokenAndHeader(context, cookieToken);
var tokenSet = GetAndStoreTokens(context);
var inputTag = string.Format(
"<input name=\"{0}\" type=\"{1}\" value=\"{2}\" />",
_htmlEncoder.HtmlEncode(_options.FormFieldName),
_htmlEncoder.HtmlEncode("hidden"),
_htmlEncoder.HtmlEncode(_tokenSerializer.Serialize(formToken)));
_htmlEncoder.HtmlEncode(tokenSet.FormToken));
return inputTag;
}
/// <summary>
/// Generates an anti-forgery token pair (cookie and form token) for this request.
/// This method is similar to GetHtml(HttpContext context), but this method gives the caller control
/// over how to persist the returned values. To validate these tokens, call the
/// appropriate overload of Validate.
/// </summary>
/// <param name="context">The HTTP context associated with the current call.</param>
/// <param name="oldCookieToken">The anti-forgery token - if any - that already existed
/// for this request. May be null. The anti-forgery system will try to reuse this cookie
/// value when generating a matching form token.</param>
/// <remarks>
/// Unlike the GetHtml(HttpContext context) method, this method has no side effect. The caller
/// is responsible for setting the response cookie and injecting the returned
/// form token as appropriate.
/// </remarks>
public AntiforgeryTokenSet GetTokens([NotNull] HttpContext context, string oldCookieToken)
/// <inheritdoc />
public AntiforgeryTokenSet GetAndStoreTokens([NotNull] HttpContext context)
{
// Will contain a new cookie value if the old cookie token
// was null or invalid. If this value is non-null when the method completes, the caller
// must persist this value in the form of a response cookie, and the existing cookie value
// should be discarded. If this value is null when the method completes, the existing
// cookie value was valid and needn't be modified.
CheckSSLConfig(context);
var deserializedcookieToken = DeserializeTokenDoesNotThrow(oldCookieToken);
var tokenSet = GetTokens(context, deserializedcookieToken);
var serializedCookieToken = Serialize(tokenSet.CookieToken);
var serializedFormToken = Serialize(tokenSet.FormToken);
return new AntiforgeryTokenSet(serializedFormToken, serializedCookieToken);
var tokenSet = GetTokensInternal(context);
SaveCookieTokenAndHeader(context, tokenSet.CookieToken);
return Serialize(tokenSet);
}
/// <summary>
/// Validates an anti-forgery token that was supplied for this request.
/// The anti-forgery token may be generated by calling GetHtml(HttpContext context).
/// </summary>
/// <param name="context">The HTTP context associated with the current call.</param>
public async Task ValidateAsync([NotNull] HttpContext context)
/// <inheritdoc />
public AntiforgeryTokenSet GetTokens([NotNull] HttpContext context)
{
CheckSSLConfig(context);
var tokenSet = GetTokensInternal(context);
return Serialize(tokenSet);
}
/// <inheritdoc />
public async Task ValidateRequestAsync([NotNull] HttpContext context)
{
CheckSSLConfig(context);
@ -116,19 +84,14 @@ namespace Microsoft.AspNet.Antiforgery
_tokenGenerator.ValidateTokens(context, cookieToken, formToken);
}
/// <summary>
/// Validates an anti-forgery token pair that was generated by the GetTokens method.
/// </summary>
/// <param name="context">The HTTP context associated with the current call.</param>
/// <param name="cookieToken">The token that was supplied in the request cookie.</param>
/// <param name="formToken">The token that was supplied in the request form body.</param>
public void Validate([NotNull] HttpContext context, string cookieToken, string formToken)
/// <inheritdoc />
public void ValidateTokens([NotNull] HttpContext context, AntiforgeryTokenSet antiforgeryTokenSet)
{
CheckSSLConfig(context);
// Extract cookie & form tokens
var deserializedCookieToken = DeserializeToken(cookieToken);
var deserializedFormToken = DeserializeToken(formToken);
var deserializedCookieToken = DeserializeToken(antiforgeryTokenSet.CookieToken);
var deserializedFormToken = DeserializeToken(antiforgeryTokenSet.FormToken);
// Validate
_tokenGenerator.ValidateTokens(
@ -137,28 +100,13 @@ namespace Microsoft.AspNet.Antiforgery
deserializedFormToken);
}
/// <summary>
/// Validates an anti-forgery token pair that was generated by the GetTokens method.
/// </summary>
/// <param name="context">The HTTP context associated with the current call.</param>
/// <param name="AntiforgeryTokenSet">The anti-forgery token pair (cookie and form token) for this request.
/// </param>
public void Validate([NotNull] HttpContext context, AntiforgeryTokenSet AntiforgeryTokenSet)
{
Validate(context, AntiforgeryTokenSet.CookieToken, AntiforgeryTokenSet.FormToken);
}
/// <summary>
/// Generates and sets an anti-forgery cookie if one is not available or not valid. Also sets response headers.
/// </summary>
/// <param name="context">The HTTP context associated with the current call.</param>
/// <inheritdoc />
public void SetCookieTokenAndHeader([NotNull] HttpContext context)
{
CheckSSLConfig(context);
var cookieToken = GetCookieTokenDoesNotThrow(context);
cookieToken = ValidateAndGenerateNewCookieToken(cookieToken);
SaveCookieTokenAndHeader(context, cookieToken);
}
@ -177,13 +125,13 @@ namespace Microsoft.AspNet.Antiforgery
}
private void SaveCookieTokenAndHeader(
[NotNull] HttpContext httpContext,
[NotNull] HttpContext context,
AntiforgeryToken cookieToken)
{
if (cookieToken != null)
{
// Persist the new cookie if it is not null.
_tokenStore.SaveCookieToken(httpContext, cookieToken);
_tokenStore.SaveCookieToken(context, cookieToken);
}
if (!_options.SuppressXFrameOptionsHeader)
@ -191,13 +139,13 @@ namespace Microsoft.AspNet.Antiforgery
// Adding X-Frame-Options header to prevent ClickJacking. See
// http://tools.ietf.org/html/draft-ietf-websec-x-frame-options-10
// for more information.
httpContext.Response.Headers.Set("X-Frame-Options", "SAMEORIGIN");
context.Response.Headers.Set("X-Frame-Options", "SAMEORIGIN");
}
}
private void CheckSSLConfig(HttpContext httpContext)
private void CheckSSLConfig(HttpContext context)
{
if (_options.RequireSSL && !httpContext.Request.IsHttps)
if (_options.RequireSSL && !context.Request.IsHttps)
{
throw new InvalidOperationException(Resources.AntiforgeryWorker_RequireSSL);
}
@ -223,11 +171,11 @@ namespace Microsoft.AspNet.Antiforgery
}
}
private AntiforgeryToken GetCookieTokenDoesNotThrow(HttpContext httpContext)
private AntiforgeryToken GetCookieTokenDoesNotThrow(HttpContext context)
{
try
{
return _tokenStore.GetCookieToken(httpContext);
return _tokenStore.GetCookieToken(context);
}
catch
{
@ -236,15 +184,16 @@ namespace Microsoft.AspNet.Antiforgery
}
}
private AntiforgeryTokenSetInternal GetTokens(HttpContext httpContext, AntiforgeryToken cookieToken)
private AntiforgeryTokenSetInternal GetTokensInternal(HttpContext context)
{
var cookieToken = GetCookieTokenDoesNotThrow(context);
var newCookieToken = ValidateAndGenerateNewCookieToken(cookieToken);
if (newCookieToken != null)
{
cookieToken = newCookieToken;
}
var formToken = _tokenGenerator.GenerateFormToken(
httpContext,
context,
cookieToken);
return new AntiforgeryTokenSetInternal()
@ -255,9 +204,11 @@ namespace Microsoft.AspNet.Antiforgery
};
}
private string Serialize(AntiforgeryToken token)
private AntiforgeryTokenSet Serialize(AntiforgeryTokenSetInternal tokenSet)
{
return (token != null) ? _tokenSerializer.Serialize(token) : null;
return new AntiforgeryTokenSet(
tokenSet.FormToken != null ? _tokenSerializer.Serialize(tokenSet.FormToken) : null,
tokenSet.CookieToken != null ? _tokenSerializer.Serialize(tokenSet.CookieToken) : null);
}
private class AntiforgeryTokenSetInternal

Просмотреть файл

@ -3,7 +3,7 @@
namespace Microsoft.AspNet.Antiforgery
{
public class AntiforgeryContextAccessor : IAntiforgeryContextAccessor
public class DefaultAntiforgeryContextAccessor : IAntiforgeryContextAccessor
{
public AntiforgeryContext Value { get; set; }
}

Просмотреть файл

@ -9,13 +9,13 @@ using Microsoft.Framework.OptionsModel;
namespace Microsoft.AspNet.Antiforgery
{
public class AntiforgeryTokenGenerator : IAntiforgeryTokenGenerator
public class DefaultAntiforgeryTokenGenerator : IAntiforgeryTokenGenerator
{
private readonly IClaimUidExtractor _claimUidExtractor;
private readonly AntiforgeryOptions _options;
private readonly IAntiforgeryAdditionalDataProvider _additionalDataProvider;
public AntiforgeryTokenGenerator(
public DefaultAntiforgeryTokenGenerator(
IOptions<AntiforgeryOptions> optionsAccessor,
IClaimUidExtractor claimUidExtractor,
IAntiforgeryAdditionalDataProvider additionalDataProvider)

Просмотреть файл

@ -9,14 +9,14 @@ using Microsoft.Framework.Internal;
namespace Microsoft.AspNet.Antiforgery
{
public class AntiforgeryTokenSerializer : IAntiforgeryTokenSerializer
public class DefaultAntiforgeryTokenSerializer : IAntiforgeryTokenSerializer
{
private static readonly string Purpose = "Microsoft.AspNet.Antiforgery.AntiforgeryToken.v1";
private readonly IDataProtector _cryptoSystem;
private const byte TokenVersion = 0x01;
public AntiforgeryTokenSerializer([NotNull] IDataProtectionProvider provider)
public DefaultAntiforgeryTokenSerializer([NotNull] IDataProtectionProvider provider)
{
_cryptoSystem = provider.CreateProtector(Purpose);
}

Просмотреть файл

@ -11,12 +11,12 @@ using Microsoft.Framework.OptionsModel;
namespace Microsoft.AspNet.Antiforgery
{
// Saves anti-XSRF tokens split between HttpRequest.Cookies and HttpRequest.Form
public class AntiforgeryTokenStore : IAntiforgeryTokenStore
public class DefaultAntiforgeryTokenStore : IAntiforgeryTokenStore
{
private readonly AntiforgeryOptions _options;
private readonly IAntiforgeryTokenSerializer _tokenSerializer;
public AntiforgeryTokenStore(
public DefaultAntiforgeryTokenStore(
[NotNull] IOptions<AntiforgeryOptions> optionsAccessor,
[NotNull] IAntiforgeryTokenSerializer tokenSerializer)
{

Просмотреть файл

@ -0,0 +1,74 @@
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Threading.Tasks;
using Microsoft.AspNet.Http;
using Microsoft.Framework.Internal;
namespace Microsoft.AspNet.Antiforgery
{
/// <summary>
/// Provides access to the antiforgery system, which provides protection against
/// Cross-site Request Forgery (XSRF, also called CSRF) attacks.
/// </summary>
public interface IAntiforgery
{
/// <summary>
/// Generates an input field for an antiforgery token.
/// </summary>
/// <param name="context">The <see cref="HttpContext"/> associated with the current call.</param>
/// <returns>
/// A string containing an &lt;input type="hidden"&gt; element. This element should be put inside
/// a &lt;form&gt;.
/// </returns>
/// <remarks>
/// This method has a side effect:
/// A response cookie is set if there is no valid cookie associated with the request.
/// </remarks>
string GetHtml([NotNull] HttpContext context);
/// <summary>
/// Generates an <see cref="AntiforgeryTokenSet"/> for this request and stores the cookie token
/// in the response.
/// </summary>
/// <param name="context">The <see cref="HttpContext"/> associated with the current call.</param>
/// <returns>An <see cref="AntiforgeryTokenSet" /> with tokens for the response.</returns>
/// <remarks>
/// This method has a side effect:
/// A response cookie is set if there is no valid cookie associated with the request.
/// </remarks>
AntiforgeryTokenSet GetAndStoreTokens([NotNull] HttpContext context);
/// <summary>
/// Generates an <see cref="AntiforgeryTokenSet"/> for this request.
/// </summary>
/// <param name="context">The <see cref="HttpContext"/> associated with the current call.</param>
/// <remarks>
/// Unlike <see cref="GetAndStoreTokens(HttpContext)"/>, this method has no side effect. The caller
/// is responsible for setting the response cookie and injecting the returned
/// form token as appropriate.
/// </remarks>
AntiforgeryTokenSet GetTokens([NotNull] HttpContext context);
/// <summary>
/// Validates an antiforgery token that was supplied as part of the request.
/// </summary>
/// <param name="context">The <see cref="HttpContext"/> associated with the current call.</param>
Task ValidateRequestAsync([NotNull] HttpContext context);
/// <summary>
/// Validates an <see cref="AntiforgeryTokenSet"/> for the current request.
/// </summary>
/// <param name="context">The <see cref="HttpContext"/> associated with the current call.</param>
/// <param name="antiforgeryTokenSet">
/// The <see cref="AntiforgeryTokenSet"/> (cookie and form token) for this request.
/// </param>
void ValidateTokens([NotNull] HttpContext context, AntiforgeryTokenSet antiforgeryTokenSet);
/// <summary>
/// Generates and stores an antiforgery cookie token if one is not available or not valid.
/// </summary>
/// <param name="context">The <see cref="HttpContext"/> associated with the current call.</param>
void SetCookieTokenAndHeader([NotNull] HttpContext context);
}
}

Просмотреть файл

@ -19,12 +19,12 @@ namespace Microsoft.Framework.DependencyInjection
services.TryAddEnumerable(
ServiceDescriptor.Transient<IConfigureOptions<AntiforgeryOptions>, AntiforgeryOptionsSetup>());
services.TryAddSingleton<IAntiforgeryTokenGenerator, AntiforgeryTokenGenerator>();
services.TryAddSingleton<IAntiforgeryTokenSerializer, AntiforgeryTokenSerializer>();
services.TryAddSingleton<IAntiforgeryTokenStore, AntiforgeryTokenStore>();
services.TryAddSingleton<IAntiforgery, DefaultAntiforgery>();
services.TryAddSingleton<IAntiforgeryTokenGenerator, DefaultAntiforgeryTokenGenerator>();
services.TryAddSingleton<IAntiforgeryTokenSerializer, DefaultAntiforgeryTokenSerializer>();
services.TryAddSingleton<IAntiforgeryTokenStore, DefaultAntiforgeryTokenStore>();
services.TryAddSingleton<IClaimUidExtractor, DefaultClaimUidExtractor>();
services.TryAddSingleton<Antiforgery, Antiforgery>();
services.TryAddScoped<IAntiforgeryContextAccessor, AntiforgeryContextAccessor>();
services.TryAddScoped<IAntiforgeryContextAccessor, DefaultAntiforgeryContextAccessor>();
services.TryAddSingleton<IAntiforgeryAdditionalDataProvider, DefaultAntiforgeryAdditionalDataProvider>();
return services;
}

Просмотреть файл

@ -18,7 +18,7 @@ namespace Microsoft.AspNet.Antiforgery
public class AntiforgeryTest
{
[Fact]
public async Task ChecksSSL_ValidateAsync_Throws()
public async Task ChecksSSL_ValidateRequestAsync_Throws()
{
// Arrange
var httpContext = new DefaultHttpContext();
@ -32,7 +32,7 @@ namespace Microsoft.AspNet.Antiforgery
// Act & Assert
var exception = await Assert.ThrowsAsync<InvalidOperationException>(
async () => await antiforgery.ValidateAsync(httpContext));
async () => await antiforgery.ValidateRequestAsync(httpContext));
Assert.Equal(
@"The anti-forgery system has the configuration value AntiforgeryOptions.RequireSsl = true, " +
"but the current request is not an SSL request.",
@ -40,7 +40,7 @@ namespace Microsoft.AspNet.Antiforgery
}
[Fact]
public void ChecksSSL_Validate_Throws()
public void ChecksSSL_ValidateTokens_Throws()
{
// Arrange
var httpContext = new DefaultHttpContext();
@ -54,7 +54,7 @@ namespace Microsoft.AspNet.Antiforgery
// Act & Assert
var exception = Assert.Throws<InvalidOperationException>(
() => antiforgery.Validate(httpContext, cookieToken: null, formToken: null));
() => antiforgery.ValidateTokens(httpContext, new AntiforgeryTokenSet("hello", "world")));
Assert.Equal(
@"The anti-forgery system has the configuration value AntiforgeryOptions.RequireSsl = true, " +
"but the current request is not an SSL request.",
@ -83,6 +83,28 @@ namespace Microsoft.AspNet.Antiforgery
exception.Message);
}
[Fact]
public void ChecksSSL_GetAndStoreTokens_Throws()
{
// Arrange
var httpContext = new DefaultHttpContext();
var options = new AntiforgeryOptions()
{
RequireSSL = true
};
var antiforgery = GetAntiforgery(options);
// Act & Assert
var exception = Assert.Throws<InvalidOperationException>(
() => antiforgery.GetAndStoreTokens(httpContext));
Assert.Equal(
@"The anti-forgery system has the configuration value AntiforgeryOptions.RequireSsl = true, " +
"but the current request is not an SSL request.",
exception.Message);
}
[Fact]
public void ChecksSSL_GetTokens_Throws()
{
@ -98,7 +120,29 @@ namespace Microsoft.AspNet.Antiforgery
// Act & Assert
var exception = Assert.Throws<InvalidOperationException>(
() => antiforgery.GetTokens(httpContext, "dkfkfkf"));
() => antiforgery.GetTokens(httpContext));
Assert.Equal(
@"The anti-forgery system has the configuration value AntiforgeryOptions.RequireSsl = true, " +
"but the current request is not an SSL request.",
exception.Message);
}
[Fact]
public void ChecksSSL_SetCookieTokenAndHeader_Throws()
{
// Arrange
var httpContext = new DefaultHttpContext();
var options = new AntiforgeryOptions()
{
RequireSSL = true
};
var antiforgery = GetAntiforgery(options);
// Act & Assert
var exception = Assert.Throws<InvalidOperationException>(
() => antiforgery.SetCookieTokenAndHeader(httpContext));
Assert.Equal(
@"The anti-forgery system has the configuration value AntiforgeryOptions.RequireSsl = true, " +
"but the current request is not an SSL request.",
@ -108,7 +152,7 @@ namespace Microsoft.AspNet.Antiforgery
#if DNX451
[Fact]
public void GetFormInputElement_ExistingInvalidCookieToken_GeneratesANewCookieAndAnAntiforgeryToken()
public void GetHtml_ExistingInvalidCookieToken_GeneratesANewCookieAndAnAntiforgeryToken()
{
// Arrange
var options = new AntiforgeryOptions()
@ -132,7 +176,7 @@ namespace Microsoft.AspNet.Antiforgery
}
[Fact]
public void GetFormInputElement_ExistingInvalidCookieToken_SwallowsExceptions()
public void GetHtml_ExistingInvalidCookieToken_SwallowsExceptions()
{
// Arrange
var options = new AntiforgeryOptions()
@ -164,7 +208,7 @@ namespace Microsoft.AspNet.Antiforgery
}
[Fact]
public void GetFormInputElement_ExistingValidCookieToken_GeneratesAnAntiforgeryToken()
public void GetHtml_ExistingValidCookieToken_GeneratesAnAntiforgeryToken()
{
// Arrange
var options = new AntiforgeryOptions()
@ -189,7 +233,7 @@ namespace Microsoft.AspNet.Antiforgery
[Theory]
[InlineData(false, "SAMEORIGIN")]
[InlineData(true, null)]
public void GetFormInputElement_AddsXFrameOptionsHeader(bool suppressXFrameOptions, string expectedHeaderValue)
public void GetHtml_AddsXFrameOptionsHeader(bool suppressXFrameOptions, string expectedHeaderValue)
{
// Arrange
var options = new AntiforgeryOptions()
@ -221,7 +265,7 @@ namespace Microsoft.AspNet.Antiforgery
var antiforgery = GetAntiforgery(context);
// Act
var tokenset = antiforgery.GetTokens(context.HttpContext, "serialized-old-cookie-token");
var tokenset = antiforgery.GetTokens(context.HttpContext);
// Assert
Assert.Equal("serialized-new-cookie-token", tokenset.CookieToken);
@ -248,7 +292,7 @@ namespace Microsoft.AspNet.Antiforgery
var antiforgery = GetAntiforgery(context);
// Act
var tokenset = antiforgery.GetTokens(context.HttpContext, "serialized-old-cookie-token");
var tokenset = antiforgery.GetTokens(context.HttpContext);
// Assert
Assert.Equal("serialized-new-cookie-token", tokenset.CookieToken);
@ -263,11 +307,10 @@ namespace Microsoft.AspNet.Antiforgery
new AntiforgeryOptions(),
useOldCookie: true,
isOldCookieValid: true);
context.TokenStore = null;
var antiforgery = GetAntiforgery(context);
// Act
var tokenset = antiforgery.GetTokens(context.HttpContext, "serialized-old-cookie-token");
var tokenset = antiforgery.GetTokens(context.HttpContext);
// Assert
Assert.Null(tokenset.CookieToken);
@ -294,7 +337,9 @@ namespace Microsoft.AspNet.Antiforgery
// Act & assert
var exception = Assert.Throws<InvalidOperationException>(
() => antiforgery.Validate(context.HttpContext, "cookie-token", "form-token"));
() => antiforgery.ValidateTokens(
context.HttpContext,
new AntiforgeryTokenSet("form-token", "cookie-token")));
Assert.Equal("my-message", exception.Message);
}
@ -317,7 +362,7 @@ namespace Microsoft.AspNet.Antiforgery
var antiforgery = GetAntiforgery(context);
// Act
antiforgery.Validate(context.HttpContext, "cookie-token", "form-token");
antiforgery.ValidateTokens(context.HttpContext, new AntiforgeryTokenSet("form-token", "cookie-token"));
// Assert
context.TokenGenerator.Verify();
@ -338,7 +383,7 @@ namespace Microsoft.AspNet.Antiforgery
// Act & assert
var exception = await Assert.ThrowsAsync<InvalidOperationException>(
async () => await antiforgery.ValidateAsync(context.HttpContext));
async () => await antiforgery.ValidateRequestAsync(context.HttpContext));
Assert.Equal("my-message", exception.Message);
}
@ -356,7 +401,7 @@ namespace Microsoft.AspNet.Antiforgery
var antiforgery = GetAntiforgery(context);
// Act
await antiforgery.ValidateAsync(context.HttpContext);
await antiforgery.ValidateRequestAsync(context.HttpContext);
// Assert
context.TokenGenerator.Verify();
@ -389,7 +434,7 @@ namespace Microsoft.AspNet.Antiforgery
#endif
private Antiforgery GetAntiforgery(
private DefaultAntiforgery GetAntiforgery(
AntiforgeryOptions options = null,
IAntiforgeryTokenGenerator tokenGenerator = null,
IAntiforgeryTokenSerializer tokenSerializer = null,
@ -401,7 +446,7 @@ namespace Microsoft.AspNet.Antiforgery
optionsManager.Options = options;
}
return new Antiforgery(
return new DefaultAntiforgery(
antiforgeryOptionsAccessor: optionsManager,
tokenGenerator: tokenGenerator,
tokenSerializer: tokenSerializer,
@ -418,7 +463,7 @@ namespace Microsoft.AspNet.Antiforgery
#if DNX451
private Antiforgery GetAntiforgery(AntiforgeryMockContext context)
private DefaultAntiforgery GetAntiforgery(AntiforgeryMockContext context)
{
return GetAntiforgery(
context.Options,

Просмотреть файл

@ -12,13 +12,13 @@ using Xunit;
namespace Microsoft.AspNet.Antiforgery
{
public class AntiforgeryTokenGeneratorProviderTest
public class DefaultAntiforgeryTokenGeneratorProviderTest
{
[Fact]
public void GenerateCookieToken()
{
// Arrange
var tokenProvider = new AntiforgeryTokenGenerator(
var tokenProvider = new DefaultAntiforgeryTokenGenerator(
optionsAccessor: new TestOptionsManager(),
claimUidExtractor: null,
additionalDataProvider: null);
@ -39,7 +39,7 @@ namespace Microsoft.AspNet.Antiforgery
httpContext.User = new ClaimsPrincipal(new ClaimsIdentity());
Assert.False(httpContext.User.Identity.IsAuthenticated);
var tokenProvider = new AntiforgeryTokenGenerator(
var tokenProvider = new DefaultAntiforgeryTokenGenerator(
optionsAccessor: new TestOptionsManager(),
claimUidExtractor: null,
additionalDataProvider: null);
@ -73,7 +73,7 @@ namespace Microsoft.AspNet.Antiforgery
var options = new AntiforgeryOptions();
var claimUidExtractor = new Mock<IClaimUidExtractor>().Object;
var tokenProvider = new AntiforgeryTokenGenerator(
var tokenProvider = new DefaultAntiforgeryTokenGenerator(
optionsAccessor: new TestOptionsManager(),
claimUidExtractor: claimUidExtractor,
additionalDataProvider: null);
@ -107,7 +107,7 @@ namespace Microsoft.AspNet.Antiforgery
var claimUidExtractor = new Mock<IClaimUidExtractor>().Object;
var tokenProvider = new AntiforgeryTokenGenerator(
var tokenProvider = new DefaultAntiforgeryTokenGenerator(
optionsAccessor: new TestOptionsManager(),
claimUidExtractor: claimUidExtractor,
additionalDataProvider: mockAdditionalDataProvider.Object);
@ -146,7 +146,7 @@ namespace Microsoft.AspNet.Antiforgery
mockClaimUidExtractor.Setup(o => o.ExtractClaimUid(identity))
.Returns(base64ClaimUId);
var tokenProvider = new AntiforgeryTokenGenerator(
var tokenProvider = new DefaultAntiforgeryTokenGenerator(
optionsAccessor: new TestOptionsManager(),
claimUidExtractor: mockClaimUidExtractor.Object,
additionalDataProvider: null);
@ -180,7 +180,7 @@ namespace Microsoft.AspNet.Antiforgery
var claimUidExtractor = new Mock<IClaimUidExtractor>().Object;
var tokenProvider = new AntiforgeryTokenGenerator(
var tokenProvider = new DefaultAntiforgeryTokenGenerator(
optionsAccessor: new TestOptionsManager(),
claimUidExtractor: claimUidExtractor,
additionalDataProvider: null);
@ -207,7 +207,7 @@ namespace Microsoft.AspNet.Antiforgery
IsSessionToken = false
};
var tokenProvider = new AntiforgeryTokenGenerator(
var tokenProvider = new DefaultAntiforgeryTokenGenerator(
optionsAccessor: new TestOptionsManager(),
claimUidExtractor: null,
additionalDataProvider: null);
@ -224,7 +224,7 @@ namespace Microsoft.AspNet.Antiforgery
{
// Arrange
AntiforgeryToken cookieToken = null;
var tokenProvider = new AntiforgeryTokenGenerator(
var tokenProvider = new DefaultAntiforgeryTokenGenerator(
optionsAccessor: new TestOptionsManager(),
claimUidExtractor: null,
additionalDataProvider: null);
@ -245,7 +245,7 @@ namespace Microsoft.AspNet.Antiforgery
IsSessionToken = true
};
var tokenProvider = new AntiforgeryTokenGenerator(
var tokenProvider = new DefaultAntiforgeryTokenGenerator(
optionsAccessor: new TestOptionsManager(),
claimUidExtractor: null,
additionalDataProvider: null);
@ -272,7 +272,7 @@ namespace Microsoft.AspNet.Antiforgery
CookieName = "my-cookie-name"
};
var tokenProvider = new AntiforgeryTokenGenerator(
var tokenProvider = new DefaultAntiforgeryTokenGenerator(
optionsAccessor: new TestOptionsManager(options),
claimUidExtractor: null,
additionalDataProvider: null);
@ -298,7 +298,7 @@ namespace Microsoft.AspNet.Antiforgery
FormFieldName = "my-form-field-name"
};
var tokenProvider = new AntiforgeryTokenGenerator(
var tokenProvider = new DefaultAntiforgeryTokenGenerator(
optionsAccessor: new TestOptionsManager(options),
claimUidExtractor: null,
additionalDataProvider: null);
@ -326,7 +326,7 @@ namespace Microsoft.AspNet.Antiforgery
FormFieldName = "my-form-field-name"
};
var tokenProvider = new AntiforgeryTokenGenerator(
var tokenProvider = new DefaultAntiforgeryTokenGenerator(
optionsAccessor: new TestOptionsManager(options),
claimUidExtractor: null,
additionalDataProvider: null);
@ -359,7 +359,7 @@ namespace Microsoft.AspNet.Antiforgery
var sessionToken = new AntiforgeryToken() { IsSessionToken = true };
var fieldtoken = new AntiforgeryToken() { IsSessionToken = false };
var tokenProvider = new AntiforgeryTokenGenerator(
var tokenProvider = new DefaultAntiforgeryTokenGenerator(
optionsAccessor: new TestOptionsManager(),
claimUidExtractor: null,
additionalDataProvider: null);
@ -397,7 +397,7 @@ namespace Microsoft.AspNet.Antiforgery
mockClaimUidExtractor.Setup(o => o.ExtractClaimUid(identity))
.Returns((string)null);
var tokenProvider = new AntiforgeryTokenGenerator(
var tokenProvider = new DefaultAntiforgeryTokenGenerator(
optionsAccessor: new TestOptionsManager(),
claimUidExtractor: mockClaimUidExtractor.Object,
additionalDataProvider: null);
@ -432,7 +432,7 @@ namespace Microsoft.AspNet.Antiforgery
mockClaimUidExtractor.Setup(o => o.ExtractClaimUid(identity))
.Returns(Convert.ToBase64String(differentToken.GetData()));
var tokenProvider = new AntiforgeryTokenGenerator(
var tokenProvider = new DefaultAntiforgeryTokenGenerator(
optionsAccessor: new TestOptionsManager(),
claimUidExtractor: mockClaimUidExtractor.Object,
additionalDataProvider: null);
@ -466,7 +466,7 @@ namespace Microsoft.AspNet.Antiforgery
mockAdditionalDataProvider.Setup(o => o.ValidateAdditionalData(httpContext, "some-additional-data"))
.Returns(false);
var tokenProvider = new AntiforgeryTokenGenerator(
var tokenProvider = new DefaultAntiforgeryTokenGenerator(
optionsAccessor: new TestOptionsManager(),
claimUidExtractor: null,
additionalDataProvider: mockAdditionalDataProvider.Object);
@ -498,7 +498,7 @@ namespace Microsoft.AspNet.Antiforgery
mockAdditionalDataProvider.Setup(o => o.ValidateAdditionalData(httpContext, "some-additional-data"))
.Returns(true);
var tokenProvider = new AntiforgeryTokenGenerator(
var tokenProvider = new DefaultAntiforgeryTokenGenerator(
optionsAccessor: new TestOptionsManager(),
claimUidExtractor: null,
additionalDataProvider: mockAdditionalDataProvider.Object);
@ -531,7 +531,7 @@ namespace Microsoft.AspNet.Antiforgery
mockAdditionalDataProvider.Setup(o => o.ValidateAdditionalData(httpContext, "some-additional-data"))
.Returns(true);
var tokenProvider = new AntiforgeryTokenGenerator(
var tokenProvider = new DefaultAntiforgeryTokenGenerator(
optionsAccessor: new TestOptionsManager(),
claimUidExtractor: new Mock<IClaimUidExtractor>().Object,
additionalDataProvider: mockAdditionalDataProvider.Object);
@ -563,7 +563,7 @@ namespace Microsoft.AspNet.Antiforgery
mockClaimUidExtractor.Setup(o => o.ExtractClaimUid(identity))
.Returns(Convert.ToBase64String(fieldtoken.ClaimUid.GetData()));
var tokenProvider = new AntiforgeryTokenGenerator(
var tokenProvider = new DefaultAntiforgeryTokenGenerator(
optionsAccessor: new TestOptionsManager(),
claimUidExtractor: mockClaimUidExtractor.Object,
additionalDataProvider: null);

Просмотреть файл

@ -11,7 +11,7 @@ using Xunit;
namespace Microsoft.AspNet.Antiforgery
{
public class AntiforgeryTokenSerializerTest
public class DefaultAntiforgeryTokenSerializerTest
{
private static readonly Mock<IDataProtectionProvider> _dataProtector = GetDataProtector();
private static readonly BinaryBlob _claimUid = new BinaryBlob(256, new byte[] { 0x6F, 0x16, 0x48, 0xE9, 0x72, 0x49, 0xAA, 0x58, 0x75, 0x40, 0x36, 0xA6, 0x7E, 0x24, 0x8C, 0xF0, 0x44, 0xF0, 0x7E, 0xCF, 0xB0, 0xED, 0x38, 0x75, 0x56, 0xCE, 0x02, 0x9A, 0x4F, 0x9A, 0x40, 0xE0 });
@ -46,7 +46,7 @@ namespace Microsoft.AspNet.Antiforgery
public void Deserialize_BadToken_Throws(string serializedToken)
{
// Arrange
var testSerializer = new AntiforgeryTokenSerializer(_dataProtector.Object);
var testSerializer = new DefaultAntiforgeryTokenSerializer(_dataProtector.Object);
// Act & assert
var ex = Assert.Throws<InvalidOperationException>(() => testSerializer.Deserialize(serializedToken));
@ -57,7 +57,7 @@ namespace Microsoft.AspNet.Antiforgery
public void Serialize_FieldToken_WithClaimUid_TokenRoundTripSuccessful()
{
// Arrange
var testSerializer = new AntiforgeryTokenSerializer(_dataProtector.Object);
var testSerializer = new DefaultAntiforgeryTokenSerializer(_dataProtector.Object);
//"01" // Version
//+ "705EEDCC7D42F1D6B3B98A593625BB4C" // SecurityToken
@ -87,7 +87,7 @@ namespace Microsoft.AspNet.Antiforgery
public void Serialize_FieldToken_WithUsername_TokenRoundTripSuccessful()
{
// Arrange
var testSerializer = new AntiforgeryTokenSerializer(_dataProtector.Object);
var testSerializer = new DefaultAntiforgeryTokenSerializer(_dataProtector.Object);
//"01" // Version
//+ "705EEDCC7D42F1D6B3B98A593625BB4C" // SecurityToken
@ -118,7 +118,7 @@ namespace Microsoft.AspNet.Antiforgery
public void Serialize_SessionToken_TokenRoundTripSuccessful()
{
// Arrange
var testSerializer = new AntiforgeryTokenSerializer(_dataProtector.Object);
var testSerializer = new DefaultAntiforgeryTokenSerializer(_dataProtector.Object);
//"01" // Version
//+ "705EEDCC7D42F1D6B3B98A593625BB4C" // SecurityToken

Просмотреть файл

@ -13,7 +13,7 @@ using Xunit;
namespace Microsoft.AspNet.Antiforgery
{
public class AntiforgeryTokenStoreTest
public class DefaultAntiforgeryTokenStoreTest
{
private readonly string _cookieName = "cookie-name";
@ -29,7 +29,7 @@ namespace Microsoft.AspNet.Antiforgery
mockHttpContext
.Setup(o => o.Request.Cookies)
.Returns(requestCookies.Object);
var contextAccessor = new AntiforgeryContextAccessor();
var contextAccessor = new DefaultAntiforgeryContextAccessor();
mockHttpContext.SetupGet(o => o.RequestServices)
.Returns(GetServiceProvider(contextAccessor));
var options = new AntiforgeryOptions()
@ -37,7 +37,7 @@ namespace Microsoft.AspNet.Antiforgery
CookieName = _cookieName
};
var tokenStore = new AntiforgeryTokenStore(
var tokenStore = new DefaultAntiforgeryTokenStore(
optionsAccessor: new TestOptionsManager(options),
tokenSerializer: null);
@ -60,7 +60,7 @@ namespace Microsoft.AspNet.Antiforgery
mockHttpContext
.Setup(o => o.Request.Cookies)
.Returns(requestCookies.Object);
var contextAccessor = new AntiforgeryContextAccessor();
var contextAccessor = new DefaultAntiforgeryContextAccessor();
mockHttpContext.SetupGet(o => o.RequestServices)
.Returns(GetServiceProvider(contextAccessor));
@ -72,7 +72,7 @@ namespace Microsoft.AspNet.Antiforgery
CookieName = _cookieName
};
var tokenStore = new AntiforgeryTokenStore(
var tokenStore = new DefaultAntiforgeryTokenStore(
optionsAccessor: new TestOptionsManager(options),
tokenSerializer: null);
@ -94,7 +94,7 @@ namespace Microsoft.AspNet.Antiforgery
CookieName = _cookieName
};
var tokenStore = new AntiforgeryTokenStore(
var tokenStore = new DefaultAntiforgeryTokenStore(
optionsAccessor: new TestOptionsManager(options),
tokenSerializer: null);
@ -122,7 +122,7 @@ namespace Microsoft.AspNet.Antiforgery
CookieName = _cookieName
};
var tokenStore = new AntiforgeryTokenStore(
var tokenStore = new DefaultAntiforgeryTokenStore(
optionsAccessor: new TestOptionsManager(options),
tokenSerializer: mockSerializer.Object);
@ -148,7 +148,7 @@ namespace Microsoft.AspNet.Antiforgery
CookieName = _cookieName
};
var tokenStore = new AntiforgeryTokenStore(
var tokenStore = new DefaultAntiforgeryTokenStore(
optionsAccessor: new TestOptionsManager(options),
tokenSerializer: mockSerializer.Object);
@ -177,7 +177,7 @@ namespace Microsoft.AspNet.Antiforgery
FormFieldName = "form-field-name",
};
var tokenStore = new AntiforgeryTokenStore(
var tokenStore = new DefaultAntiforgeryTokenStore(
optionsAccessor: new TestOptionsManager(options),
tokenSerializer: null);
@ -213,7 +213,7 @@ namespace Microsoft.AspNet.Antiforgery
FormFieldName = "form-field-name",
};
var tokenStore = new AntiforgeryTokenStore(
var tokenStore = new DefaultAntiforgeryTokenStore(
optionsAccessor: new TestOptionsManager(options),
tokenSerializer: mockSerializer.Object);
@ -248,7 +248,7 @@ namespace Microsoft.AspNet.Antiforgery
FormFieldName = "form-field-name",
};
var tokenStore = new AntiforgeryTokenStore(
var tokenStore = new DefaultAntiforgeryTokenStore(
optionsAccessor: new TestOptionsManager(options),
tokenSerializer: mockSerializer.Object);
@ -275,7 +275,7 @@ namespace Microsoft.AspNet.Antiforgery
var mockHttpContext = new Mock<HttpContext>();
mockHttpContext.Setup(o => o.Response.Cookies)
.Returns(cookies);
var contextAccessor = new AntiforgeryContextAccessor();
var contextAccessor = new DefaultAntiforgeryContextAccessor();
mockHttpContext.SetupGet(o => o.RequestServices)
.Returns(GetServiceProvider(contextAccessor));
@ -289,7 +289,7 @@ namespace Microsoft.AspNet.Antiforgery
RequireSSL = requireSsl
};
var tokenStore = new AntiforgeryTokenStore(
var tokenStore = new DefaultAntiforgeryTokenStore(
optionsAccessor: new TestOptionsManager(options),
tokenSerializer: mockSerializer.Object);
@ -317,7 +317,7 @@ namespace Microsoft.AspNet.Antiforgery
mockHttpContext.Setup(o => o.Request)
.Returns(request.Object);
var contextAccessor = new AntiforgeryContextAccessor();
var contextAccessor = new DefaultAntiforgeryContextAccessor();
mockHttpContext.SetupGet(o => o.RequestServices)
.Returns(GetServiceProvider(contextAccessor));

Просмотреть файл

@ -11,7 +11,7 @@ using Xunit;
namespace Microsoft.AspNet.Antiforgery
{
public class ClaimUidExtractorTest
public class DefaultClaimUidExtractorTest
{
[Fact]
public void ExtractClaimUid_NullIdentity()