@* validation summary tag helper will target just
elements and append the list of errors *@
@* - i.e. this helper, like
helper appends content. *@
diff --git a/samples/TagHelperSample.Web/Views/Movies/Index.cshtml b/samples/TagHelperSample.Web/Views/Movies/Index.cshtml
index b0ff77c174..5eda5ea485 100644
--- a/samples/TagHelperSample.Web/Views/Movies/Index.cshtml
+++ b/samples/TagHelperSample.Web/Views/Movies/Index.cshtml
@@ -23,12 +23,12 @@
Watch the greatest movies right here!
Submit your movie rankings:
-
-
diff --git a/src/Microsoft.AspNet.Mvc.Core/Properties/Resources.Designer.cs b/src/Microsoft.AspNet.Mvc.Core/Properties/Resources.Designer.cs
index 53b40d0931..5d5e703579 100644
--- a/src/Microsoft.AspNet.Mvc.Core/Properties/Resources.Designer.cs
+++ b/src/Microsoft.AspNet.Mvc.Core/Properties/Resources.Designer.cs
@@ -42,150 +42,6 @@ namespace Microsoft.AspNet.Mvc.Core
return string.Format(CultureInfo.CurrentCulture, GetString("ObjectResult_MatchAllContentType"), p0, p1);
}
- ///
- /// The provided anti-forgery token failed a custom data check.
- ///
- internal static string AntiForgeryToken_AdditionalDataCheckFailed
- {
- get { return GetString("AntiForgeryToken_AdditionalDataCheckFailed"); }
- }
-
- ///
- /// The provided anti-forgery token failed a custom data check.
- ///
- internal static string FormatAntiForgeryToken_AdditionalDataCheckFailed()
- {
- return GetString("AntiForgeryToken_AdditionalDataCheckFailed");
- }
-
- ///
- /// The provided anti-forgery token was meant for a different claims-based user than the current user.
- ///
- internal static string AntiForgeryToken_ClaimUidMismatch
- {
- get { return GetString("AntiForgeryToken_ClaimUidMismatch"); }
- }
-
- ///
- /// The provided anti-forgery token was meant for a different claims-based user than the current user.
- ///
- internal static string FormatAntiForgeryToken_ClaimUidMismatch()
- {
- return GetString("AntiForgeryToken_ClaimUidMismatch");
- }
-
- ///
- /// The required anti-forgery cookie "{0}" is not present.
- ///
- internal static string AntiForgeryToken_CookieMissing
- {
- get { return GetString("AntiForgeryToken_CookieMissing"); }
- }
-
- ///
- /// The required anti-forgery cookie "{0}" is not present.
- ///
- internal static string FormatAntiForgeryToken_CookieMissing(object p0)
- {
- return string.Format(CultureInfo.CurrentCulture, GetString("AntiForgeryToken_CookieMissing"), p0);
- }
-
- ///
- /// The anti-forgery token could not be decrypted.
- ///
- internal static string AntiForgeryToken_DeserializationFailed
- {
- get { return GetString("AntiForgeryToken_DeserializationFailed"); }
- }
-
- ///
- /// The anti-forgery token could not be decrypted.
- ///
- internal static string FormatAntiForgeryToken_DeserializationFailed()
- {
- return GetString("AntiForgeryToken_DeserializationFailed");
- }
-
- ///
- /// The required anti-forgery form field "{0}" is not present.
- ///
- internal static string AntiForgeryToken_FormFieldMissing
- {
- get { return GetString("AntiForgeryToken_FormFieldMissing"); }
- }
-
- ///
- /// The required anti-forgery form field "{0}" is not present.
- ///
- internal static string FormatAntiForgeryToken_FormFieldMissing(object p0)
- {
- return string.Format(CultureInfo.CurrentCulture, GetString("AntiForgeryToken_FormFieldMissing"), p0);
- }
-
- ///
- /// The anti-forgery cookie token and form field token do not match.
- ///
- internal static string AntiForgeryToken_SecurityTokenMismatch
- {
- get { return GetString("AntiForgeryToken_SecurityTokenMismatch"); }
- }
-
- ///
- /// The anti-forgery cookie token and form field token do not match.
- ///
- internal static string FormatAntiForgeryToken_SecurityTokenMismatch()
- {
- return GetString("AntiForgeryToken_SecurityTokenMismatch");
- }
-
- ///
- /// Validation of the provided anti-forgery token failed. The cookie "{0}" and the form field "{1}" were swapped.
- ///
- internal static string AntiForgeryToken_TokensSwapped
- {
- get { return GetString("AntiForgeryToken_TokensSwapped"); }
- }
-
- ///
- /// Validation of the provided anti-forgery token failed. The cookie "{0}" and the form field "{1}" were swapped.
- ///
- internal static string FormatAntiForgeryToken_TokensSwapped(object p0, object p1)
- {
- return string.Format(CultureInfo.CurrentCulture, GetString("AntiForgeryToken_TokensSwapped"), p0, p1);
- }
-
- ///
- /// The provided anti-forgery token was meant for user "{0}", but the current user is "{1}".
- ///
- internal static string AntiForgeryToken_UsernameMismatch
- {
- get { return GetString("AntiForgeryToken_UsernameMismatch"); }
- }
-
- ///
- /// The provided anti-forgery token was meant for user "{0}", but the current user is "{1}".
- ///
- internal static string FormatAntiForgeryToken_UsernameMismatch(object p0, object p1)
- {
- return string.Format(CultureInfo.CurrentCulture, GetString("AntiForgeryToken_UsernameMismatch"), p0, p1);
- }
-
- ///
- /// The anti-forgery system has the configuration value AntiForgeryOptions.RequireSsl = true, but the current request is not an SSL request.
- ///
- internal static string AntiForgeryWorker_RequireSSL
- {
- get { return GetString("AntiForgeryWorker_RequireSSL"); }
- }
-
- ///
- /// The anti-forgery system has the configuration value AntiForgeryOptions.RequireSsl = true, but the current request is not an SSL request.
- ///
- internal static string FormatAntiForgeryWorker_RequireSSL()
- {
- return GetString("AntiForgeryWorker_RequireSSL");
- }
-
///
/// 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.
///
@@ -234,22 +90,6 @@ namespace Microsoft.AspNet.Mvc.Core
return string.Format(CultureInfo.CurrentCulture, GetString("ClaimUidExtractor_ClaimNotPresent"), p0);
}
- ///
- /// The provided identity of type '{0}' is marked IsAuthenticated = true but does not have a value for Name. By default, the anti-forgery system requires that all authenticated identities have a unique Name. If it is not possible to provide a unique Name for this identity, consider extending IAdditionalDataProvider by overriding the DefaultAdditionalDataProvider or a custom type that can provide some form of unique identifier for the current user.
- ///
- internal static string TokenValidator_AuthenticatedUserWithoutUsername
- {
- get { return GetString("TokenValidator_AuthenticatedUserWithoutUsername"); }
- }
-
- ///
- /// The provided identity of type '{0}' is marked IsAuthenticated = true but does not have a value for Name. By default, the anti-forgery system requires that all authenticated identities have a unique Name. If it is not possible to provide a unique Name for this identity, consider extending IAdditionalDataProvider by overriding the DefaultAdditionalDataProvider or a custom type that can provide some form of unique identifier for the current user.
- ///
- internal static string FormatTokenValidator_AuthenticatedUserWithoutUsername(object p0)
- {
- return string.Format(CultureInfo.CurrentCulture, GetString("TokenValidator_AuthenticatedUserWithoutUsername"), p0);
- }
-
///
/// The class ReflectedActionFilterEndPoint only supports ReflectedActionDescriptors.
///
diff --git a/src/Microsoft.AspNet.Mvc.Core/Resources.resx b/src/Microsoft.AspNet.Mvc.Core/Resources.resx
index 6a17f8b56a..bf9e674308 100644
--- a/src/Microsoft.AspNet.Mvc.Core/Resources.resx
+++ b/src/Microsoft.AspNet.Mvc.Core/Resources.resx
@@ -1,17 +1,17 @@
-
@@ -123,33 +123,6 @@
The content-type '{0}' added in the '{1}' property is invalid. Media types which match all types or match all subtypes are not supported.
-
- The provided anti-forgery token failed a custom data check.
-
-
- The provided anti-forgery token was meant for a different claims-based user than the current user.
-
-
- The required anti-forgery cookie "{0}" is not present.
-
-
- The anti-forgery token could not be decrypted.
-
-
- The required anti-forgery form field "{0}" is not present.
-
-
- The anti-forgery cookie token and form field token do not match.
-
-
- Validation of the provided anti-forgery token failed. The cookie "{0}" and the form field "{1}" were swapped.
-
-
- The provided anti-forgery token was meant for user "{0}", but the current user is "{1}".
-
-
- The anti-forgery system has the configuration value AntiForgeryOptions.RequireSsl = true, but the current request is not an SSL request.
-
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.
@@ -159,9 +132,6 @@
A claim of type '{0}' was not present on the provided ClaimsIdentity.
-
- The provided identity of type '{0}' is marked IsAuthenticated = true but does not have a value for Name. By default, the anti-forgery system requires that all authenticated identities have a unique Name. If it is not possible to provide a unique Name for this identity, consider extending IAdditionalDataProvider by overriding the DefaultAdditionalDataProvider or a custom type that can provide some form of unique identifier for the current user.
-
The class ReflectedActionFilterEndPoint only supports ReflectedActionDescriptors.
diff --git a/src/Microsoft.AspNet.Mvc.Extensions/AntiForgery/AntiForgery.cs b/src/Microsoft.AspNet.Mvc.Extensions/AntiForgery/AntiForgery.cs
deleted file mode 100644
index 158169fd5e..0000000000
--- a/src/Microsoft.AspNet.Mvc.Extensions/AntiForgery/AntiForgery.cs
+++ /dev/null
@@ -1,138 +0,0 @@
-// 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;
-using System.Linq;
-using System.Security.Cryptography;
-using System.Text;
-using System.Threading.Tasks;
-using Microsoft.AspNet.DataProtection;
-using Microsoft.AspNet.Http;
-using Microsoft.AspNet.Mvc.Rendering;
-using Microsoft.AspNet.WebUtilities;
-using Microsoft.Framework.Internal;
-using Microsoft.Framework.OptionsModel;
-using Microsoft.Framework.WebEncoders;
-
-namespace Microsoft.AspNet.Mvc
-{
- ///
- /// Provides access to the anti-forgery system, which provides protection against
- /// Cross-site Request Forgery (XSRF, also called CSRF) attacks.
- ///
- public sealed class AntiForgery
- {
- private static readonly string _purpose = "Microsoft.AspNet.Mvc.AntiXsrf.AntiForgeryToken.v1";
- private readonly AntiForgeryWorker _worker;
-
- public AntiForgery([NotNull] IClaimUidExtractor claimUidExtractor,
- [NotNull] IDataProtectionProvider dataProtectionProvider,
- [NotNull] IAntiForgeryAdditionalDataProvider additionalDataProvider,
- [NotNull] IOptions antiforgeryOptions,
- [NotNull] IHtmlEncoder htmlEncoder,
- [NotNull] IOptions dataProtectionOptions)
- {
- var config = antiforgeryOptions.Options;
- var applicationId = dataProtectionOptions.Options.ApplicationDiscriminator ?? string.Empty;
- config.CookieName = config.CookieName ?? ComputeCookieName(applicationId);
-
- var serializer = new AntiForgeryTokenSerializer(dataProtectionProvider.CreateProtector(_purpose));
- var tokenStore = new AntiForgeryTokenStore(config, serializer);
- var tokenProvider = new AntiForgeryTokenProvider(config, claimUidExtractor, additionalDataProvider);
- _worker = new AntiForgeryWorker(serializer, config, tokenStore, tokenProvider, tokenProvider, htmlEncoder);
- }
-
- ///
- /// Generates an anti-forgery token for this request. This token can
- /// be validated by calling the Validate() method.
- ///
- /// The HTTP context associated with the current call.
- /// An HTML string corresponding to an <input type="hidden">
- /// element. This element should be put inside a <form>.
- ///
- /// This method has a side effect:
- /// A response cookie is set if there is no valid cookie associated with the request.
- ///
- public TagBuilder GetHtml([NotNull] HttpContext context)
- {
- var builder = _worker.GetFormInputElement(context);
- return builder;
- }
-
- ///
- /// 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.
- ///
- /// The HTTP context associated with the current call.
- /// 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.
- ///
- /// 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.
- ///
- 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.
- return _worker.GetTokens(context, oldCookieToken);
- }
-
- ///
- /// Validates an anti-forgery token that was supplied for this request.
- /// The anti-forgery token may be generated by calling GetHtml(HttpContext context).
- ///
- /// The HTTP context associated with the current call.
- public async Task ValidateAsync([NotNull] HttpContext context)
- {
- await _worker.ValidateAsync(context);
- }
-
- ///
- /// Validates an anti-forgery token pair that was generated by the GetTokens method.
- ///
- /// The HTTP context associated with the current call.
- /// The token that was supplied in the request cookie.
- /// The token that was supplied in the request form body.
- public void Validate([NotNull] HttpContext context, string cookieToken, string formToken)
- {
- _worker.Validate(context, cookieToken, formToken);
- }
-
- ///
- /// Validates an anti-forgery token pair that was generated by the GetTokens method.
- ///
- /// The HTTP context associated with the current call.
- /// The anti-forgery token pair (cookie and form token) for this request.
- ///
- public void Validate([NotNull] HttpContext context, AntiForgeryTokenSet antiForgeryTokenSet)
- {
- Validate(context, antiForgeryTokenSet.CookieToken, antiForgeryTokenSet.FormToken);
- }
-
- ///
- /// Generates and sets an anti-forgery cookie if one is not available or not valid. Also sets response headers.
- ///
- /// The HTTP context associated with the current call.
- public void SetCookieTokenAndHeader([NotNull] HttpContext context)
- {
- _worker.SetCookieTokenAndHeader(context);
- }
-
- private string ComputeCookieName(string applicationId)
- {
- using (var sha256 = SHA256.Create())
- {
- var hash = sha256.ComputeHash(Encoding.UTF8.GetBytes(applicationId));
- var subHash = hash.Take(8).ToArray();
- return WebEncoders.Base64UrlEncode(subHash);
- }
- }
- }
-}
\ No newline at end of file
diff --git a/src/Microsoft.AspNet.Mvc.Extensions/AntiForgery/AntiForgeryContext.cs b/src/Microsoft.AspNet.Mvc.Extensions/AntiForgery/AntiForgeryContext.cs
deleted file mode 100644
index fb3971eff8..0000000000
--- a/src/Microsoft.AspNet.Mvc.Extensions/AntiForgery/AntiForgeryContext.cs
+++ /dev/null
@@ -1,13 +0,0 @@
-// 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.
-
-namespace Microsoft.AspNet.Mvc
-{
- ///
- /// Used as a per request state.
- ///
- internal class AntiForgeryContext
- {
- public AntiForgeryToken CookieToken { get; set; }
- }
-}
\ No newline at end of file
diff --git a/src/Microsoft.AspNet.Mvc.Extensions/AntiForgery/AntiForgeryOptions.cs b/src/Microsoft.AspNet.Mvc.Extensions/AntiForgery/AntiForgeryOptions.cs
deleted file mode 100644
index 1d5ace92b8..0000000000
--- a/src/Microsoft.AspNet.Mvc.Extensions/AntiForgery/AntiForgeryOptions.cs
+++ /dev/null
@@ -1,96 +0,0 @@
-// 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;
-using Microsoft.AspNet.Mvc.Extensions;
-
-namespace Microsoft.AspNet.Mvc
-{
- ///
- /// Provides programmatic configuration for the anti-forgery token system.
- ///
- public class AntiForgeryOptions
- {
- private const string AntiForgeryTokenFieldName = "__RequestVerificationToken";
- private string _cookieName;
- private string _formFieldName = AntiForgeryTokenFieldName;
-
- public AntiForgeryOptions()
- {
- }
-
- ///
- /// Specifies the name of the cookie that is used by the anti-forgery
- /// system.
- ///
- ///
- /// If an explicit name is not provided, the system will automatically
- /// generate a name.
- ///
- public string CookieName
- {
- get
- {
- return _cookieName;
- }
-
- set
- {
- if (value == null)
- {
- throw new ArgumentNullException(nameof(value),
- Resources.FormatPropertyOfTypeCannotBeNull(
- nameof(CookieName), typeof(AntiForgeryOptions)));
- }
-
- _cookieName = value;
- }
- }
-
- ///
- /// Specifies the name of the anti-forgery token field that is used by the anti-forgery system.
- ///
- public string FormFieldName
- {
- get
- {
- return _formFieldName;
- }
-
- set
- {
- if (value == null)
- {
- throw new ArgumentNullException(nameof(value),
- Resources.FormatPropertyOfTypeCannotBeNull(
- nameof(FormFieldName), typeof(AntiForgeryOptions)));
- }
-
- _formFieldName = value;
- }
- }
-
- ///
- /// Specifies whether SSL is required for the anti-forgery system
- /// to operate. If this setting is 'true' and a non-SSL request
- /// comes into the system, all anti-forgery APIs will fail.
- ///
- public bool RequireSSL
- {
- get;
- set;
- }
-
- ///
- /// Specifies whether to suppress the generation of X-Frame-Options header
- /// which is used to prevent ClickJacking. By default, the X-Frame-Options
- /// header is generated with the value SAMEORIGIN. If this setting is 'true',
- /// the X-Frame-Options header will not be generated for the response.
- ///
- public bool SuppressXFrameOptionsHeader
- {
- get;
- set;
- }
- }
-}
\ No newline at end of file
diff --git a/src/Microsoft.AspNet.Mvc.Extensions/AntiForgery/AntiForgeryToken.cs b/src/Microsoft.AspNet.Mvc.Extensions/AntiForgery/AntiForgeryToken.cs
deleted file mode 100644
index e455b9a7da..0000000000
--- a/src/Microsoft.AspNet.Mvc.Extensions/AntiForgery/AntiForgeryToken.cs
+++ /dev/null
@@ -1,53 +0,0 @@
-// 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.
-
-namespace Microsoft.AspNet.Mvc
-{
- internal sealed class AntiForgeryToken
- {
- internal const int SecurityTokenBitLength = 128;
- internal const int ClaimUidBitLength = 256;
-
- private string _additionalData = string.Empty;
- private string _username = string.Empty;
- private BinaryBlob _securityToken;
-
- public string AdditionalData
- {
- get { return _additionalData; }
- set
- {
- _additionalData = value ?? string.Empty;
- }
- }
-
- public BinaryBlob ClaimUid { get; set; }
-
- public bool IsSessionToken { get; set; }
-
- public BinaryBlob SecurityToken
- {
- get
- {
- if (_securityToken == null)
- {
- _securityToken = new BinaryBlob(SecurityTokenBitLength);
- }
- return _securityToken;
- }
- set
- {
- _securityToken = value;
- }
- }
-
- public string Username
- {
- get { return _username; }
- set
- {
- _username = value ?? string.Empty;
- }
- }
- }
-}
\ No newline at end of file
diff --git a/src/Microsoft.AspNet.Mvc.Extensions/AntiForgery/AntiForgeryTokenProvider.cs b/src/Microsoft.AspNet.Mvc.Extensions/AntiForgery/AntiForgeryTokenProvider.cs
deleted file mode 100644
index fc0b92a18f..0000000000
--- a/src/Microsoft.AspNet.Mvc.Extensions/AntiForgery/AntiForgeryTokenProvider.cs
+++ /dev/null
@@ -1,168 +0,0 @@
-// 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;
-using System.Diagnostics;
-using System.Security.Claims;
-using Microsoft.AspNet.Http;
-using Microsoft.AspNet.Mvc.Extensions;
-
-namespace Microsoft.AspNet.Mvc
-{
- internal sealed class AntiForgeryTokenProvider : IAntiForgeryTokenValidator, IAntiForgeryTokenGenerator
- {
- private readonly IClaimUidExtractor _claimUidExtractor;
- private readonly AntiForgeryOptions _config;
- private readonly IAntiForgeryAdditionalDataProvider _additionalDataProvider;
-
- internal AntiForgeryTokenProvider(AntiForgeryOptions config,
- IClaimUidExtractor claimUidExtractor,
- IAntiForgeryAdditionalDataProvider additionalDataProvider)
- {
- _config = config;
- _claimUidExtractor = claimUidExtractor;
- _additionalDataProvider = additionalDataProvider;
- }
-
- public AntiForgeryToken GenerateCookieToken()
- {
- return new AntiForgeryToken()
- {
- // SecurityToken will be populated automatically.
- IsSessionToken = true
- };
- }
-
- public AntiForgeryToken GenerateFormToken(HttpContext httpContext,
- ClaimsIdentity identity,
- AntiForgeryToken cookieToken)
- {
- Debug.Assert(IsCookieTokenValid(cookieToken));
-
- var formToken = new AntiForgeryToken()
- {
- SecurityToken = cookieToken.SecurityToken,
- IsSessionToken = false
- };
-
- var isIdentityAuthenticated = false;
-
- // populate Username and ClaimUid
- if (identity != null && identity.IsAuthenticated)
- {
- isIdentityAuthenticated = true;
- formToken.ClaimUid = GetClaimUidBlob(_claimUidExtractor.ExtractClaimUid(identity));
- if (formToken.ClaimUid == null)
- {
- formToken.Username = identity.Name;
- }
- }
-
- // populate AdditionalData
- if (_additionalDataProvider != null)
- {
- formToken.AdditionalData = _additionalDataProvider.GetAdditionalData(httpContext);
- }
-
- if (isIdentityAuthenticated
- && string.IsNullOrEmpty(formToken.Username)
- && formToken.ClaimUid == null
- && string.IsNullOrEmpty(formToken.AdditionalData))
- {
- // Application says user is authenticated, but we have no identifier for the user.
- throw new InvalidOperationException(
- Resources.FormatTokenValidator_AuthenticatedUserWithoutUsername(identity.GetType()));
- }
-
- return formToken;
- }
-
- public bool IsCookieTokenValid(AntiForgeryToken cookieToken)
- {
- return (cookieToken != null && cookieToken.IsSessionToken);
- }
-
- public void ValidateTokens(
- HttpContext httpContext,
- ClaimsIdentity identity,
- AntiForgeryToken sessionToken,
- AntiForgeryToken fieldToken)
- {
- // Were the tokens even present at all?
- if (sessionToken == null)
- {
- throw new InvalidOperationException(
- Resources.FormatAntiForgeryToken_CookieMissing(_config.CookieName));
- }
- if (fieldToken == null)
- {
- throw new InvalidOperationException(
- Resources.FormatAntiForgeryToken_FormFieldMissing(_config.FormFieldName));
- }
-
- // Do the tokens have the correct format?
- if (!sessionToken.IsSessionToken || fieldToken.IsSessionToken)
- {
- throw new InvalidOperationException(
- Resources.FormatAntiForgeryToken_TokensSwapped(_config.CookieName, _config.FormFieldName));
- }
-
- // Are the security tokens embedded in each incoming token identical?
- if (!Equals(sessionToken.SecurityToken, fieldToken.SecurityToken))
- {
- throw new InvalidOperationException(Resources.AntiForgeryToken_SecurityTokenMismatch);
- }
-
- // Is the incoming token meant for the current user?
- var currentUsername = string.Empty;
- BinaryBlob currentClaimUid = null;
-
- if (identity != null && identity.IsAuthenticated)
- {
- currentClaimUid = GetClaimUidBlob(_claimUidExtractor.ExtractClaimUid(identity));
- if (currentClaimUid == null)
- {
- currentUsername = identity.Name ?? string.Empty;
- }
- }
-
- // OpenID and other similar authentication schemes use URIs for the username.
- // These should be treated as case-sensitive.
- var useCaseSensitiveUsernameComparison =
- currentUsername.StartsWith("http://", StringComparison.OrdinalIgnoreCase) ||
- currentUsername.StartsWith("https://", StringComparison.OrdinalIgnoreCase);
-
- if (!string.Equals(fieldToken.Username,
- currentUsername,
- (useCaseSensitiveUsernameComparison) ?
- StringComparison.Ordinal :
- StringComparison.OrdinalIgnoreCase))
- {
- throw new InvalidOperationException(
- Resources.FormatAntiForgeryToken_UsernameMismatch(fieldToken.Username, currentUsername));
- }
-
- if (!Equals(fieldToken.ClaimUid, currentClaimUid))
- {
- throw new InvalidOperationException(Resources.AntiForgeryToken_ClaimUidMismatch);
- }
-
- // Is the AdditionalData valid?
- if (_additionalDataProvider != null &&
- !_additionalDataProvider.ValidateAdditionalData(httpContext, fieldToken.AdditionalData))
- {
- throw new InvalidOperationException(Resources.AntiForgeryToken_AdditionalDataCheckFailed);
- }
- }
-
- private static BinaryBlob GetClaimUidBlob(string base64ClaimUid)
- {
- if (base64ClaimUid == null)
- {
- return null;
- }
-
- return new BinaryBlob(256, Convert.FromBase64String(base64ClaimUid));
- }
- }
-}
\ No newline at end of file
diff --git a/src/Microsoft.AspNet.Mvc.Extensions/AntiForgery/AntiForgeryTokenSerializer.cs b/src/Microsoft.AspNet.Mvc.Extensions/AntiForgery/AntiForgeryTokenSerializer.cs
deleted file mode 100644
index 660a0c242f..0000000000
--- a/src/Microsoft.AspNet.Mvc.Extensions/AntiForgery/AntiForgeryTokenSerializer.cs
+++ /dev/null
@@ -1,136 +0,0 @@
-// 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;
-using System.IO;
-using Microsoft.AspNet.DataProtection;
-using Microsoft.AspNet.Mvc.Extensions;
-using Microsoft.AspNet.WebUtilities;
-using Microsoft.Framework.Internal;
-
-namespace Microsoft.AspNet.Mvc
-{
- internal sealed class AntiForgeryTokenSerializer : IAntiForgeryTokenSerializer
- {
- private readonly IDataProtector _cryptoSystem;
- private const byte TokenVersion = 0x01;
-
- internal AntiForgeryTokenSerializer([NotNull] IDataProtector cryptoSystem)
- {
- _cryptoSystem = cryptoSystem;
- }
-
- public AntiForgeryToken Deserialize(string serializedToken)
- {
- Exception innerException = null;
- try
- {
- var tokenBytes = WebEncoders.Base64UrlDecode(serializedToken);
- using (var stream = new MemoryStream(_cryptoSystem.Unprotect(tokenBytes)))
- {
- using (var reader = new BinaryReader(stream))
- {
- var token = DeserializeImpl(reader);
- if (token != null)
- {
- return token;
- }
- }
- }
- }
- catch (Exception ex)
- {
- // swallow all exceptions - homogenize error if something went wrong
- innerException = ex;
- }
-
- // if we reached this point, something went wrong deserializing
- throw new InvalidOperationException(Resources.AntiForgeryToken_DeserializationFailed, innerException);
- }
-
- /* The serialized format of the anti-XSRF token is as follows:
- * Version: 1 byte integer
- * SecurityToken: 16 byte binary blob
- * IsSessionToken: 1 byte Boolean
- * [if IsSessionToken != true]
- * +- IsClaimsBased: 1 byte Boolean
- * | [if IsClaimsBased = true]
- * | `- ClaimUid: 32 byte binary blob
- * | [if IsClaimsBased = false]
- * | `- Username: UTF-8 string with 7-bit integer length prefix
- * `- AdditionalData: UTF-8 string with 7-bit integer length prefix
- */
- private static AntiForgeryToken DeserializeImpl(BinaryReader reader)
- {
- // we can only consume tokens of the same serialized version that we generate
- var embeddedVersion = reader.ReadByte();
- if (embeddedVersion != TokenVersion)
- {
- return null;
- }
-
- var deserializedToken = new AntiForgeryToken();
- var securityTokenBytes = reader.ReadBytes(AntiForgeryToken.SecurityTokenBitLength / 8);
- deserializedToken.SecurityToken =
- new BinaryBlob(AntiForgeryToken.SecurityTokenBitLength, securityTokenBytes);
- deserializedToken.IsSessionToken = reader.ReadBoolean();
-
- if (!deserializedToken.IsSessionToken)
- {
- var isClaimsBased = reader.ReadBoolean();
- if (isClaimsBased)
- {
- var claimUidBytes = reader.ReadBytes(AntiForgeryToken.ClaimUidBitLength / 8);
- deserializedToken.ClaimUid = new BinaryBlob(AntiForgeryToken.ClaimUidBitLength, claimUidBytes);
- }
- else
- {
- deserializedToken.Username = reader.ReadString();
- }
-
- deserializedToken.AdditionalData = reader.ReadString();
- }
-
- // if there's still unconsumed data in the stream, fail
- if (reader.BaseStream.ReadByte() != -1)
- {
- return null;
- }
-
- // success
- return deserializedToken;
- }
-
- public string Serialize([NotNull] AntiForgeryToken token)
- {
- using (var stream = new MemoryStream())
- {
- using (var writer = new BinaryWriter(stream))
- {
- writer.Write(TokenVersion);
- writer.Write(token.SecurityToken.GetData());
- writer.Write(token.IsSessionToken);
-
- if (!token.IsSessionToken)
- {
- if (token.ClaimUid != null)
- {
- writer.Write(true /* isClaimsBased */);
- writer.Write(token.ClaimUid.GetData());
- }
- else
- {
- writer.Write(false /* isClaimsBased */);
- writer.Write(token.Username);
- }
-
- writer.Write(token.AdditionalData);
- }
-
- writer.Flush();
- return WebEncoders.Base64UrlEncode(_cryptoSystem.Protect(stream.ToArray()));
- }
- }
- }
- }
-}
\ No newline at end of file
diff --git a/src/Microsoft.AspNet.Mvc.Extensions/AntiForgery/AntiForgeryTokenSet.cs b/src/Microsoft.AspNet.Mvc.Extensions/AntiForgery/AntiForgeryTokenSet.cs
deleted file mode 100644
index d992ed5ef7..0000000000
--- a/src/Microsoft.AspNet.Mvc.Extensions/AntiForgery/AntiForgeryTokenSet.cs
+++ /dev/null
@@ -1,43 +0,0 @@
-// 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;
-using Microsoft.AspNet.Mvc.Extensions;
-
-namespace Microsoft.AspNet.Mvc
-{
- ///
- /// The anti-forgery token pair (cookie and form token) for a request.
- ///
- public class AntiForgeryTokenSet
- {
- ///
- /// Creates the anti-forgery token pair (cookie and form token) for a request.
- ///
- /// The token that is supplied in the request form body.
- /// The token that is supplied in the request cookie.
- public AntiForgeryTokenSet(string formToken, string cookieToken)
- {
- if (string.IsNullOrEmpty(formToken))
- {
- throw new ArgumentException(Resources.ArgumentCannotBeNullOrEmpty, nameof(formToken));
- }
-
- FormToken = formToken;
-
- // Cookie Token is allowed to be null in the case when the old cookie is valid
- // and there is no new cookieToken generated.
- CookieToken = cookieToken;
- }
-
- ///
- /// The token that is supplied in the request form body.
- ///
- public string FormToken { get; private set; }
-
- /// The cookie token is allowed to be null.
- /// This would be the case when the old cookie token is still valid.
- /// In such cases a call to GetTokens would return a token set with null cookie token.
- public string CookieToken { get; private set; }
- }
-}
\ No newline at end of file
diff --git a/src/Microsoft.AspNet.Mvc.Extensions/AntiForgery/AntiForgeryTokenStore.cs b/src/Microsoft.AspNet.Mvc.Extensions/AntiForgery/AntiForgeryTokenStore.cs
deleted file mode 100644
index 7c3de1314e..0000000000
--- a/src/Microsoft.AspNet.Mvc.Extensions/AntiForgery/AntiForgeryTokenStore.cs
+++ /dev/null
@@ -1,79 +0,0 @@
-// 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.Diagnostics;
-using System.Threading.Tasks;
-using Microsoft.AspNet.Http;
-using Microsoft.Framework.DependencyInjection;
-using Microsoft.Framework.Internal;
-
-namespace Microsoft.AspNet.Mvc
-{
- // Saves anti-XSRF tokens split between HttpRequest.Cookies and HttpRequest.Form
- internal sealed class AntiForgeryTokenStore : IAntiForgeryTokenStore
- {
- private readonly AntiForgeryOptions _config;
- private readonly IAntiForgeryTokenSerializer _serializer;
-
- internal AntiForgeryTokenStore([NotNull] AntiForgeryOptions config,
- [NotNull] IAntiForgeryTokenSerializer serializer)
- {
- _config = config;
- _serializer = serializer;
- }
-
- public AntiForgeryToken GetCookieToken(HttpContext httpContext)
- {
- var contextAccessor =
- httpContext.RequestServices.GetRequiredService>();
- if (contextAccessor.Value != null)
- {
- return contextAccessor.Value.CookieToken;
- }
-
- var requestCookie = httpContext.Request.Cookies[_config.CookieName];
- if (string.IsNullOrEmpty(requestCookie))
- {
- // unable to find the cookie.
- return null;
- }
-
- return _serializer.Deserialize(requestCookie);
- }
-
- public async Task GetFormTokenAsync(HttpContext httpContext)
- {
- var form = await httpContext.Request.ReadFormAsync();
- var value = form[_config.FormFieldName];
- if (string.IsNullOrEmpty(value))
- {
- // did not exist
- return null;
- }
-
- return _serializer.Deserialize(value);
- }
-
- public void SaveCookieToken(HttpContext httpContext, AntiForgeryToken token)
- {
- // Add the cookie to the request based context.
- // This is useful if the cookie needs to be reloaded in the context of the same request.
- var contextAccessor =
- httpContext.RequestServices.GetRequiredService>();
- Debug.Assert(contextAccessor.Value == null, "AntiForgeryContext should be set only once per request.");
- contextAccessor.Value = new AntiForgeryContext() { CookieToken = token };
-
- var serializedToken = _serializer.Serialize(token);
- var options = new CookieOptions() { HttpOnly = true };
-
- // Note: don't use "newCookie.Secure = _config.RequireSSL;" since the default
- // value of newCookie.Secure is poulated out of band.
- if (_config.RequireSSL)
- {
- options.Secure = true;
- }
-
- httpContext.Response.Cookies.Append(_config.CookieName, serializedToken, options);
- }
- }
-}
\ No newline at end of file
diff --git a/src/Microsoft.AspNet.Mvc.Extensions/AntiForgery/AntiForgeryWorker.cs b/src/Microsoft.AspNet.Mvc.Extensions/AntiForgery/AntiForgeryWorker.cs
deleted file mode 100644
index 64158c32d8..0000000000
--- a/src/Microsoft.AspNet.Mvc.Extensions/AntiForgery/AntiForgeryWorker.cs
+++ /dev/null
@@ -1,257 +0,0 @@
-// 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;
-using System.Diagnostics;
-using System.Security.Claims;
-using System.Threading.Tasks;
-using Microsoft.AspNet.Http;
-using Microsoft.AspNet.Mvc.Extensions;
-using Microsoft.AspNet.Mvc.Rendering;
-using Microsoft.Framework.Internal;
-using Microsoft.Framework.WebEncoders;
-
-namespace Microsoft.AspNet.Mvc
-{
- internal sealed class AntiForgeryWorker
- {
- private readonly AntiForgeryOptions _config;
- private readonly IAntiForgeryTokenSerializer _serializer;
- private readonly IAntiForgeryTokenStore _tokenStore;
- private readonly IAntiForgeryTokenValidator _validator;
- private readonly IAntiForgeryTokenGenerator _generator;
- private readonly IHtmlEncoder _htmlEncoder;
-
- internal AntiForgeryWorker([NotNull] IAntiForgeryTokenSerializer serializer,
- [NotNull] AntiForgeryOptions config,
- [NotNull] IAntiForgeryTokenStore tokenStore,
- [NotNull] IAntiForgeryTokenGenerator generator,
- [NotNull] IAntiForgeryTokenValidator validator,
- [NotNull] IHtmlEncoder htmlEncoder)
- {
- _serializer = serializer;
- _config = config;
- _tokenStore = tokenStore;
- _generator = generator;
- _validator = validator;
- _htmlEncoder = htmlEncoder;
- }
-
- private void CheckSSLConfig(HttpContext httpContext)
- {
- if (_config.RequireSSL && !httpContext.Request.IsHttps)
- {
- throw new InvalidOperationException(Resources.AntiForgeryWorker_RequireSSL);
- }
- }
-
- private AntiForgeryToken DeserializeToken(string serializedToken)
- {
- return (!string.IsNullOrEmpty(serializedToken))
- ? _serializer.Deserialize(serializedToken)
- : null;
- }
-
- private AntiForgeryToken DeserializeTokenDoesNotThrow(string serializedToken)
- {
- try
- {
- return DeserializeToken(serializedToken);
- }
- catch
- {
- // ignore failures since we'll just generate a new token
- return null;
- }
- }
-
- private static ClaimsIdentity ExtractIdentity(HttpContext httpContext)
- {
- if (httpContext != null)
- {
- var user = httpContext.User;
-
- if (user != null)
- {
- // We only support ClaimsIdentity.
- return user.Identity as ClaimsIdentity;
- }
- }
-
- return null;
- }
-
- private AntiForgeryToken GetCookieTokenDoesNotThrow(HttpContext httpContext)
- {
- try
- {
- return _tokenStore.GetCookieToken(httpContext);
- }
- catch
- {
- // ignore failures since we'll just generate a new token
- return null;
- }
- }
-
- // [ ENTRY POINT ]
- // Generates an anti-XSRF token pair for the current user. The return
- // value is the hidden input form element that should be rendered in
- // the