Esempio n. 1
0
        public void GetFormToken_FormFieldIsValid_ReturnsToken()
        {
            // Arrange
            AntiForgeryToken expectedToken = new AntiForgeryToken();

            Mock <HttpContextBase> mockHttpContext = new Mock <HttpContextBase>();

            mockHttpContext.Setup(o => o.Request.Form.Get("form-field-name")).Returns("valid-value");

            MockAntiForgeryConfig config = new MockAntiForgeryConfig()
            {
                FormFieldName = "form-field-name"
            };

            Mock <MockableAntiForgeryTokenSerializer> mockSerializer = new Mock <MockableAntiForgeryTokenSerializer>();

            mockSerializer.Setup(o => o.Deserialize("valid-value")).Returns((object)expectedToken);

            AntiForgeryTokenStore tokenStore = new AntiForgeryTokenStore(
                config: config,
                serializer: mockSerializer.Object);

            // Act
            AntiForgeryToken retVal = tokenStore.GetFormToken(mockHttpContext.Object);

            // Assert
            Assert.Same(expectedToken, retVal);
        }
Esempio n. 2
0
        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);
        }
Esempio n. 3
0
        public void GetCookieToken_CookieIsEmpty_ReturnsNull()
        {
            // Arrange
            Mock <HttpContextBase> mockHttpContext = new Mock <HttpContextBase>();

            mockHttpContext.Setup(o => o.Request.Cookies).Returns(new HttpCookieCollection()
            {
                new HttpCookie("cookie-name", "")
            });

            MockAntiForgeryConfig config = new MockAntiForgeryConfig()
            {
                CookieName = "cookie-name"
            };

            AntiForgeryTokenStore tokenStore = new AntiForgeryTokenStore(
                config: config,
                serializer: null);

            // Act
            AntiForgeryToken token = tokenStore.GetCookieToken(mockHttpContext.Object);

            // Assert
            Assert.Null(token);
        }
Esempio n. 4
0
        public void ValidateTokens_AdditionalDataRejected()
        {
            // Arrange
            HttpContextBase  httpContext  = new Mock <HttpContextBase>().Object;
            IIdentity        identity     = new GenericIdentity(String.Empty);
            AntiForgeryToken sessionToken = new AntiForgeryToken()
            {
                IsSessionToken = true
            };
            AntiForgeryToken fieldtoken = new AntiForgeryToken()
            {
                SecurityToken = sessionToken.SecurityToken, Username = String.Empty, IsSessionToken = false, AdditionalData = "some-additional-data"
            };

            Mock <IAntiForgeryAdditionalDataProvider> mockAdditionalDataProvider = new Mock <IAntiForgeryAdditionalDataProvider>();

            mockAdditionalDataProvider.Setup(o => o.ValidateAdditionalData(httpContext, "some-additional-data")).Returns(false);

            MockAntiForgeryConfig config = new MockAntiForgeryConfig()
            {
                AdditionalDataProvider = mockAdditionalDataProvider.Object
            };
            TokenValidator validator = new TokenValidator(
                config: config,
                claimUidExtractor: null);

            // Act & assert
            var ex = Assert.Throws <HttpAntiForgeryException>(() => validator.ValidateTokens(httpContext, identity, sessionToken, fieldtoken));

            Assert.Equal(@"The provided anti-forgery token failed a custom data check.", ex.Message);
        }
Esempio n. 5
0
        public void ValidateTokens_FieldAndSessionTokensSwapped()
        {
            // Arrange
            HttpContextBase  httpContext  = new Mock <HttpContextBase>().Object;
            IIdentity        identity     = new Mock <IIdentity>().Object;
            AntiForgeryToken sessionToken = new AntiForgeryToken()
            {
                IsSessionToken = true
            };
            AntiForgeryToken fieldtoken = new AntiForgeryToken()
            {
                IsSessionToken = false
            };

            MockAntiForgeryConfig config = new MockAntiForgeryConfig()
            {
                CookieName    = "my-cookie-name",
                FormFieldName = "my-form-field-name"
            };
            TokenValidator validator = new TokenValidator(
                config: config,
                claimUidExtractor: null);

            // Act & assert
            var ex1 = Assert.Throws <HttpAntiForgeryException>(() => validator.ValidateTokens(httpContext, identity, fieldtoken, fieldtoken));

            Assert.Equal(@"Validation of the provided anti-forgery token failed. The cookie ""my-cookie-name"" and the form field ""my-form-field-name"" were swapped.", ex1.Message);

            var ex2 = Assert.Throws <HttpAntiForgeryException>(() => validator.ValidateTokens(httpContext, identity, sessionToken, sessionToken));

            Assert.Equal(@"Validation of the provided anti-forgery token failed. The cookie ""my-cookie-name"" and the form field ""my-form-field-name"" were swapped.", ex2.Message);
        }
