public void ConstructorWithMessageParameter() { // Act HttpAntiForgeryException ex = new HttpAntiForgeryException("the message"); // Assert Assert.AreEqual("the message", ex.Message); }
public void TypeIsSerializable() { // If this ever fails with SerializationException : Unable to find assembly 'System.Web.Mvc, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' // (usually when the assembly version is incremented) you need to modify the App.config file in this test project to reference the new version. // Arrange MemoryStream ms = new MemoryStream(); BinaryFormatter formatter = new BinaryFormatter(); HttpAntiForgeryException ex = new HttpAntiForgeryException( "the message", new Exception("inner exception") ); // Act formatter.Serialize(ms, ex); ms.Position = 0; HttpAntiForgeryException deserialized = formatter.Deserialize(ms) as HttpAntiForgeryException; // Assert Assert.NotNull(deserialized); Assert.Equal("the message", deserialized.Message); Assert.NotNull(deserialized.InnerException); Assert.Equal("inner exception", deserialized.InnerException.Message); }
public void GetFormToken_FormFieldIsInvalid_PropagatesException() { // Arrange Mock <HttpContextBase> mockHttpContext = new Mock <HttpContextBase>(); mockHttpContext.Setup(o => o.Request.Form.Get("form-field-name")).Returns("invalid-value"); MockAntiForgeryConfig config = new MockAntiForgeryConfig() { FormFieldName = "form-field-name" }; HttpAntiForgeryException expectedException = new HttpAntiForgeryException("some exception"); Mock <MockableAntiForgeryTokenSerializer> mockSerializer = new Mock <MockableAntiForgeryTokenSerializer>(); mockSerializer.Setup(o => o.Deserialize("invalid-value")).Throws(expectedException); AntiForgeryTokenStore tokenStore = new AntiForgeryTokenStore( config: config, serializer: mockSerializer.Object); // Act & assert var ex = Assert.Throws <HttpAntiForgeryException>(() => tokenStore.GetFormToken(mockHttpContext.Object)); Assert.Same(expectedException, ex); }
public AntiForgeryToken Deserialize(string serializedToken) { try { using ( MemoryStream stream = new MemoryStream(_cryptoSystem.Unprotect(serializedToken)) ) { using (BinaryReader reader = new BinaryReader(stream)) { AntiForgeryToken token = DeserializeImpl(reader); if (token != null) { return(token); } } } } catch { // swallow all exceptions - homogenize error if something went wrong } // if we reached this point, something went wrong deserializing throw HttpAntiForgeryException.CreateDeserializationFailedException(); }
public void GetCookieToken_CookieIsInvalid_PropagatesException() { // Arrange Mock <HttpContextBase> mockHttpContext = new Mock <HttpContextBase>(); mockHttpContext.Setup(o => o.Request.Cookies).Returns(new HttpCookieCollection() { new HttpCookie("cookie-name", "invalid-value") }); MockAntiForgeryConfig config = new MockAntiForgeryConfig() { CookieName = "cookie-name" }; HttpAntiForgeryException expectedException = new HttpAntiForgeryException("some exception"); Mock <MockableAntiForgeryTokenSerializer> mockSerializer = new Mock <MockableAntiForgeryTokenSerializer>(); mockSerializer.Setup(o => o.Deserialize("invalid-value")).Throws(expectedException); AntiForgeryTokenStore tokenStore = new AntiForgeryTokenStore( config: config, serializer: mockSerializer.Object); // Act & assert var ex = Assert.Throws <HttpAntiForgeryException>(() => tokenStore.GetCookieToken(mockHttpContext.Object)); Assert.Equal(expectedException, ex); }
public void ConstructorWithMessageParameter() { // Act HttpAntiForgeryException ex = new HttpAntiForgeryException("the message"); // Assert Assert.Equal("the message", ex.Message); }
public void ValidateTokens(HttpContextBase httpContext, IIdentity identity, AntiForgeryToken sessionToken, AntiForgeryToken fieldToken) { // Were the tokens even present at all? if (sessionToken == null) { throw HttpAntiForgeryException.CreateCookieMissingException(_config.CookieName); } if (fieldToken == null) { throw HttpAntiForgeryException.CreateFormFieldMissingException(_config.FormFieldName); } // Do the tokens have the correct format? if (!sessionToken.IsSessionToken || fieldToken.IsSessionToken) { throw HttpAntiForgeryException.CreateTokensSwappedException(_config.CookieName, _config.FormFieldName); } // Are the security tokens embedded in each incoming token identical? if (!Equals(sessionToken.SecurityToken, fieldToken.SecurityToken)) { throw HttpAntiForgeryException.CreateSecurityTokenMismatchException(); } // Is the incoming token meant for the current user? string currentUsername = String.Empty; BinaryBlob currentClaimUid = null; if (identity != null && identity.IsAuthenticated) { currentClaimUid = _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. bool useCaseSensitiveUsernameComparison = currentUsername.StartsWith("http://", StringComparison.OrdinalIgnoreCase) || currentUsername.StartsWith("https://", StringComparison.OrdinalIgnoreCase); if (!String.Equals(fieldToken.Username, currentUsername, (useCaseSensitiveUsernameComparison) ? StringComparison.Ordinal : StringComparison.OrdinalIgnoreCase)) { throw HttpAntiForgeryException.CreateUsernameMismatchException(fieldToken.Username, currentUsername); } if (!Equals(fieldToken.ClaimUid, currentClaimUid)) { throw HttpAntiForgeryException.CreateClaimUidMismatchException(); } // Is the AdditionalData valid? if (_config.AdditionalDataProvider != null && !_config.AdditionalDataProvider.ValidateAdditionalData(httpContext, fieldToken.AdditionalData)) { throw HttpAntiForgeryException.CreateAdditionalDataCheckFailedException(); } }
public void ConstructorWithMessageAndInnerExceptionParameter() { // Arrange Exception innerException = new Exception(); // Act HttpAntiForgeryException ex = new HttpAntiForgeryException("the message", innerException); // Assert Assert.AreEqual("the message", ex.Message); Assert.AreEqual(innerException, ex.InnerException); }
public void ConstructorWithMessageAndInnerExceptionParameter() { // Arrange Exception innerException = new Exception(); // Act HttpAntiForgeryException ex = new HttpAntiForgeryException("the message", innerException); // Assert Assert.Equal("the message", ex.Message); Assert.Equal(innerException, ex.InnerException); }
public AntiForgeryToken?Deserialize(string serializedToken, bool throwOnError) { AntiForgeryToken?token = DeserializeImpl(serializedToken); if (token is null && throwOnError) { throw HttpAntiForgeryException.CreateDeserializationFailedException(); } return(token); }
public void TypeIsSerializable() { // Arrange MemoryStream ms = new MemoryStream(); BinaryFormatter formatter = new BinaryFormatter(); HttpAntiForgeryException ex = new HttpAntiForgeryException("the message", new Exception("inner exception")); // Act formatter.Serialize(ms, ex); ms.Position = 0; HttpAntiForgeryException deserialized = formatter.Deserialize(ms) as HttpAntiForgeryException; // Assert Assert.IsNotNull(deserialized, "Deserialization process did not return the exception."); Assert.AreEqual("the message", deserialized.Message); Assert.IsNotNull(deserialized.InnerException); Assert.AreEqual("inner exception", deserialized.InnerException.Message); }
[Ignore] // There's some issue with deserialization where the type gets deserialized to an instance of the MVC2 type public void TypeIsSerializable() { // Arrange MemoryStream ms = new MemoryStream(); BinaryFormatter formatter = new BinaryFormatter(); HttpAntiForgeryException ex = new HttpAntiForgeryException("the message", new Exception("inner exception")); // Act formatter.Serialize(ms, ex); ms.Position = 0; HttpAntiForgeryException deserialized = formatter.Deserialize(ms) as HttpAntiForgeryException; // Assert Assert.IsNotNull(deserialized, "Deserialization process did not return the exception."); Assert.AreEqual("the message", deserialized.Message); Assert.IsNotNull(deserialized.InnerException); Assert.AreEqual("inner exception", deserialized.InnerException.Message); }
public void ValidateTokens(HttpContextBase httpContext, IIdentity identity, AntiForgeryToken sessionToken, AntiForgeryToken fieldToken) { if (sessionToken == null) { throw HttpAntiForgeryException.CreateCookieMissingException(this._config.CookieName); } if (fieldToken == null) { throw HttpAntiForgeryException.CreateFormFieldMissingException(this._config.FormFieldName); } if (!sessionToken.IsSessionToken || fieldToken.IsSessionToken) { throw HttpAntiForgeryException.CreateTokensSwappedException(this._config.CookieName, this._config.FormFieldName); } if (!object.Equals(sessionToken.SecurityToken, fieldToken.SecurityToken)) { throw HttpAntiForgeryException.CreateSecurityTokenMismatchException(); } string text = string.Empty; BinaryBlob binaryBlob = null; if (identity != null && identity.IsAuthenticated) { binaryBlob = this._claimUidExtractor.ExtractClaimUid(identity); if (binaryBlob == null) { text = (identity.Name ?? string.Empty); } } bool flag = text.StartsWith("http://", StringComparison.OrdinalIgnoreCase) || text.StartsWith("https://", StringComparison.OrdinalIgnoreCase); if (!string.Equals(fieldToken.Username, text, flag ? StringComparison.Ordinal : StringComparison.OrdinalIgnoreCase)) { throw HttpAntiForgeryException.CreateUsernameMismatchException(fieldToken.Username, text); } if (!object.Equals(fieldToken.ClaimUid, binaryBlob)) { throw HttpAntiForgeryException.CreateClaimUidMismatchException(); } if (this._config.AdditionalDataProvider != null && !this._config.AdditionalDataProvider.ValidateAdditionalData(httpContext, fieldToken.AdditionalData)) { throw HttpAntiForgeryException.CreateAdditionalDataCheckFailedException(); } }
public void DeserializationExceptionDoesNotContainInnerException() { // Arrange AntiForgeryDataSerializer serializer = new AntiForgeryDataSerializer(); // Act & assert HttpAntiForgeryException exception = null; try { serializer.Deserialize("Can't deserialize this."); } catch (HttpAntiForgeryException ex) { exception = ex; } Assert.NotNull(exception); Assert.Null(exception.InnerException); }
public AntiForgeryToken Deserialize(string serializedToken) { try { using (MemoryStream memoryStream = new MemoryStream(this._cryptoSystem.Unprotect(serializedToken))) { using (BinaryReader binaryReader = new BinaryReader(memoryStream)) { AntiForgeryToken antiForgeryToken = AntiForgeryTokenSerializer.DeserializeImpl(binaryReader); if (antiForgeryToken != null) { return(antiForgeryToken); } } } } catch { } throw HttpAntiForgeryException.CreateDeserializationFailedException(); }
public void TypeIsSerializable() { // If this ever fails with SerializationException : Unable to find assembly 'System.Web.Mvc, Version=2.0.0.0, Culture=neutral, PublicKeyToken=2f9147bba06de483' // (usually when the assembly version is incremented) you need to modify the App.config file in this test project to reference the new version. // Arrange MemoryStream ms = new MemoryStream(); BinaryFormatter formatter = new BinaryFormatter(); HttpAntiForgeryException ex = new HttpAntiForgeryException("the message", new Exception("inner exception")); // Act formatter.Serialize(ms, ex); ms.Position = 0; HttpAntiForgeryException deserialized = formatter.Deserialize(ms) as HttpAntiForgeryException; // Assert Assert.NotNull(deserialized); Assert.Equal("the message", deserialized.Message); Assert.NotNull(deserialized.InnerException); Assert.Equal("inner exception", deserialized.InnerException.Message); }
public void DeserializeThrowsIfFormatterThrows() { // Arrange Exception innerException = new Exception(); Mock <IStateFormatter> mockFormatter = new Mock <IStateFormatter>(); mockFormatter.Expect(f => f.Deserialize("bad value")).Throws(innerException); AntiForgeryDataSerializer serializer = new AntiForgeryDataSerializer() { Formatter = mockFormatter.Object }; // Act HttpAntiForgeryException ex = ExceptionHelper.ExpectException <HttpAntiForgeryException>( delegate { serializer.Deserialize("bad value"); }, "A required anti-forgery token was not supplied or was invalid."); // Assert Assert.AreEqual(innerException, ex.InnerException); }
/// <summary> /// Does nothing by default. This can be easily overriden to add custom handling of anti forgery token. /// </summary> /// <param name="exception">The exception that was thrown by the application, and caught by the error /// handler.</param> public virtual void OnAntiForgeryException(HttpAntiForgeryException exception) { }