public void Validate_FromStore_Success() { // Arrange GenericIdentity identity = new GenericIdentity("some-user"); Mock <HttpContextBase> mockHttpContext = new Mock <HttpContextBase>(); mockHttpContext.Setup(o => o.User).Returns(new GenericPrincipal(identity, new string[0])); AntiForgeryToken cookieToken = new AntiForgeryToken(); AntiForgeryToken formToken = new AntiForgeryToken(); Mock <MockableTokenStore> mockTokenStore = new Mock <MockableTokenStore>(); mockTokenStore.Setup(o => o.GetCookieToken(mockHttpContext.Object)).Returns(cookieToken); mockTokenStore.Setup(o => o.GetFormToken(mockHttpContext.Object)).Returns(formToken); Mock <MockableTokenValidator> mockValidator = new Mock <MockableTokenValidator>(); mockValidator.Setup(o => o.ValidateTokens(mockHttpContext.Object, identity, cookieToken, formToken)).Verifiable(); AntiForgeryWorker worker = new AntiForgeryWorker( config: new MockAntiForgeryConfig(), serializer: null, tokenStore: mockTokenStore.Object, validator: mockValidator.Object); // Act worker.Validate(mockHttpContext.Object); // Assert mockValidator.Verify(); }
public async Task ChecksSSL_ValidateAsync_Throws() { // Arrange var mockHttpContext = new Mock<HttpContext>(); mockHttpContext.Setup(o => o.Request.IsSecure) .Returns(false); var config = new AntiForgeryOptions() { RequireSSL = true }; var worker = new AntiForgeryWorker( config: config, serializer: null, tokenStore: null, generator: null, validator: null); // Act & assert var ex = await Assert.ThrowsAsync<InvalidOperationException>( async () => await worker.ValidateAsync(mockHttpContext.Object)); Assert.Equal( @"The anti-forgery system has the configuration value AntiForgeryOptions.RequireSsl = true, " + "but the current request is not an SSL request.", ex.Message); }
public void Validate_FromStore_Failure() { // Arrange GenericIdentity identity = new GenericIdentity("some-user"); Mock <HttpContextBase> mockHttpContext = new Mock <HttpContextBase>(); mockHttpContext.Setup(o => o.User).Returns(new GenericPrincipal(identity, new string[0])); AntiForgeryToken cookieToken = new AntiForgeryToken(); AntiForgeryToken formToken = new AntiForgeryToken(); Mock <MockableTokenStore> mockTokenStore = new Mock <MockableTokenStore>(); mockTokenStore.Setup(o => o.GetCookieToken(mockHttpContext.Object)).Returns(cookieToken); mockTokenStore.Setup(o => o.GetFormToken(mockHttpContext.Object)).Returns(formToken); Mock <MockableTokenValidator> mockValidator = new Mock <MockableTokenValidator>(); mockValidator.Setup(o => o.ValidateTokens(mockHttpContext.Object, identity, cookieToken, formToken)).Throws(new HttpAntiForgeryException("my-message")); AntiForgeryWorker worker = new AntiForgeryWorker( config: new MockAntiForgeryConfig(), serializer: null, tokenStore: mockTokenStore.Object, validator: mockValidator.Object); // Act & assert var ex = Assert.Throws <HttpAntiForgeryException>(() => worker.Validate(mockHttpContext.Object)); Assert.Equal("my-message", ex.Message); }
public void GetHtml_SetsCookieDomainAndPathIfSpecified() { // Arrange AntiForgeryWorker worker = new AntiForgeryWorker() { Serializer = new DummyAntiForgeryTokenSerializer() }; var context = CreateContext(); // Act string formValue = worker.GetHtml(context, "some other salt", "theDomain", "thePath").ToHtmlString(); // Assert Assert.True(formValue.StartsWith(_serializedValuePrefix), "Form value prefix did not match."); Match formMatch = _randomFormValueSuffixRegex.Match(formValue); string formTokenValue = formMatch.Groups["value"].Value; HttpCookie cookie = context.Response.Cookies[_antiForgeryTokenCookieName]; Assert.NotNull(cookie); Assert.True(cookie.HttpOnly, "Cookie should have HTTP-only flag set."); Assert.Equal("theDomain", cookie.Domain); Assert.Equal("thePath", cookie.Path); Match cookieMatch = _randomCookieValueSuffixRegex.Match(cookie.Value); string cookieTokenValue = cookieMatch.Groups["value"].Value; Assert.Equal(formTokenValue, cookieTokenValue); }
public void GetHtml_ReturnsFormFieldAndSetsCookieValueIfDoesNotExist() { // Arrange AntiForgeryWorker worker = new AntiForgeryWorker() { Serializer = new DummyAntiForgeryTokenSerializer() }; var context = CreateContext(); // Act string formValue = worker.GetHtml(context, "some other salt", null, null).ToHtmlString(); // Assert Assert.True(formValue.StartsWith(_serializedValuePrefix), "Form value prefix did not match."); Match formMatch = _randomFormValueSuffixRegex.Match(formValue); string formTokenValue = formMatch.Groups["value"].Value; HttpCookie cookie = context.Response.Cookies[_antiForgeryTokenCookieName]; Assert.NotNull(cookie); Assert.True(cookie.HttpOnly, "Cookie should have HTTP-only flag set."); Assert.True(String.IsNullOrEmpty(cookie.Domain), "Domain should not have been set."); Assert.Equal("/", cookie.Path); Match cookieMatch = _randomCookieValueSuffixRegex.Match(cookie.Value); string cookieTokenValue = cookieMatch.Groups["value"].Value; Assert.Equal(formTokenValue, cookieTokenValue); }
public void ChecksSSL() { // Arrange Mock<HttpContextBase> mockHttpContext = new Mock<HttpContextBase>(); mockHttpContext.Setup(o => o.Request.IsSecureConnection).Returns(false); IAntiForgeryConfig config = new MockAntiForgeryConfig() { RequireSSL = true }; AntiForgeryWorker worker = new AntiForgeryWorker( config: config, serializer: null, tokenStore: null, validator: null); // Act & assert var ex = Assert.Throws<InvalidOperationException>(() => worker.Validate(mockHttpContext.Object, "session-token", "field-token")); Assert.Equal(@"The anti-forgery system has the configuration value AntiForgeryConfig.RequireSsl = true, but the current request is not an SSL request.", ex.Message); ex = Assert.Throws<InvalidOperationException>(() => worker.Validate(mockHttpContext.Object)); Assert.Equal(@"The anti-forgery system has the configuration value AntiForgeryConfig.RequireSsl = true, but the current request is not an SSL request.", ex.Message); ex = Assert.Throws<InvalidOperationException>(() => worker.GetFormInputElement(mockHttpContext.Object)); Assert.Equal(@"The anti-forgery system has the configuration value AntiForgeryConfig.RequireSsl = true, but the current request is not an SSL request.", ex.Message); ex = Assert.Throws<InvalidOperationException>(() => { string dummy1, dummy2; worker.GetTokens(mockHttpContext.Object, "cookie-token", out dummy1, out dummy2); }); Assert.Equal(@"The anti-forgery system has the configuration value AntiForgeryConfig.RequireSsl = true, but the current request is not an SSL request.", ex.Message); }
public void ChecksSSL_GetFormInputElement_Throws() { // Arrange var mockHttpContext = new Mock <HttpContext>(); mockHttpContext.Setup(o => o.Request.IsSecure) .Returns(false); var config = new AntiForgeryOptions() { RequireSSL = true }; var worker = new AntiForgeryWorker( config: config, serializer: null, tokenStore: null, generator: null, validator: null); // Act & assert var ex = Assert.Throws <InvalidOperationException>(() => worker.GetFormInputElement(mockHttpContext.Object)); Assert.Equal( @"The anti-forgery system has the configuration value AntiForgeryOptions.RequireSsl = true, " + "but the current request is not an SSL request.", ex.Message); }
public void ChecksSSL_Validate_Throws() { // Arrange var mockHttpContext = new Mock<HttpContext>(); mockHttpContext.Setup(o => o.Request.IsHttps) .Returns(false); var config = new AntiForgeryOptions() { RequireSSL = true }; var worker = new AntiForgeryWorker( config: config, serializer: null, tokenStore: null, generator: null, validator: null, htmlEncoder: new HtmlEncoder()); // Act & assert var ex = Assert.Throws<InvalidOperationException>( () => worker.Validate(mockHttpContext.Object, cookieToken: null, formToken: null)); Assert.Equal( @"The anti-forgery system has the configuration value AntiForgeryOptions.RequireSsl = true, " + "but the current request is not an SSL request.", ex.Message); }
public async Task ChecksSSL_ValidateAsync_Throws() { // Arrange var mockHttpContext = new Mock <HttpContext>(); mockHttpContext.Setup(o => o.Request.IsHttps) .Returns(false); var config = new AntiForgeryOptions() { RequireSSL = true }; var worker = new AntiForgeryWorker( config: config, serializer: null, tokenStore: null, generator: null, validator: null, htmlEncoder: new HtmlEncoder()); // Act & assert var ex = await Assert.ThrowsAsync <InvalidOperationException>( async() => await worker.ValidateAsync(mockHttpContext.Object)); Assert.Equal( @"The anti-forgery system has the configuration value AntiForgeryOptions.RequireSsl = true, " + "but the current request is not an SSL request.", ex.Message); }
public void ChecksSSL() { // Arrange Mock <HttpContextBase> mockHttpContext = new Mock <HttpContextBase>(); mockHttpContext.Setup(o => o.Request.IsSecureConnection).Returns(false); IAntiForgeryConfig config = new MockAntiForgeryConfig() { RequireSSL = true }; AntiForgeryWorker worker = new AntiForgeryWorker( config: config, serializer: null, tokenStore: null, validator: null); // Act & assert var ex = Assert.Throws <InvalidOperationException>(() => worker.Validate(mockHttpContext.Object, "session-token", "field-token")); Assert.Equal(@"The anti-forgery system has the configuration value AntiForgeryConfig.RequireSsl = true, but the current request is not an SSL request.", ex.Message); ex = Assert.Throws <InvalidOperationException>(() => worker.Validate(mockHttpContext.Object)); Assert.Equal(@"The anti-forgery system has the configuration value AntiForgeryConfig.RequireSsl = true, but the current request is not an SSL request.", ex.Message); ex = Assert.Throws <InvalidOperationException>(() => worker.GetFormInputElement(mockHttpContext.Object)); Assert.Equal(@"The anti-forgery system has the configuration value AntiForgeryConfig.RequireSsl = true, but the current request is not an SSL request.", ex.Message); ex = Assert.Throws <InvalidOperationException>(() => { string dummy1, dummy2; worker.GetTokens(mockHttpContext.Object, "cookie-token", out dummy1, out dummy2); }); Assert.Equal(@"The anti-forgery system has the configuration value AntiForgeryConfig.RequireSsl = true, but the current request is not an SSL request.", ex.Message); }
public void GetHtml_SetsCookieDomainAndPathIfSpecified() { // Arrange AntiForgeryWorker worker = new AntiForgeryWorker() { Serializer = new DummyAntiForgeryTokenSerializer() }; var context = CreateContext(); // Act string formValue = worker.GetHtml(context, "some other salt", "theDomain", "thePath").ToHtmlString(); // Assert Assert.IsTrue(formValue.StartsWith(_serializedValuePrefix), "Form value prefix did not match."); Match formMatch = _randomFormValueSuffixRegex.Match(formValue); string formTokenValue = formMatch.Groups["value"].Value; HttpCookie cookie = context.Response.Cookies[_antiForgeryTokenCookieName]; Assert.IsNotNull(cookie, "Cookie was not set correctly."); Assert.IsTrue(cookie.HttpOnly, "Cookie should have HTTP-only flag set."); Assert.AreEqual("theDomain", cookie.Domain); Assert.AreEqual("thePath", cookie.Path); Match cookieMatch = _randomCookieValueSuffixRegex.Match(cookie.Value); string cookieTokenValue = cookieMatch.Groups["value"].Value; Assert.AreEqual(formTokenValue, cookieTokenValue, "Form and cookie token values did not match."); }
public void GetHtml_ReturnsFormFieldAndSetsCookieValueIfDoesNotExist() { // Arrange AntiForgeryWorker worker = new AntiForgeryWorker() { Serializer = new DummyAntiForgeryTokenSerializer() }; var context = CreateContext(); // Act string formValue = worker.GetHtml(context,"some other salt", null, null).ToHtmlString(); // Assert Assert.IsTrue(formValue.StartsWith(_serializedValuePrefix), "Form value prefix did not match."); Match formMatch = _randomFormValueSuffixRegex.Match(formValue); string formTokenValue = formMatch.Groups["value"].Value; HttpCookie cookie = context.Response.Cookies[_antiForgeryTokenCookieName]; Assert.IsNotNull(cookie, "Cookie was not set correctly."); Assert.IsTrue(cookie.HttpOnly, "Cookie should have HTTP-only flag set."); Assert.IsTrue(String.IsNullOrEmpty(cookie.Domain), "Domain should not have been set."); Assert.AreEqual("/", cookie.Path, "Path should have remained at '/' by default."); Match cookieMatch = _randomCookieValueSuffixRegex.Match(cookie.Value); string cookieTokenValue = cookieMatch.Groups["value"].Value; Assert.AreEqual(formTokenValue, cookieTokenValue, "Form and cookie token values did not match."); }
public void GetHtml_CreatesNewCookieValueIfCookieExistsButIsNotValid() { // Arrange AntiForgeryWorker worker = new AntiForgeryWorker() { Serializer = new DummyAntiForgeryTokenSerializer() }; var context = CreateContext("invalid"); // Act string formValue = worker.GetHtml(context, "some other salt", null, null).ToHtmlString(); // Assert Assert.IsTrue(formValue.StartsWith(_serializedValuePrefix), "Form value prefix did not match."); Match formMatch = _randomFormValueSuffixRegex.Match(formValue); string formTokenValue = formMatch.Groups["value"].Value; HttpCookie cookie = context.Response.Cookies[_antiForgeryTokenCookieName]; Assert.IsNotNull(cookie, "Cookie was not set correctly."); Assert.IsTrue(cookie.HttpOnly, "Cookie should have HTTP-only flag set."); Assert.IsTrue(String.IsNullOrEmpty(cookie.Domain), "Domain should not have been set."); Assert.AreEqual("/", cookie.Path, "Path should have remained at '/' by default."); Match cookieMatch = _randomCookieValueSuffixRegex.Match(cookie.Value); string cookieTokenValue = cookieMatch.Groups["value"].Value; Assert.AreEqual(formTokenValue, cookieTokenValue, "Form and cookie token values did not match."); }
public void GetFormInputElement_ExistingInvalidCookieToken() { // Arrange GenericIdentity identity = new GenericIdentity("some-user"); Mock <HttpContextBase> mockHttpContext = new Mock <HttpContextBase>(); mockHttpContext.Setup(o => o.User).Returns(new GenericPrincipal(identity, new string[0])); Mock <HttpResponseBase> mockResponse = new Mock <HttpResponseBase>(); mockResponse.Setup(r => r.Headers).Returns(new NameValueCollection()); mockHttpContext.Setup(o => o.Response).Returns(mockResponse.Object); AntiForgeryToken oldCookieToken = new AntiForgeryToken() { IsSessionToken = true }; AntiForgeryToken newCookieToken = new AntiForgeryToken() { IsSessionToken = true }; AntiForgeryToken formToken = new AntiForgeryToken(); MockAntiForgeryConfig config = new MockAntiForgeryConfig() { FormFieldName = "form-field-name" }; Mock <MockableAntiForgeryTokenSerializer> mockSerializer = new Mock <MockableAntiForgeryTokenSerializer>(MockBehavior.Strict); mockSerializer.Setup(o => o.Serialize(formToken)).Returns("serialized-form-token"); Mock <MockableTokenStore> mockTokenStore = new Mock <MockableTokenStore>(MockBehavior.Strict); mockTokenStore.Setup(o => o.GetCookieToken(mockHttpContext.Object)).Returns(oldCookieToken); mockTokenStore.Setup(o => o.SaveCookieToken(mockHttpContext.Object, newCookieToken)).Verifiable(); Mock <MockableTokenValidator> mockValidator = new Mock <MockableTokenValidator>(MockBehavior.Strict); mockValidator.Setup(o => o.GenerateFormToken(mockHttpContext.Object, identity, newCookieToken)).Returns(formToken); mockValidator.Setup(o => o.IsCookieTokenValid(oldCookieToken)).Returns(false); mockValidator.Setup(o => o.IsCookieTokenValid(newCookieToken)).Returns(true); mockValidator.Setup(o => o.GenerateCookieToken()).Returns(newCookieToken); AntiForgeryWorker worker = new AntiForgeryWorker( config: config, serializer: mockSerializer.Object, tokenStore: mockTokenStore.Object, validator: mockValidator.Object); // Act TagBuilder retVal = worker.GetFormInputElement(mockHttpContext.Object); // Assert Assert.Equal(@"<input name=""form-field-name"" type=""hidden"" value=""serialized-form-token"" />", retVal.ToString(TagRenderMode.SelfClosing)); mockTokenStore.Verify(); }
public void GetTokens_ExistingValidCookieToken() { // Arrange GenericIdentity identity = new GenericIdentity("some-user"); Mock <HttpContextBase> mockHttpContext = new Mock <HttpContextBase>(); mockHttpContext .Setup(o => o.User) .Returns(new GenericPrincipal(identity, new string[0])); AntiForgeryToken cookieToken = new AntiForgeryToken() { IsSessionToken = true }; AntiForgeryToken formToken = new AntiForgeryToken(); Mock <MockableAntiForgeryTokenSerializer> mockSerializer = new Mock <MockableAntiForgeryTokenSerializer>(MockBehavior.Strict); mockSerializer .Setup(o => o.Deserialize("serialized-old-cookie-token")) .Returns(cookieToken); mockSerializer.Setup(o => o.Serialize(formToken)).Returns("serialized-form-token"); Mock <MockableTokenValidator> mockValidator = new Mock <MockableTokenValidator>( MockBehavior.Strict ); mockValidator .Setup(o => o.GenerateFormToken(mockHttpContext.Object, identity, cookieToken)) .Returns(formToken); mockValidator.Setup(o => o.IsCookieTokenValid(cookieToken)).Returns(true); AntiForgeryWorker worker = new AntiForgeryWorker( config: new MockAntiForgeryConfig(), serializer: mockSerializer.Object, tokenStore: null, validator: mockValidator.Object ); // Act string serializedNewCookieToken, serializedFormToken; worker.GetTokens( mockHttpContext.Object, "serialized-old-cookie-token", out serializedNewCookieToken, out serializedFormToken ); // Assert Assert.Null(serializedNewCookieToken); Assert.Equal("serialized-form-token", serializedFormToken); }
public void GetHtml_ReusesCookieValueIfExistsAndIsValid() { // Arrange AntiForgeryWorker worker = new AntiForgeryWorker() { Serializer = new DummyAntiForgeryTokenSerializer() }; var context = CreateContext("2001-01-01:some value:some salt:username"); // Act string formValue = worker.GetHtml(context, "some other salt", null, null).ToHtmlString(); // Assert Assert.True(formValue.StartsWith(_serializedValuePrefix), "Form value prefix did not match."); Assert.True(formValue.EndsWith(_someValueSuffix), "Form value suffix did not match."); Assert.Equal(0, context.Response.Cookies.Count); }
public void GetFormInputElement_ExistingInvalidCookieToken() { // Arrange GenericIdentity identity = new GenericIdentity("some-user"); Mock<HttpContextBase> mockHttpContext = new Mock<HttpContextBase>(); mockHttpContext.Setup(o => o.User).Returns(new GenericPrincipal(identity, new string[0])); Mock<HttpResponseBase> mockResponse = new Mock<HttpResponseBase>(); mockResponse.Setup(r => r.Headers).Returns(new NameValueCollection()); mockHttpContext.Setup(o => o.Response).Returns(mockResponse.Object); AntiForgeryToken oldCookieToken = new AntiForgeryToken() { IsSessionToken = true }; AntiForgeryToken newCookieToken = new AntiForgeryToken() { IsSessionToken = true }; AntiForgeryToken formToken = new AntiForgeryToken(); MockAntiForgeryConfig config = new MockAntiForgeryConfig() { FormFieldName = "form-field-name" }; Mock<MockableAntiForgeryTokenSerializer> mockSerializer = new Mock<MockableAntiForgeryTokenSerializer>(MockBehavior.Strict); mockSerializer.Setup(o => o.Serialize(formToken)).Returns("serialized-form-token"); Mock<MockableTokenStore> mockTokenStore = new Mock<MockableTokenStore>(MockBehavior.Strict); mockTokenStore.Setup(o => o.GetCookieToken(mockHttpContext.Object)).Returns(oldCookieToken); mockTokenStore.Setup(o => o.SaveCookieToken(mockHttpContext.Object, newCookieToken)).Verifiable(); Mock<MockableTokenValidator> mockValidator = new Mock<MockableTokenValidator>(MockBehavior.Strict); mockValidator.Setup(o => o.GenerateFormToken(mockHttpContext.Object, identity, newCookieToken)).Returns(formToken); mockValidator.Setup(o => o.IsCookieTokenValid(oldCookieToken)).Returns(false); mockValidator.Setup(o => o.IsCookieTokenValid(newCookieToken)).Returns(true); mockValidator.Setup(o => o.GenerateCookieToken()).Returns(newCookieToken); AntiForgeryWorker worker = new AntiForgeryWorker( config: config, serializer: mockSerializer.Object, tokenStore: mockTokenStore.Object, validator: mockValidator.Object); // Act TagBuilder retVal = worker.GetFormInputElement(mockHttpContext.Object); // Assert Assert.Equal(@"<input name=""form-field-name"" type=""hidden"" value=""serialized-form-token"" />", retVal.ToString(TagRenderMode.SelfClosing)); mockTokenStore.Verify(); }
private static void Validate_Helper(string cookieValue, string formValue, string username = "******") { // Arrange //ValidateAntiForgeryTokenAttribute attribute = GetAttribute(); var context = CreateContext(cookieValue, formValue, username); AntiForgeryWorker worker = new AntiForgeryWorker() { Serializer = new DummyAntiForgeryTokenSerializer() }; // Act & Assert ExceptionAssert.Throws <HttpAntiForgeryException>( delegate { //attribute.OnAuthorization(authContext); worker.Validate(context, "the real salt"); }, "A required anti-forgery token was not supplied or was invalid."); }
public void GetFormInputElement_AddsXFrameOptionsHeader(bool suppressXFrameOptions, string expectedHeaderValue) { // Arrange GenericIdentity identity = new GenericIdentity("some-user"); Mock <HttpContextBase> mockHttpContext = new Mock <HttpContextBase>(); mockHttpContext.Setup(o => o.User).Returns(new GenericPrincipal(identity, new string[0])); NameValueCollection headers = new NameValueCollection(); Mock <HttpResponseBase> mockResponse = new Mock <HttpResponseBase>(); mockResponse.Setup(r => r.Headers).Returns(headers); mockResponse.Setup(r => r.AddHeader(It.IsAny <string>(), It.IsAny <string>())).Callback <string, string>((k, v) => { headers.Add(k, v); }); mockHttpContext.Setup(o => o.Response).Returns(mockResponse.Object); AntiForgeryToken oldCookieToken = new AntiForgeryToken() { IsSessionToken = true }; AntiForgeryToken newCookieToken = new AntiForgeryToken() { IsSessionToken = true }; AntiForgeryToken formToken = new AntiForgeryToken(); MockAntiForgeryConfig config = new MockAntiForgeryConfig() { FormFieldName = "form-field-name", SuppressXFrameOptionsHeader = suppressXFrameOptions }; Mock <MockableAntiForgeryTokenSerializer> mockSerializer = new Mock <MockableAntiForgeryTokenSerializer>(MockBehavior.Strict); mockSerializer.Setup(o => o.Serialize(formToken)).Returns("serialized-form-token"); Mock <MockableTokenStore> mockTokenStore = new Mock <MockableTokenStore>(MockBehavior.Strict); mockTokenStore.Setup(o => o.GetCookieToken(mockHttpContext.Object)).Returns(oldCookieToken); mockTokenStore.Setup(o => o.SaveCookieToken(mockHttpContext.Object, newCookieToken)).Verifiable(); Mock <MockableTokenValidator> mockValidator = new Mock <MockableTokenValidator>(MockBehavior.Strict); mockValidator.Setup(o => o.GenerateFormToken(mockHttpContext.Object, identity, newCookieToken)).Returns(formToken); mockValidator.Setup(o => o.IsCookieTokenValid(oldCookieToken)).Returns(false); mockValidator.Setup(o => o.IsCookieTokenValid(newCookieToken)).Returns(true); mockValidator.Setup(o => o.GenerateCookieToken()).Returns(newCookieToken); AntiForgeryWorker worker = new AntiForgeryWorker( config: config, serializer: mockSerializer.Object, tokenStore: mockTokenStore.Object, validator: mockValidator.Object); HttpContextBase context = mockHttpContext.Object; // Act TagBuilder retVal = worker.GetFormInputElement(context); // Assert string xFrameOptions = context.Response.Headers["X-FRAME-OPTIONS"]; Assert.Equal(expectedHeaderValue, xFrameOptions); }
public void GetHtml_ReusesCookieValueIfExistsAndIsValid() { // Arrange AntiForgeryWorker worker = new AntiForgeryWorker() { Serializer = new DummyAntiForgeryTokenSerializer() }; var context = CreateContext("2001-01-01:some value:some salt:username"); // Act string formValue = worker.GetHtml(context, "some other salt", null, null).ToHtmlString(); // Assert Assert.IsTrue(formValue.StartsWith(_serializedValuePrefix), "Form value prefix did not match."); Assert.IsTrue(formValue.EndsWith(_someValueSuffix), "Form value suffix did not match."); Assert.AreEqual(0, context.Response.Cookies.Count, "Cookie should not have been added to response."); }
public void GetFormInputElement_AddsXFrameOptionsHeader(bool suppressXFrameOptions, string expectedHeaderValue) { // Arrange GenericIdentity identity = new GenericIdentity("some-user"); Mock<HttpContextBase> mockHttpContext = new Mock<HttpContextBase>(); mockHttpContext.Setup(o => o.User).Returns(new GenericPrincipal(identity, new string[0])); NameValueCollection headers = new NameValueCollection(); Mock<HttpResponseBase> mockResponse = new Mock<HttpResponseBase>(); mockResponse.Setup(r => r.Headers).Returns(headers); mockResponse.Setup(r => r.AddHeader(It.IsAny<string>(), It.IsAny<string>())).Callback<string, string>((k, v) => { headers.Add(k, v); }); mockHttpContext.Setup(o => o.Response).Returns(mockResponse.Object); AntiForgeryToken oldCookieToken = new AntiForgeryToken() { IsSessionToken = true }; AntiForgeryToken newCookieToken = new AntiForgeryToken() { IsSessionToken = true }; AntiForgeryToken formToken = new AntiForgeryToken(); MockAntiForgeryConfig config = new MockAntiForgeryConfig() { FormFieldName = "form-field-name", SuppressXFrameOptionsHeader = suppressXFrameOptions }; Mock<MockableAntiForgeryTokenSerializer> mockSerializer = new Mock<MockableAntiForgeryTokenSerializer>(MockBehavior.Strict); mockSerializer.Setup(o => o.Serialize(formToken)).Returns("serialized-form-token"); Mock<MockableTokenStore> mockTokenStore = new Mock<MockableTokenStore>(MockBehavior.Strict); mockTokenStore.Setup(o => o.GetCookieToken(mockHttpContext.Object)).Returns(oldCookieToken); mockTokenStore.Setup(o => o.SaveCookieToken(mockHttpContext.Object, newCookieToken)).Verifiable(); Mock<MockableTokenValidator> mockValidator = new Mock<MockableTokenValidator>(MockBehavior.Strict); mockValidator.Setup(o => o.GenerateFormToken(mockHttpContext.Object, identity, newCookieToken)).Returns(formToken); mockValidator.Setup(o => o.IsCookieTokenValid(oldCookieToken)).Returns(false); mockValidator.Setup(o => o.IsCookieTokenValid(newCookieToken)).Returns(true); mockValidator.Setup(o => o.GenerateCookieToken()).Returns(newCookieToken); AntiForgeryWorker worker = new AntiForgeryWorker( config: config, serializer: mockSerializer.Object, tokenStore: mockTokenStore.Object, validator: mockValidator.Object); HttpContextBase context = mockHttpContext.Object; // Act TagBuilder retVal = worker.GetFormInputElement(context); // Assert string xFrameOptions = context.Response.Headers["X-FRAME-OPTIONS"]; Assert.Equal(expectedHeaderValue, xFrameOptions); }
public void GetTokens_ExistingValidCookieToken() { // Arrange GenericIdentity identity = new GenericIdentity("some-user"); Mock<HttpContextBase> mockHttpContext = new Mock<HttpContextBase>(); mockHttpContext.Setup(o => o.User).Returns(new GenericPrincipal(identity, new string[0])); AntiForgeryToken cookieToken = new AntiForgeryToken() { IsSessionToken = true }; AntiForgeryToken formToken = new AntiForgeryToken(); Mock<MockableAntiForgeryTokenSerializer> mockSerializer = new Mock<MockableAntiForgeryTokenSerializer>(MockBehavior.Strict); mockSerializer.Setup(o => o.Deserialize("serialized-old-cookie-token")).Returns(cookieToken); mockSerializer.Setup(o => o.Serialize(formToken)).Returns("serialized-form-token"); Mock<MockableTokenValidator> mockValidator = new Mock<MockableTokenValidator>(MockBehavior.Strict); mockValidator.Setup(o => o.GenerateFormToken(mockHttpContext.Object, identity, cookieToken)).Returns(formToken); mockValidator.Setup(o => o.IsCookieTokenValid(cookieToken)).Returns(true); AntiForgeryWorker worker = new AntiForgeryWorker( config: new MockAntiForgeryConfig(), serializer: mockSerializer.Object, tokenStore: null, validator: mockValidator.Object); // Act string serializedNewCookieToken, serializedFormToken; worker.GetTokens(mockHttpContext.Object, "serialized-old-cookie-token", out serializedNewCookieToken, out serializedFormToken); // Assert Assert.Null(serializedNewCookieToken); Assert.Equal("serialized-form-token", serializedFormToken); }
public void Validate_FromStore_Failure() { // Arrange GenericIdentity identity = new GenericIdentity("some-user"); Mock<HttpContextBase> mockHttpContext = new Mock<HttpContextBase>(); mockHttpContext.Setup(o => o.User).Returns(new GenericPrincipal(identity, new string[0])); AntiForgeryToken cookieToken = new AntiForgeryToken(); AntiForgeryToken formToken = new AntiForgeryToken(); Mock<MockableTokenStore> mockTokenStore = new Mock<MockableTokenStore>(); mockTokenStore.Setup(o => o.GetCookieToken(mockHttpContext.Object)).Returns(cookieToken); mockTokenStore.Setup(o => o.GetFormToken(mockHttpContext.Object)).Returns(formToken); Mock<MockableTokenValidator> mockValidator = new Mock<MockableTokenValidator>(); mockValidator.Setup(o => o.ValidateTokens(mockHttpContext.Object, identity, cookieToken, formToken)).Throws(new HttpAntiForgeryException("my-message")); AntiForgeryWorker worker = new AntiForgeryWorker( config: new MockAntiForgeryConfig(), serializer: null, tokenStore: mockTokenStore.Object, validator: mockValidator.Object); // Act & assert var ex = Assert.Throws<HttpAntiForgeryException>(() => worker.Validate(mockHttpContext.Object)); Assert.Equal("my-message", ex.Message); }
private static void Validate_Helper(string cookieValue, string formValue, string username = "******") { // Arrange //ValidateAntiForgeryTokenAttribute attribute = GetAttribute(); var context = CreateContext(cookieValue, formValue, username); AntiForgeryWorker worker = new AntiForgeryWorker() { Serializer = new DummyAntiForgeryTokenSerializer() }; // Act & Assert ExceptionAssert.Throws<HttpAntiForgeryException>( delegate { //attribute.OnAuthorization(authContext); worker.Validate(context, "the real salt"); }, "A required anti-forgery token was not supplied or was invalid."); }
public void Validate_FromStore_Success() { // Arrange GenericIdentity identity = new GenericIdentity("some-user"); Mock<HttpContextBase> mockHttpContext = new Mock<HttpContextBase>(); mockHttpContext.Setup(o => o.User).Returns(new GenericPrincipal(identity, new string[0])); AntiForgeryToken cookieToken = new AntiForgeryToken(); AntiForgeryToken formToken = new AntiForgeryToken(); Mock<MockableTokenStore> mockTokenStore = new Mock<MockableTokenStore>(); mockTokenStore.Setup(o => o.GetCookieToken(mockHttpContext.Object)).Returns(cookieToken); mockTokenStore.Setup(o => o.GetFormToken(mockHttpContext.Object)).Returns(formToken); Mock<MockableTokenValidator> mockValidator = new Mock<MockableTokenValidator>(); mockValidator.Setup(o => o.ValidateTokens(mockHttpContext.Object, identity, cookieToken, formToken)).Verifiable(); AntiForgeryWorker worker = new AntiForgeryWorker( config: new MockAntiForgeryConfig(), serializer: null, tokenStore: mockTokenStore.Object, validator: mockValidator.Object); // Act worker.Validate(mockHttpContext.Object); // Assert mockValidator.Verify(); }
public void GetHtml_CreatesNewCookieValueIfCookieExistsButIsNotValid() { // Arrange AntiForgeryWorker worker = new AntiForgeryWorker() { Serializer = new DummyAntiForgeryTokenSerializer() }; var context = CreateContext("invalid"); // Act string formValue = worker.GetHtml(context, "some other salt", null, null).ToHtmlString(); // Assert Assert.True(formValue.StartsWith(_serializedValuePrefix), "Form value prefix did not match."); Match formMatch = _randomFormValueSuffixRegex.Match(formValue); string formTokenValue = formMatch.Groups["value"].Value; HttpCookie cookie = context.Response.Cookies[_antiForgeryTokenCookieName]; Assert.NotNull(cookie); Assert.True(cookie.HttpOnly, "Cookie should have HTTP-only flag set."); Assert.True(String.IsNullOrEmpty(cookie.Domain), "Domain should not have been set."); Assert.Equal("/", cookie.Path); Match cookieMatch = _randomCookieValueSuffixRegex.Match(cookie.Value); string cookieTokenValue = cookieMatch.Groups["value"].Value; Assert.Equal(formTokenValue, cookieTokenValue); }