Esempio n. 6
0
        public void GenerateFormToken_ClaimsBasedIdentity()
        {
            // Arrange
            AntiForgeryToken cookieToken = new AntiForgeryToken()
            {
                IsSessionToken = true
            };
            HttpContextBase httpContext = new Mock <HttpContextBase>().Object;
            IIdentity       identity    = new GenericIdentity("some-identity");

            MockAntiForgeryConfig config = new MockAntiForgeryConfig()
            {
                UniqueClaimTypeIdentifier = "unique-identifier"
            };

            BinaryBlob expectedClaimUid = new BinaryBlob(256);
            Mock <MockableClaimUidExtractor> mockClaimUidExtractor = new Mock <MockableClaimUidExtractor>();

            mockClaimUidExtractor.Setup(o => o.ExtractClaimUid(identity)).Returns((object)expectedClaimUid);

            TokenValidator validator = new TokenValidator(
                config: config,
                claimUidExtractor: mockClaimUidExtractor.Object);

            // Act
            var fieldToken = validator.GenerateFormToken(httpContext, identity, cookieToken);

            // Assert
            Assert.NotNull(fieldToken);
            Assert.Equal(cookieToken.SecurityToken, fieldToken.SecurityToken);
            Assert.False(fieldToken.IsSessionToken);
            Assert.Equal("", fieldToken.Username);
            Assert.Equal(expectedClaimUid, fieldToken.ClaimUid);
            Assert.Equal("", fieldToken.AdditionalData);
        }
Esempio n. 7
0
        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 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()
        {
            // 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);
        }
Esempio n. 10
0
        public void ValidateTokens_FieldTokenMissing()
        {
            // Arrange
            HttpContextBase  httpContext  = new Mock <HttpContextBase>().Object;
            IIdentity        identity     = new Mock <IIdentity>().Object;
            AntiForgeryToken sessionToken = new AntiForgeryToken()
            {
                IsSessionToken = true
            };
            AntiForgeryToken fieldtoken = null;

            MockAntiForgeryConfig config = new MockAntiForgeryConfig()
            {
                FormFieldName = "my-form-field-name"
            };
            TokenValidator validator = new TokenValidator(config: config, claimUidExtractor: null);

            // Act & assert
            var ex = Assert.Throws <HttpAntiForgeryException>(
                () => validator.ValidateTokens(httpContext, identity, sessionToken, fieldtoken)
                );

            Assert.Equal(
                @"The required anti-forgery form field ""my-form-field-name"" is not present.",
                ex.Message
                );
        }
Esempio n. 11
0
        public void GetCookieToken_CookieIsValid_ReturnsToken()
        {
            // Arrange
            AntiForgeryToken expectedToken = new AntiForgeryToken();

            Mock <HttpContextBase> mockHttpContext = new Mock <HttpContextBase>();

            mockHttpContext.Setup(o => o.Request.Cookies).Returns(new HttpCookieCollection()
            {
                new HttpCookie("cookie-name", "valid-value")
            });

            MockAntiForgeryConfig config = new MockAntiForgeryConfig()
            {
                CookieName = "cookie-name"
            };

            Mock <MockableAntiForgeryTokenSerializer> mockSerializer = new Mock <MockableAntiForgeryTokenSerializer>();

            mockSerializer.Setup(o => o.Deserialize("valid-value")).Returns((object)expectedToken);

            AntiForgeryTokenStore tokenStore = new AntiForgeryTokenStore(
                config: config,
                serializer: mockSerializer.Object);

            // Act
            AntiForgeryToken retVal = tokenStore.GetCookieToken(mockHttpContext.Object);

            // Assert
            Assert.Same(expectedToken, retVal);
        }
Esempio n. 12
0
        public void GenerateFormToken_AnonymousUser()
        {
            // Arrange
            AntiForgeryToken cookieToken = new AntiForgeryToken()
            {
                IsSessionToken = true
            };
            HttpContextBase  httpContext  = new Mock <HttpContextBase>().Object;
            Mock <IIdentity> mockIdentity = new Mock <IIdentity>();

            mockIdentity.Setup(o => o.IsAuthenticated).Returns(false);

            IAntiForgeryConfig config = new MockAntiForgeryConfig();

            TokenValidator validator = new TokenValidator(config: config, claimUidExtractor: null);

            // Act
            var fieldToken = validator.GenerateFormToken(
                httpContext,
                mockIdentity.Object,
                cookieToken
                );

            // Assert
            Assert.NotNull(fieldToken);
            Assert.Equal(cookieToken.SecurityToken, fieldToken.SecurityToken);
            Assert.False(fieldToken.IsSessionToken);
            Assert.Equal("", fieldToken.Username);
            Assert.Null(fieldToken.ClaimUid);
            Assert.Equal("", fieldToken.AdditionalData);
        }
Esempio n. 13
0
        public void GenerateFormToken_AuthenticatedWithoutUsernameAndNoAdditionalData_NoAdditionalData()
        {
            // Arrange
            AntiForgeryToken cookieToken = new AntiForgeryToken()
            {
                IsSessionToken = true
            };

            HttpContextBase    httpContext       = new Mock <HttpContextBase>().Object;
            IIdentity          identity          = new MyAuthenticatedIdentityWithoutUsername();
            IAntiForgeryConfig config            = new MockAntiForgeryConfig();
            IClaimUidExtractor claimUidExtractor = new Mock <MockableClaimUidExtractor>().Object;

            TokenValidator validator = new TokenValidator(
                config: config,
                claimUidExtractor: claimUidExtractor
                );

            // Act & assert
            var ex = Assert.Throws <InvalidOperationException>(
                () => validator.GenerateFormToken(httpContext, identity, cookieToken)
                );

            Assert.Equal(
                @"The provided identity of type 'System.Web.Helpers.AntiXsrf.Test.TokenValidatorTest+MyAuthenticatedIdentityWithoutUsername' 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 setting the static property AntiForgeryConfig.AdditionalDataProvider to an instance of a type that can provide some form of unique identifier for the current user.",
                ex.Message
                );
        }
