Add an IAntiforgery interface and simplify API

This commit is contained in:
Ryan Nowak 2015-06-24 15:52:39 -07:00
parent 9eeb1de68f
commit b3e92da7d8
13 changed files with 237 additions and 168 deletions

View File

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

View File

@ -15,7 +15,7 @@ namespace Microsoft.AspNet.Antiforgery
/// Provides access to the anti-forgery system, which provides protection against /// Provides access to the anti-forgery system, which provides protection against
/// Cross-site Request Forgery (XSRF, also called CSRF) attacks. /// Cross-site Request Forgery (XSRF, also called CSRF) attacks.
/// </summary> /// </summary>
public class Antiforgery public class DefaultAntiforgery : IAntiforgery
{ {
private readonly IHtmlEncoder _htmlEncoder; private readonly IHtmlEncoder _htmlEncoder;
private readonly AntiforgeryOptions _options; private readonly AntiforgeryOptions _options;
@ -23,7 +23,7 @@ namespace Microsoft.AspNet.Antiforgery
private readonly IAntiforgeryTokenSerializer _tokenSerializer; private readonly IAntiforgeryTokenSerializer _tokenSerializer;
private readonly IAntiforgeryTokenStore _tokenStore; private readonly IAntiforgeryTokenStore _tokenStore;
public Antiforgery( public DefaultAntiforgery(
IOptions<AntiforgeryOptions> antiforgeryOptionsAccessor, IOptions<AntiforgeryOptions> antiforgeryOptionsAccessor,
IAntiforgeryTokenGenerator tokenGenerator, IAntiforgeryTokenGenerator tokenGenerator,
IAntiforgeryTokenSerializer tokenSerializer, IAntiforgeryTokenSerializer tokenSerializer,
@ -37,74 +37,42 @@ namespace Microsoft.AspNet.Antiforgery
_htmlEncoder = htmlEncoder; _htmlEncoder = htmlEncoder;
} }
/// <summary> /// <inheritdoc />
/// 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>
public string GetHtml([NotNull] HttpContext context) public string GetHtml([NotNull] HttpContext context)
{ {
CheckSSLConfig(context); CheckSSLConfig(context);
var cookieToken = GetCookieTokenDoesNotThrow(context); var tokenSet = GetAndStoreTokens(context);
var tokenSet = GetTokens(context, cookieToken);
cookieToken = tokenSet.CookieToken;
var formToken = tokenSet.FormToken;
SaveCookieTokenAndHeader(context, cookieToken);
var inputTag = string.Format( var inputTag = string.Format(
"<input name=\"{0}\" type=\"{1}\" value=\"{2}\" />", "<input name=\"{0}\" type=\"{1}\" value=\"{2}\" />",
_htmlEncoder.HtmlEncode(_options.FormFieldName), _htmlEncoder.HtmlEncode(_options.FormFieldName),
_htmlEncoder.HtmlEncode("hidden"), _htmlEncoder.HtmlEncode("hidden"),
_htmlEncoder.HtmlEncode(_tokenSerializer.Serialize(formToken))); _htmlEncoder.HtmlEncode(tokenSet.FormToken));
return inputTag; return inputTag;
} }
/// <summary> /// <inheritdoc />
/// Generates an anti-forgery token pair (cookie and form token) for this request. public AntiforgeryTokenSet GetAndStoreTokens([NotNull] HttpContext context)
/// 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)
{ {
// 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); CheckSSLConfig(context);
var deserializedcookieToken = DeserializeTokenDoesNotThrow(oldCookieToken); var tokenSet = GetTokensInternal(context);
var tokenSet = GetTokens(context, deserializedcookieToken); SaveCookieTokenAndHeader(context, tokenSet.CookieToken);
return Serialize(tokenSet);
var serializedCookieToken = Serialize(tokenSet.CookieToken);
var serializedFormToken = Serialize(tokenSet.FormToken);
return new AntiforgeryTokenSet(serializedFormToken, serializedCookieToken);
} }
/// <summary> /// <inheritdoc />
/// Validates an anti-forgery token that was supplied for this request. public AntiforgeryTokenSet GetTokens([NotNull] HttpContext context)
/// The anti-forgery token may be generated by calling GetHtml(HttpContext context). {
/// </summary> CheckSSLConfig(context);
/// <param name="context">The HTTP context associated with the current call.</param>
public async Task ValidateAsync([NotNull] HttpContext context) var tokenSet = GetTokensInternal(context);
return Serialize(tokenSet);
}
/// <inheritdoc />
public async Task ValidateRequestAsync([NotNull] HttpContext context)
{ {
CheckSSLConfig(context); CheckSSLConfig(context);
@ -116,19 +84,14 @@ namespace Microsoft.AspNet.Antiforgery
_tokenGenerator.ValidateTokens(context, cookieToken, formToken); _tokenGenerator.ValidateTokens(context, cookieToken, formToken);
} }
/// <summary> /// <inheritdoc />
/// Validates an anti-forgery token pair that was generated by the GetTokens method. public void ValidateTokens([NotNull] HttpContext context, AntiforgeryTokenSet antiforgeryTokenSet)
/// </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)
{ {
CheckSSLConfig(context); CheckSSLConfig(context);
// Extract cookie & form tokens // Extract cookie & form tokens
var deserializedCookieToken = DeserializeToken(cookieToken); var deserializedCookieToken = DeserializeToken(antiforgeryTokenSet.CookieToken);
var deserializedFormToken = DeserializeToken(formToken); var deserializedFormToken = DeserializeToken(antiforgeryTokenSet.FormToken);
// Validate // Validate
_tokenGenerator.ValidateTokens( _tokenGenerator.ValidateTokens(
@ -137,28 +100,13 @@ namespace Microsoft.AspNet.Antiforgery
deserializedFormToken); deserializedFormToken);
} }
/// <summary> /// <inheritdoc />
/// 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>
public void SetCookieTokenAndHeader([NotNull] HttpContext context) public void SetCookieTokenAndHeader([NotNull] HttpContext context)
{ {
CheckSSLConfig(context); CheckSSLConfig(context);
var cookieToken = GetCookieTokenDoesNotThrow(context); var cookieToken = GetCookieTokenDoesNotThrow(context);
cookieToken = ValidateAndGenerateNewCookieToken(cookieToken); cookieToken = ValidateAndGenerateNewCookieToken(cookieToken);
SaveCookieTokenAndHeader(context, cookieToken); SaveCookieTokenAndHeader(context, cookieToken);
} }
@ -177,13 +125,13 @@ namespace Microsoft.AspNet.Antiforgery
} }
private void SaveCookieTokenAndHeader( private void SaveCookieTokenAndHeader(
[NotNull] HttpContext httpContext, [NotNull] HttpContext context,
AntiforgeryToken cookieToken) AntiforgeryToken cookieToken)
{ {
if (cookieToken != null) if (cookieToken != null)
{ {
// Persist the new cookie if it is not null. // Persist the new cookie if it is not null.
_tokenStore.SaveCookieToken(httpContext, cookieToken); _tokenStore.SaveCookieToken(context, cookieToken);
} }
if (!_options.SuppressXFrameOptionsHeader) if (!_options.SuppressXFrameOptionsHeader)
@ -191,13 +139,13 @@ namespace Microsoft.AspNet.Antiforgery
// Adding X-Frame-Options header to prevent ClickJacking. See // Adding X-Frame-Options header to prevent ClickJacking. See
// http://tools.ietf.org/html/draft-ietf-websec-x-frame-options-10 // http://tools.ietf.org/html/draft-ietf-websec-x-frame-options-10
// for more information. // 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); 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 try
{ {
return _tokenStore.GetCookieToken(httpContext); return _tokenStore.GetCookieToken(context);
} }
catch 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); var newCookieToken = ValidateAndGenerateNewCookieToken(cookieToken);
if (newCookieToken != null) if (newCookieToken != null)
{ {
cookieToken = newCookieToken; cookieToken = newCookieToken;
} }
var formToken = _tokenGenerator.GenerateFormToken( var formToken = _tokenGenerator.GenerateFormToken(
httpContext, context,
cookieToken); cookieToken);
return new AntiforgeryTokenSetInternal() 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 private class AntiforgeryTokenSetInternal

View File

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

View File

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

View File

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

View File

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

View File

@ -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);
}
}

