Fix aspnet/Mvc#2749 - fail gracefully with non-form content

This change will report a more specific error when antiforgery is used
with non-form content than "invalid content type".
This commit is contained in:
unknown 2015-08-06 10:29:16 -07:00
Родитель 9bcecf3994
Коммит b922d816be
2 изменённых файлов: 42 добавлений и 0 удалений

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

@ -53,6 +53,14 @@ namespace Microsoft.AspNet.Antiforgery
Resources.FormatAntiforgery_CookieToken_MustBeProvided(_options.CookieName));
}
if (!httpContext.Request.HasFormContentType)
{
// Check the content-type before accessing the form collection to make sure
// we throw gracefully.
throw new InvalidOperationException(
Resources.FormatAntiforgery_FormToken_MustBeProvided(_options.FormFieldName));
}
var form = await httpContext.Request.ReadFormAsync();
var formField = form[_options.FormFieldName];
if (string.IsNullOrEmpty(formField))

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

@ -186,11 +186,44 @@ namespace Microsoft.AspNet.Antiforgery
Assert.Equal("The required antiforgery cookie \"cookie-name\" is not present.", exception.Message);
}
[Fact]
public async Task GetRequestTokens_NonFormContentType_Throws()
{
// Arrange
var httpContext = new DefaultHttpContext();
httpContext.Request.ContentType = "application/json";
// Will not be accessed
httpContext.Request.Form = null;
httpContext.Request.Cookies = new ReadableStringCollection(new Dictionary<string, string[]>()
{
{ "cookie-name", new string[] { "cookie-value" } },
});
var options = new AntiforgeryOptions()
{
CookieName = "cookie-name",
FormFieldName = "form-field-name",
};
var tokenStore = new DefaultAntiforgeryTokenStore(
optionsAccessor: new TestOptionsManager(options),
tokenSerializer: null);
// Act
var exception = await Assert.ThrowsAsync<InvalidOperationException>(
async () => await tokenStore.GetRequestTokensAsync(httpContext));
// Assert
Assert.Equal("The required antiforgery form field \"form-field-name\" is not present.", exception.Message);
}
[Fact]
public async Task GetRequestTokens_FormFieldIsEmpty_Throws()
{
// Arrange
var httpContext = new DefaultHttpContext();
httpContext.Request.ContentType = "application/x-www-form-urlencoded";
httpContext.Request.Form = new FormCollection(new Dictionary<string, string[]>());
httpContext.Request.Cookies = new ReadableStringCollection(new Dictionary<string, string[]>()
{
@ -220,6 +253,7 @@ namespace Microsoft.AspNet.Antiforgery
{
// Arrange
var httpContext = new DefaultHttpContext();
httpContext.Request.ContentType = "application/x-www-form-urlencoded";
httpContext.Request.Form = new FormCollection(new Dictionary<string, string[]>()
{
{ "form-field-name", new string[] { "form-value" } },