Esempio n. 14
0
        public void ValidateTokens_Success_AnonymousUser()
        {
            // Arrange
            HttpContextBase  httpContext  = new Mock <HttpContextBase>().Object;
            IIdentity        identity     = new GenericIdentity(String.Empty);
            AntiForgeryToken sessionToken = new AntiForgeryToken()
            {
                IsSessionToken = true
            };
            AntiForgeryToken fieldtoken = new AntiForgeryToken()
            {
                SecurityToken  = sessionToken.SecurityToken,
                Username       = String.Empty,
                IsSessionToken = false,
                AdditionalData = "some-additional-data"
            };

            Mock <IAntiForgeryAdditionalDataProvider> mockAdditionalDataProvider =
                new Mock <IAntiForgeryAdditionalDataProvider>();

            mockAdditionalDataProvider
            .Setup(o => o.ValidateAdditionalData(httpContext, "some-additional-data"))
            .Returns(true);

            MockAntiForgeryConfig config = new MockAntiForgeryConfig()
            {
                AdditionalDataProvider = mockAdditionalDataProvider.Object
            };
            TokenValidator validator = new TokenValidator(config: config, claimUidExtractor: null);

            // Act
            validator.ValidateTokens(httpContext, identity, sessionToken, fieldtoken);
            // Assert
            // Nothing to assert - if we got this far, success!
        }
Esempio n. 15
0
        public void ValidateTokens_Success_ClaimsBasedUser()
        {
            // Arrange
            HttpContextBase  httpContext  = new Mock <HttpContextBase>().Object;
            IIdentity        identity     = new GenericIdentity("the-user");
            AntiForgeryToken sessionToken = new AntiForgeryToken()
            {
                IsSessionToken = true
            };
            AntiForgeryToken fieldtoken = new AntiForgeryToken()
            {
                SecurityToken  = sessionToken.SecurityToken,
                IsSessionToken = false,
                ClaimUid       = new BinaryBlob(256)
            };

            Mock <MockableClaimUidExtractor> mockClaimUidExtractor =
                new Mock <MockableClaimUidExtractor>();

            mockClaimUidExtractor
            .Setup(o => o.ExtractClaimUid(identity))
            .Returns(fieldtoken.ClaimUid);

            MockAntiForgeryConfig config = new MockAntiForgeryConfig();

            TokenValidator validator = new TokenValidator(
                config: config,
                claimUidExtractor: mockClaimUidExtractor.Object
                );

            // Act
            validator.ValidateTokens(httpContext, identity, sessionToken, fieldtoken);
            // Assert
            // Nothing to assert - if we got this far, success!
        }
        public void GenerateFormToken_AnonymousUser()
        {
            // Arrange
            AntiForgeryToken cookieToken = new AntiForgeryToken() { IsSessionToken = true };
            HttpContextBase httpContext = new Mock<HttpContextBase>().Object;
            Mock<IIdentity> mockIdentity = new Mock<IIdentity>();
            mockIdentity.Setup(o => o.IsAuthenticated).Returns(false);

            IAntiForgeryConfig config = new MockAntiForgeryConfig();

            TokenValidator validator = new TokenValidator(
                config: config,
                claimUidExtractor: null);

            // Act
            var fieldToken = validator.GenerateFormToken(httpContext, mockIdentity.Object, cookieToken);

            // Assert
            Assert.NotNull(fieldToken);
            Assert.Equal(cookieToken.SecurityToken, fieldToken.SecurityToken);
            Assert.False(fieldToken.IsSessionToken);
            Assert.Equal("", fieldToken.Username);
            Assert.Equal(null, fieldToken.ClaimUid);
            Assert.Equal("", fieldToken.AdditionalData);
        }