View File

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

View File

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

View File

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

View File

@ -11,7 +11,7 @@ using Xunit;
namespace Microsoft.AspNet.Antiforgery namespace Microsoft.AspNet.Antiforgery
{ {
public class AntiforgeryTokenSerializerTest public class DefaultAntiforgeryTokenSerializerTest
{ {
private static readonly Mock<IDataProtectionProvider> _dataProtector = GetDataProtector(); 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 }); 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) public void Deserialize_BadToken_Throws(string serializedToken)
{ {
// Arrange // Arrange
var testSerializer = new AntiforgeryTokenSerializer(_dataProtector.Object); var testSerializer = new DefaultAntiforgeryTokenSerializer(_dataProtector.Object);
// Act & assert // Act & assert
var ex = Assert.Throws<InvalidOperationException>(() => testSerializer.Deserialize(serializedToken)); var ex = Assert.Throws<InvalidOperationException>(() => testSerializer.Deserialize(serializedToken));
@ -57,7 +57,7 @@ namespace Microsoft.AspNet.Antiforgery
public void Serialize_FieldToken_WithClaimUid_TokenRoundTripSuccessful() public void Serialize_FieldToken_WithClaimUid_TokenRoundTripSuccessful()
{ {
// Arrange // Arrange
var testSerializer = new AntiforgeryTokenSerializer(_dataProtector.Object); var testSerializer = new DefaultAntiforgeryTokenSerializer(_dataProtector.Object);
//"01" // Version //"01" // Version
//+ "705EEDCC7D42F1D6B3B98A593625BB4C" // SecurityToken //+ "705EEDCC7D42F1D6B3B98A593625BB4C" // SecurityToken
@ -87,7 +87,7 @@ namespace Microsoft.AspNet.Antiforgery
public void Serialize_FieldToken_WithUsername_TokenRoundTripSuccessful() public void Serialize_FieldToken_WithUsername_TokenRoundTripSuccessful()
{ {
// Arrange // Arrange
var testSerializer = new AntiforgeryTokenSerializer(_dataProtector.Object); var testSerializer = new DefaultAntiforgeryTokenSerializer(_dataProtector.Object);
//"01" // Version //"01" // Version
//+ "705EEDCC7D42F1D6B3B98A593625BB4C" // SecurityToken //+ "705EEDCC7D42F1D6B3B98A593625BB4C" // SecurityToken
@ -118,7 +118,7 @@ namespace Microsoft.AspNet.Antiforgery
public void Serialize_SessionToken_TokenRoundTripSuccessful() public void Serialize_SessionToken_TokenRoundTripSuccessful()
{ {
// Arrange // Arrange
var testSerializer = new AntiforgeryTokenSerializer(_dataProtector.Object); var testSerializer = new DefaultAntiforgeryTokenSerializer(_dataProtector.Object);
//"01" // Version //"01" // Version
//+ "705EEDCC7D42F1D6B3B98A593625BB4C" // SecurityToken //+ "705EEDCC7D42F1D6B3B98A593625BB4C" // SecurityToken

View File

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

View File

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