Esempio n. 17
0
        public void GenerateFormToken_AuthenticatedWithoutUsernameAndNoAdditionalData_NoAdditionalData_SuppressHeuristics()
        {
            // Arrange
            AntiForgeryToken cookieToken = new AntiForgeryToken()
            {
                IsSessionToken = true
            };
            HttpContextBase httpContext = new Mock <HttpContextBase>().Object;
            IIdentity       identity    = new MyAuthenticatedIdentityWithoutUsername();

            IAntiForgeryConfig config = new MockAntiForgeryConfig()
            {
                SuppressIdentityHeuristicChecks = true
            };
            IClaimUidExtractor claimUidExtractor = new Mock <MockableClaimUidExtractor>().Object;

            TokenValidator validator = new TokenValidator(
                config: config,
                claimUidExtractor: claimUidExtractor
                );

            // Act
            var fieldToken = validator.GenerateFormToken(httpContext, identity, cookieToken);

            // Assert
            Assert.NotNull(fieldToken);
            Assert.Equal(cookieToken.SecurityToken, fieldToken.SecurityToken);
            Assert.False(fieldToken.IsSessionToken);
            Assert.Equal("", fieldToken.Username);
            Assert.Null(fieldToken.ClaimUid);
            Assert.Equal("", fieldToken.AdditionalData);
        }
        public void ExtractClaimUid_ClaimsIdentity()
        {
            // Arrange
            Mock <IIdentity> mockIdentity = new Mock <IIdentity>();

            mockIdentity.Setup(o => o.IsAuthenticated).Returns(true);
            MockAntiForgeryConfig config = new MockAntiForgeryConfig()
            {
                UniqueClaimTypeIdentifier = "unique-identifier"
            };
            ClaimsIdentityConverter converter = new ClaimsIdentityConverter(new Func <IIdentity, ClaimsIdentity>[] {
                identity =>
                {
                    Assert.Equal(mockIdentity.Object, identity);
                    MockClaimsIdentity claimsIdentity = new MockClaimsIdentity();
                    claimsIdentity.AddClaim("unique-identifier", "some-value");
                    return(claimsIdentity);
                }
            });

            ClaimUidExtractor extractor = new ClaimUidExtractor(
                config: config,
                claimsIdentityConverter: converter);

            // Act
            BinaryBlob retVal = extractor.ExtractClaimUid(mockIdentity.Object);

            // Assert
            Assert.NotNull(retVal);
            Assert.Equal("CA9CCFF86F903FBB7505BAAA9F222E49EC2A1E8FAD630AE73DE180BD679751ED", HexUtil.HexEncode(retVal.GetData()));
        }
Esempio n. 19
0
        public void GenerateFormToken_AuthenticatedWithoutUsername_WithAdditionalData()
        {
            // Arrange
            AntiForgeryToken cookieToken = new AntiForgeryToken()
            {
                IsSessionToken = true
            };
            HttpContextBase httpContext = new Mock <HttpContextBase>().Object;
            IIdentity       identity    = new MyAuthenticatedIdentityWithoutUsername();

            Mock <IAntiForgeryAdditionalDataProvider> mockAdditionalDataProvider = new Mock <IAntiForgeryAdditionalDataProvider>();

            mockAdditionalDataProvider.Setup(o => o.GetAdditionalData(httpContext)).Returns("additional-data");

            IAntiForgeryConfig config = new MockAntiForgeryConfig()
            {
                AdditionalDataProvider = mockAdditionalDataProvider.Object
            };
            IClaimUidExtractor claimUidExtractor = new Mock <MockableClaimUidExtractor>().Object;

            TokenValidator validator = new TokenValidator(
                config: config,
                claimUidExtractor: claimUidExtractor);

            // Act
            var fieldToken = validator.GenerateFormToken(httpContext, identity, cookieToken);

            // Assert
            Assert.NotNull(fieldToken);
            Assert.Equal(cookieToken.SecurityToken, fieldToken.SecurityToken);
            Assert.False(fieldToken.IsSessionToken);
            Assert.Equal("", fieldToken.Username);
            Assert.Equal(null, fieldToken.ClaimUid);
            Assert.Equal("additional-data", fieldToken.AdditionalData);
        }
        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 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 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 ExtractClaimUid_NotAClaimsIdentity()
        {
            // Arrange
            Mock<IIdentity> mockIdentity = new Mock<IIdentity>();
            mockIdentity.Setup(o => o.IsAuthenticated).Returns(true);
            MockAntiForgeryConfig config = new MockAntiForgeryConfig();
            ClaimsIdentityConverter converter = new ClaimsIdentityConverter(new Func<IIdentity, ClaimsIdentity>[0]);

            ClaimUidExtractor extractor = new ClaimUidExtractor(
                config: config,
                claimsIdentityConverter: converter);

            // Act
            BinaryBlob retVal = extractor.ExtractClaimUid(mockIdentity.Object);

            // Assert
            Assert.Null(retVal);
        }
        public void ExtractClaimUid_ClaimsIdentityHeuristicsSuppressed()
        {
            // Arrange
            GenericIdentity       identity = new GenericIdentity("the-user");
            MockAntiForgeryConfig config   = new MockAntiForgeryConfig()
            {
                SuppressIdentityHeuristicChecks = true
            };

            ClaimUidExtractor extractor = new ClaimUidExtractor(
                config: config,
                claimsIdentityConverter: null);

            // Act
            BinaryBlob retVal = extractor.ExtractClaimUid(identity);

            // Assert
            Assert.Null(retVal);
        }
        public void ExtractClaimUid_ClaimsIdentityHeuristicsSuppressed()
        {
            // Arrange
            GenericIdentity identity = new GenericIdentity("the-user");
            MockAntiForgeryConfig config = new MockAntiForgeryConfig()
            {
                SuppressIdentityHeuristicChecks = true
            };

            ClaimUidExtractor extractor = new ClaimUidExtractor(
                config: config,
                claimsIdentityConverter: null);

            // Act
            BinaryBlob retVal = extractor.ExtractClaimUid(identity);

            // Assert
            Assert.Null(retVal);
        }
        public void ExtractClaimUid_NotAClaimsIdentity()
        {
            // Arrange
            Mock <IIdentity> mockIdentity = new Mock <IIdentity>();

            mockIdentity.Setup(o => o.IsAuthenticated).Returns(true);
            MockAntiForgeryConfig   config    = new MockAntiForgeryConfig();
            ClaimsIdentityConverter converter = new ClaimsIdentityConverter(new Func <IIdentity, ClaimsIdentity> [0]);

            ClaimUidExtractor extractor = new ClaimUidExtractor(
                config: config,
                claimsIdentityConverter: converter);

            // Act
            BinaryBlob retVal = extractor.ExtractClaimUid(mockIdentity.Object);

            // Assert
            Assert.Null(retVal);
        }
        public void GenerateFormToken_AuthenticatedWithoutUsernameAndNoAdditionalData_NoAdditionalData()
        {
            // Arrange
            AntiForgeryToken cookieToken = new AntiForgeryToken()
            {
                IsSessionToken = true
            };

            HttpContextBase httpContext = new Mock<HttpContextBase>().Object;
            IIdentity identity = new MyAuthenticatedIdentityWithoutUsername();
            IAntiForgeryConfig config = new MockAntiForgeryConfig();
            IClaimUidExtractor claimUidExtractor = new Mock<MockableClaimUidExtractor>().Object;

            TokenValidator validator = new TokenValidator(
                config: config,
                claimUidExtractor: claimUidExtractor);

            // Act & assert
            var ex = Assert.Throws<InvalidOperationException>(() => validator.GenerateFormToken(httpContext, identity, cookieToken));
            Assert.Equal(@"The provided identity of type 'System.Web.Helpers.AntiXsrf.Test.TokenValidatorTest+MyAuthenticatedIdentityWithoutUsername' 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 setting the static property AntiForgeryConfig.AdditionalDataProvider to an instance of a type that can provide some form of unique identifier for the current user.", ex.Message);
        }
        public void GetCookieToken_CookieDoesNotExist_ReturnsNull()
        {
            // Arrange
            Mock<HttpContextBase> mockHttpContext = new Mock<HttpContextBase>();
            mockHttpContext.Setup(o => o.Request.Cookies).Returns(new HttpCookieCollection());

            MockAntiForgeryConfig config = new MockAntiForgeryConfig()
            {
                CookieName = "cookie-name"
            };

            AntiForgeryTokenStore tokenStore = new AntiForgeryTokenStore(
                config: config,
                serializer: null);

            // Act
            AntiForgeryToken token = tokenStore.GetCookieToken(mockHttpContext.Object);

            // Assert
            Assert.Null(token);
        }
        public void SaveCookieToken(bool requireSsl, bool?expectedCookieSecureFlag)
        {
            // Arrange
            AntiForgeryToken     token    = new AntiForgeryToken();
            HttpCookieCollection cookies  = new HttpCookieCollection();
            bool defaultCookieSecureValue =
                expectedCookieSecureFlag ?? new HttpCookie("name", "value").Secure; // pulled from config; set by ctor

            Mock <HttpContextBase> mockHttpContext = new Mock <HttpContextBase>();

            mockHttpContext.Setup(o => o.Response.Cookies).Returns(cookies);

            Mock <MockableAntiForgeryTokenSerializer> mockSerializer =
                new Mock <MockableAntiForgeryTokenSerializer>();

            mockSerializer.Setup(o => o.Serialize(token)).Returns("serialized-value");

            MockAntiForgeryConfig config = new MockAntiForgeryConfig()
            {
                CookieName = "cookie-name",
                RequireSSL = requireSsl
            };

            AntiForgeryTokenStore tokenStore = new AntiForgeryTokenStore(
                config: config,
                serializer: mockSerializer.Object
                );

            // Act
            tokenStore.SaveCookieToken(mockHttpContext.Object, token);

            // Assert
            Assert.Single(cookies);
            HttpCookie cookie = cookies["cookie-name"];

            Assert.NotNull(cookie);
            Assert.Equal("serialized-value", cookie.Value);
            Assert.True(cookie.HttpOnly);
            Assert.Equal(defaultCookieSecureValue, cookie.Secure);
        }
Esempio n. 30
0
        public void GetFormToken_FormFieldIsEmpty_ReturnsNull()
        {
            // Arrange
            Mock <HttpContextBase> mockHttpContext = new Mock <HttpContextBase>();

            mockHttpContext.Setup(o => o.Request.Form.Get("form-field-name")).Returns("");

            MockAntiForgeryConfig config = new MockAntiForgeryConfig()
            {
                FormFieldName = "form-field-name"
            };

            AntiForgeryTokenStore tokenStore = new AntiForgeryTokenStore(
                config: config,
                serializer: null);

            // Act
            AntiForgeryToken token = tokenStore.GetFormToken(mockHttpContext.Object);

            // Assert
            Assert.Null(token);
        }
        public void GetFormToken_FormFieldIsEmpty_ReturnsNull()
        {
            // Arrange
            Mock<HttpContextBase> mockHttpContext = new Mock<HttpContextBase>();
            mockHttpContext.Setup(o => o.Request.Form.Get("form-field-name")).Returns("");

            MockAntiForgeryConfig config = new MockAntiForgeryConfig()
            {
                FormFieldName = "form-field-name"
            };

            AntiForgeryTokenStore tokenStore = new AntiForgeryTokenStore(
                config: config,
                serializer: null);

            // Act
            AntiForgeryToken token = tokenStore.GetFormToken(mockHttpContext.Object);

            // Assert
            Assert.Null(token);
        }
        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 void GetFormToken_FormFieldIsValid_ReturnsToken()
        {
            // Arrange
            AntiForgeryToken expectedToken = new AntiForgeryToken();

            Mock<HttpContextBase> mockHttpContext = new Mock<HttpContextBase>();
            mockHttpContext.Setup(o => o.Request.Form.Get("form-field-name")).Returns("valid-value");

            MockAntiForgeryConfig config = new MockAntiForgeryConfig()
            {
                FormFieldName = "form-field-name"
            };

            Mock<MockableAntiForgeryTokenSerializer> mockSerializer = new Mock<MockableAntiForgeryTokenSerializer>();
            mockSerializer.Setup(o => o.Deserialize("valid-value")).Returns((object)expectedToken);

            AntiForgeryTokenStore tokenStore = new AntiForgeryTokenStore(
                config: config,
                serializer: mockSerializer.Object);

            // Act
            AntiForgeryToken retVal = tokenStore.GetFormToken(mockHttpContext.Object);

            // Assert
            Assert.Same(expectedToken, retVal);
        }
        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 SaveCookieToken(bool requireSsl, bool? expectedCookieSecureFlag)
        {
            // Arrange
            AntiForgeryToken token = new AntiForgeryToken();
            HttpCookieCollection cookies = new HttpCookieCollection();
            bool defaultCookieSecureValue = expectedCookieSecureFlag ?? new HttpCookie("name", "value").Secure; // pulled from config; set by ctor

            Mock<HttpContextBase> mockHttpContext = new Mock<HttpContextBase>();
            mockHttpContext.Setup(o => o.Response.Cookies).Returns(cookies);

            Mock<MockableAntiForgeryTokenSerializer> mockSerializer = new Mock<MockableAntiForgeryTokenSerializer>();
            mockSerializer.Setup(o => o.Serialize(token)).Returns("serialized-value");

            MockAntiForgeryConfig config = new MockAntiForgeryConfig()
            {
                CookieName = "cookie-name",
                RequireSSL = requireSsl
            };

            AntiForgeryTokenStore tokenStore = new AntiForgeryTokenStore(
                config: config,
                serializer: mockSerializer.Object);

            // Act
            tokenStore.SaveCookieToken(mockHttpContext.Object, token);

            // Assert
            Assert.Equal(1, cookies.Count);
            HttpCookie cookie = cookies["cookie-name"];

            Assert.NotNull(cookie);
            Assert.Equal("serialized-value", cookie.Value);
            Assert.True(cookie.HttpOnly);
            Assert.Equal(defaultCookieSecureValue, cookie.Secure);
        }
        public void GenerateFormToken_AuthenticatedWithoutUsername_WithAdditionalData()
        {
            // Arrange
            AntiForgeryToken cookieToken = new AntiForgeryToken() { IsSessionToken = true };
            HttpContextBase httpContext = new Mock<HttpContextBase>().Object;
            IIdentity identity = new MyAuthenticatedIdentityWithoutUsername();

            Mock<IAntiForgeryAdditionalDataProvider> mockAdditionalDataProvider = new Mock<IAntiForgeryAdditionalDataProvider>();
            mockAdditionalDataProvider.Setup(o => o.GetAdditionalData(httpContext)).Returns("additional-data");

            IAntiForgeryConfig config = new MockAntiForgeryConfig()
            {
                AdditionalDataProvider = mockAdditionalDataProvider.Object
            };
            IClaimUidExtractor claimUidExtractor = new Mock<MockableClaimUidExtractor>().Object;

            TokenValidator validator = new TokenValidator(
                config: config,
                claimUidExtractor: claimUidExtractor);

            // Act
            var fieldToken = validator.GenerateFormToken(httpContext, identity, cookieToken);

            // Assert
            Assert.NotNull(fieldToken);
            Assert.Equal(cookieToken.SecurityToken, fieldToken.SecurityToken);
            Assert.False(fieldToken.IsSessionToken);
            Assert.Equal("", fieldToken.Username);
            Assert.Equal(null, fieldToken.ClaimUid);
            Assert.Equal("additional-data", fieldToken.AdditionalData);
        }
        public void ValidateTokens_AdditionalDataRejected()
        {
            // Arrange
            HttpContextBase httpContext = new Mock<HttpContextBase>().Object;
            IIdentity identity = new GenericIdentity(String.Empty);
            AntiForgeryToken sessionToken = new AntiForgeryToken() { IsSessionToken = true };
            AntiForgeryToken fieldtoken = new AntiForgeryToken() { SecurityToken = sessionToken.SecurityToken, Username = String.Empty, IsSessionToken = false, AdditionalData = "some-additional-data" };

            Mock<IAntiForgeryAdditionalDataProvider> mockAdditionalDataProvider = new Mock<IAntiForgeryAdditionalDataProvider>();
            mockAdditionalDataProvider.Setup(o => o.ValidateAdditionalData(httpContext, "some-additional-data")).Returns(false);

            MockAntiForgeryConfig config = new MockAntiForgeryConfig()
            {
                AdditionalDataProvider = mockAdditionalDataProvider.Object
            };
            TokenValidator validator = new TokenValidator(
                config: config,
                claimUidExtractor: null);

            // Act & assert
            var ex = Assert.Throws<HttpAntiForgeryException>(() => validator.ValidateTokens(httpContext, identity, sessionToken, fieldtoken));
            Assert.Equal(@"The provided anti-forgery token failed a custom data check.", ex.Message);
        }
        public void ExtractClaimUid_ClaimsIdentity()
        {
            // Arrange
            Mock<IIdentity> mockIdentity = new Mock<IIdentity>();
            mockIdentity.Setup(o => o.IsAuthenticated).Returns(true);
            MockAntiForgeryConfig config = new MockAntiForgeryConfig()
            {
                UniqueClaimTypeIdentifier = "unique-identifier"
            };
            ClaimsIdentityConverter converter = new ClaimsIdentityConverter(new Func<IIdentity, ClaimsIdentity>[] {
               identity =>
               {
                   Assert.Equal(mockIdentity.Object, identity);
                   MockClaimsIdentity claimsIdentity = new MockClaimsIdentity();
                   claimsIdentity.AddClaim("unique-identifier", "some-value");
                   return claimsIdentity;
               }
            });

            ClaimUidExtractor extractor = new ClaimUidExtractor(
                config: config,
                claimsIdentityConverter: converter);

            // Act
            BinaryBlob retVal = extractor.ExtractClaimUid(mockIdentity.Object);

            // Assert
            Assert.NotNull(retVal);
            Assert.Equal("CA9CCFF86F903FBB7505BAAA9F222E49EC2A1E8FAD630AE73DE180BD679751ED", HexUtil.HexEncode(retVal.GetData()));
        }
        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 GenerateFormToken_ClaimsBasedIdentity()
        {
            // Arrange
            AntiForgeryToken cookieToken = new AntiForgeryToken() { IsSessionToken = true };
            HttpContextBase httpContext = new Mock<HttpContextBase>().Object;
            IIdentity identity = new GenericIdentity("some-identity");

            MockAntiForgeryConfig config = new MockAntiForgeryConfig()
            {
                UniqueClaimTypeIdentifier = "unique-identifier"
            };

            BinaryBlob expectedClaimUid = new BinaryBlob(256);
            Mock<MockableClaimUidExtractor> mockClaimUidExtractor = new Mock<MockableClaimUidExtractor>();
            mockClaimUidExtractor.Setup(o => o.ExtractClaimUid(identity)).Returns((object)expectedClaimUid);

            TokenValidator validator = new TokenValidator(
                config: config,
                claimUidExtractor: mockClaimUidExtractor.Object);

            // Act
            var fieldToken = validator.GenerateFormToken(httpContext, identity, cookieToken);

            // Assert
            Assert.NotNull(fieldToken);
            Assert.Equal(cookieToken.SecurityToken, fieldToken.SecurityToken);
            Assert.False(fieldToken.IsSessionToken);
            Assert.Equal("", fieldToken.Username);
            Assert.Equal(expectedClaimUid, fieldToken.ClaimUid);
            Assert.Equal("", fieldToken.AdditionalData);
        }
        public void ValidateTokens_FieldTokenMissing()
        {
            // Arrange
            HttpContextBase httpContext = new Mock<HttpContextBase>().Object;
            IIdentity identity = new Mock<IIdentity>().Object;
            AntiForgeryToken sessionToken = new AntiForgeryToken() { IsSessionToken = true };
            AntiForgeryToken fieldtoken = null;

            MockAntiForgeryConfig config = new MockAntiForgeryConfig()
            {
                FormFieldName = "my-form-field-name"
            };
            TokenValidator validator = new TokenValidator(
                config: config,
                claimUidExtractor: null);

            // Act & assert
            var ex = Assert.Throws<HttpAntiForgeryException>(() => validator.ValidateTokens(httpContext, identity, sessionToken, fieldtoken));
            Assert.Equal(@"The required anti-forgery form field ""my-form-field-name"" is not present.", ex.Message);
        }
        public void ValidateTokens_FieldAndSessionTokensSwapped()
        {
            // Arrange
            HttpContextBase httpContext = new Mock<HttpContextBase>().Object;
            IIdentity identity = new Mock<IIdentity>().Object;
            AntiForgeryToken sessionToken = new AntiForgeryToken() { IsSessionToken = true };
            AntiForgeryToken fieldtoken = new AntiForgeryToken() { IsSessionToken = false };

            MockAntiForgeryConfig config = new MockAntiForgeryConfig()
            {
                CookieName = "my-cookie-name",
                FormFieldName = "my-form-field-name"
            };
            TokenValidator validator = new TokenValidator(
                config: config,
                claimUidExtractor: null);

            // Act & assert
            var ex1 = Assert.Throws<HttpAntiForgeryException>(() => validator.ValidateTokens(httpContext, identity, fieldtoken, fieldtoken));
            Assert.Equal(@"Validation of the provided anti-forgery token failed. The cookie ""my-cookie-name"" and the form field ""my-form-field-name"" were swapped.", ex1.Message);

            var ex2 = Assert.Throws<HttpAntiForgeryException>(() => validator.ValidateTokens(httpContext, identity, sessionToken, sessionToken));
            Assert.Equal(@"Validation of the provided anti-forgery token failed. The cookie ""my-cookie-name"" and the form field ""my-form-field-name"" were swapped.", ex2.Message);
        }
        public void ValidateTokens_Success_ClaimsBasedUser()
        {
            // Arrange
            HttpContextBase httpContext = new Mock<HttpContextBase>().Object;
            IIdentity identity = new GenericIdentity("the-user");
            AntiForgeryToken sessionToken = new AntiForgeryToken() { IsSessionToken = true };
            AntiForgeryToken fieldtoken = new AntiForgeryToken() { SecurityToken = sessionToken.SecurityToken, IsSessionToken = false, ClaimUid = new BinaryBlob(256) };

            Mock<MockableClaimUidExtractor> mockClaimUidExtractor = new Mock<MockableClaimUidExtractor>();
            mockClaimUidExtractor.Setup(o => o.ExtractClaimUid(identity)).Returns(fieldtoken.ClaimUid);

            MockAntiForgeryConfig config = new MockAntiForgeryConfig();

            TokenValidator validator = new TokenValidator(
                config: config,
                claimUidExtractor: mockClaimUidExtractor.Object);

            // Act
            validator.ValidateTokens(httpContext, identity, sessionToken, fieldtoken);

            // Assert
            // Nothing to assert - if we got this far, success!
        }
        public void GetCookieToken_CookieIsValid_ReturnsToken()
        {
            // Arrange
            AntiForgeryToken expectedToken = new AntiForgeryToken();

            Mock<HttpContextBase> mockHttpContext = new Mock<HttpContextBase>();
            mockHttpContext.Setup(o => o.Request.Cookies).Returns(new HttpCookieCollection()
            {
                new HttpCookie("cookie-name", "valid-value")
            });

            MockAntiForgeryConfig config = new MockAntiForgeryConfig()
            {
                CookieName = "cookie-name"
            };

            Mock<MockableAntiForgeryTokenSerializer> mockSerializer = new Mock<MockableAntiForgeryTokenSerializer>();
            mockSerializer.Setup(o => o.Deserialize("valid-value")).Returns((object)expectedToken);

            AntiForgeryTokenStore tokenStore = new AntiForgeryTokenStore(
                config: config,
                serializer: mockSerializer.Object);

            // Act
            AntiForgeryToken retVal = tokenStore.GetCookieToken(mockHttpContext.Object);

            // Assert
            Assert.Same(expectedToken, retVal);
        }
        public void GenerateFormToken_AuthenticatedWithoutUsernameAndNoAdditionalData_NoAdditionalData_SuppressHeuristics()
        {
            // Arrange
            AntiForgeryToken cookieToken = new AntiForgeryToken() { IsSessionToken = true };
            HttpContextBase httpContext = new Mock<HttpContextBase>().Object;
            IIdentity identity = new MyAuthenticatedIdentityWithoutUsername();

            IAntiForgeryConfig config = new MockAntiForgeryConfig()
            {
                SuppressIdentityHeuristicChecks = true
            };
            IClaimUidExtractor claimUidExtractor = new Mock<MockableClaimUidExtractor>().Object;

            TokenValidator validator = new TokenValidator(
                config: config,
                claimUidExtractor: claimUidExtractor);

            // Act
            var fieldToken = validator.GenerateFormToken(httpContext, identity, cookieToken);

            // Assert
            Assert.NotNull(fieldToken);
            Assert.Equal(cookieToken.SecurityToken, fieldToken.SecurityToken);
            Assert.False(fieldToken.IsSessionToken);
            Assert.Equal("", fieldToken.Username);
            Assert.Equal(null, fieldToken.ClaimUid);
            Assert.Equal("", fieldToken.AdditionalData);
        }
        public void ValidateTokens_Success_AuthenticatedUserWithUsername()
        {
            // Arrange
            HttpContextBase httpContext = new Mock<HttpContextBase>().Object;
            IIdentity identity = new GenericIdentity("the-user");
            AntiForgeryToken sessionToken = new AntiForgeryToken() { IsSessionToken = true };
            AntiForgeryToken fieldtoken = new AntiForgeryToken() { SecurityToken = sessionToken.SecurityToken, Username = "******", IsSessionToken = false, AdditionalData = "some-additional-data" };

            Mock<IAntiForgeryAdditionalDataProvider> mockAdditionalDataProvider = new Mock<IAntiForgeryAdditionalDataProvider>();
            mockAdditionalDataProvider.Setup(o => o.ValidateAdditionalData(httpContext, "some-additional-data")).Returns(true);

            MockAntiForgeryConfig config = new MockAntiForgeryConfig()
            {
                AdditionalDataProvider = mockAdditionalDataProvider.Object
            };
            TokenValidator validator = new TokenValidator(
                config: config,
                claimUidExtractor: new Mock<MockableClaimUidExtractor>().Object);

            // Act
            validator.ValidateTokens(httpContext, identity, sessionToken, fieldtoken);

            // Assert
            // Nothing to assert - if we got this far, success!
        }