Пример #1
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);
        }
Пример #2
0
        /// <summary>
        /// Digest
        /// </summary>
        /// <typeparam name="T">T</typeparam>
        /// <param name="items">Items</param>
        /// <param name="objectId">Object Id</param>
        /// <returns>Log History</returns>
        public LogHistory <T> Digest <T>(IEnumerable <T> items, string objectId)
            where T : LogItem
        {
            Contract.Requires <ArgumentException>(!string.IsNullOrWhiteSpace(objectId));

            Contract.Ensures(Contract.Result <LogHistory <T> >() != null);

            using (new PerformanceMonitor())
            {
                var history = new LogHistory <T>();

                try
                {
                    if (null != items && 0 < items.Count())
                    {
                        history.GeneratedOn = DateTime.UtcNow;
                        history.Count       = items.Count();
                        history.Items       = items.ToArray();
                        history.MinimumDate = items.Select(m => m.OccurredOn).Min();
                        history.MaximumDate = items.Select(m => m.OccurredOn).Max();

                        var blob = new BinaryBlob <LogHistory <T> >(ServerConfiguration.Default);
                        blob.Save(objectId, history);
                    }
                }
                catch (Exception ex)
                {
                    this.Log(ex, EventTypes.Error, (int)ServiceFault.BlobDigest);
                }

                return(history);
            }
        }
        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()));
        }
Пример #4
0
        public void Equals_DifferentData_ReturnsFalse()
        {
            // Arrange
            object blobA = new BinaryBlob(32, new byte[] { 0x01, 0x02, 0x03, 0x04 });
            object blobB = new BinaryBlob(32, new byte[] { 0x04, 0x03, 0x02, 0x01 });

            // Act & assert
            Assert.NotEqual(blobA, blobB);
        }
Пример #5
0
        public void Equals_SameData_ReturnsTrue()
        {
            // Arrange
            object blobA = new BinaryBlob(32, new byte[] { 0x01, 0x02, 0x03, 0x04 });
            object blobB = new BinaryBlob(32, new byte[] { 0x01, 0x02, 0x03, 0x04 });

            // Act & assert
            Assert.Equal(blobA, blobB);
        }
Пример #6
0
        public void Equals_NotABlob_ReturnsFalse()
        {
            // Arrange
            object blobA = new BinaryBlob(32);
            object blobB = "hello";

            // Act & assert
            Assert.NotEqual(blobA, blobB);
        }
Пример #7
0
        public void Ctor_BitLength_ProducesDifferentValues()
        {
            // Act
            BinaryBlob blobA = new BinaryBlob(bitLength: 64);
            BinaryBlob blobB = new BinaryBlob(bitLength: 64);

            // Assert
            Assert.NotEqual(blobA.GetData(), blobB.GetData());
        }
Пример #8
0
        public void Equals_DifferentData_ReturnsFalse()
        {
            // Arrange
            object blobA = new BinaryBlob(32, new byte[] { 0x01, 0x02, 0x03, 0x04 });
            object blobB = new BinaryBlob(32, new byte[] { 0x04, 0x03, 0x02, 0x01 });

            // Act & assert
            Assert.NotEqual(blobA, blobB);
        }
Пример #9
0
        public void Equals_NotABlob_ReturnsFalse()
        {
            // Arrange
            object blobA = new BinaryBlob(32);
            object blobB = "hello";

            // Act & assert
            Assert.NotEqual(blobA, blobB);
        }
Пример #10
0
        public void Equals_Null_ReturnsFalse()
        {
            // Arrange
            object blobA = new BinaryBlob(32);
            object blobB = null;

            // Act & assert
            Assert.NotEqual(blobA, blobB);
        }
Пример #11
0
        public void Ctor_BitLength_ProducesDifferentValues()
        {
            // Act
            BinaryBlob blobA = new BinaryBlob(bitLength: 64);
            BinaryBlob blobB = new BinaryBlob(bitLength: 64);

            // Assert
            Assert.NotEqual(blobA.GetData(), blobB.GetData());
        }
Пример #12
0
 /// <summary>
 /// Get Object from Blob
 /// </summary>
 /// <typeparam name="T">Log Item</typeparam>
 /// <param name="objectId">Object Identifier</param>
 /// <returns>Log History</returns>
 private LogHistory <T> Get <T>(string objectId)
     where T : LogItem
 {
     using (var perf = new PerformanceMonitor())
     {
         perf.Append("Pulling from blob storage.");
         var blob = new BinaryBlob <LogHistory <T> >(ServerConfiguration.Default);
         return(blob.GetDigest <LogHistory <T> >(objectId));
     }
 }
Пример #13
0
        public void Ctor_BitLength()
        {
            // Act
            BinaryBlob blob = new BinaryBlob(bitLength: 64);
            byte[] data = blob.GetData();

            // Assert
            Assert.Equal(64, blob.BitLength);
            Assert.Equal(64 / 8, data.Length);
            Assert.NotEqual(new byte[64 / 8], data); // should not be a zero-filled array
        }
Пример #14
0
        public void Ctor_BitLength()
        {
            // Act
            var blob = new BinaryBlob(bitLength: 64);
            var data = blob.GetData();

            // Assert
            Assert.Equal(64, blob.BitLength);
            Assert.Equal(64 / 8, data.Length);
            Assert.NotEqual(new byte[64 / 8], data); // should not be a zero-filled array
        }
Пример #15
0
        public void Ctor_Data()
        {
            // Arrange
            byte[] expectedData = new byte[] { 0x01, 0x02, 0x03, 0x04 };

            // Act
            BinaryBlob blob = new BinaryBlob(32, expectedData);

            // Assert
            Assert.Equal(32, blob.BitLength);
            Assert.Equal(expectedData, blob.GetData());
        }
Пример #16
0
        public void Ctor_Data()
        {
            // Arrange
            byte[] expectedData = new byte[] { 0x01, 0x02, 0x03, 0x04 };

            // Act
            BinaryBlob blob = new BinaryBlob(32, expectedData);

            // Assert
            Assert.Equal(32, blob.BitLength);
            Assert.Equal(expectedData, blob.GetData());
        }
        public void ExtractClaimUid_NullIdentity()
        {
            // Arrange
            ClaimUidExtractor extractor = new ClaimUidExtractor(
                config: null,
                claimsIdentityConverter: null);

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

            // Assert
            Assert.Null(retVal);
        }
Пример #18
0
        public void SecurityTokenProperty_PropertySetter_DoesNotUseDefaults()
        {
            // Arrange
            var token = new AntiForgeryToken();

            // Act
            var securityToken = new BinaryBlob(64);

            token.SecurityToken = securityToken;

            // Assert
            Assert.Equal(securityToken, token.SecurityToken);
        }
Пример #19
0
        public void GetHashCodeTest()
        {
            // Arrange
            byte[] blobData         = new byte[] { 0x01, 0x02, 0x03, 0x04 };
            int    expectedHashCode = BitConverter.ToInt32(blobData, 0);

            BinaryBlob blob = new BinaryBlob(32, blobData);

            // Act
            int actualHashCode = blob.GetHashCode();

            // Assert
            Assert.Equal(expectedHashCode, actualHashCode);
        }
Пример #20
0
        public void RoundTrip()
        {
            var random   = new Random();
            var objectId = Guid.NewGuid().ToString().Replace("-", string.Empty);
            var blob     = new BinaryBlob <SerializeMePlease>(CloudStorageAccount.DevelopmentStorageAccount);
            var data     = new SerializeMePlease()
            {
                Identifier = Guid.NewGuid(),
            };

            blob.Save(objectId, data);

            var got = blob.Get(objectId);

            Assert.AreEqual <Guid>(data.Identifier, got.Identifier);
        }
Пример #21
0
        public void ClaimUidProperty()
        {
            // Arrange
            var token = new AntiForgeryToken();

            // Act & assert - 1
            Assert.Null(token.ClaimUid);

            // Act & assert - 2
            BinaryBlob blob = new BinaryBlob(32);
            token.ClaimUid = blob;
            Assert.Equal(blob, token.ClaimUid);

            // Act & assert - 3
            token.ClaimUid = null;
            Assert.Null(token.ClaimUid);
        }
        public void ExtractClaimUid_Unauthenticated()
        {
            // Arrange
            ClaimUidExtractor extractor = new ClaimUidExtractor(
                config: null,
                claimsIdentityConverter: null);

            Mock <IIdentity> mockIdentity = new Mock <IIdentity>();

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

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

            // Assert
            Assert.Null(retVal);
        }
Пример #23
0
        private void SetupFileUpload(IKernel kernel, IAppBuilder app)
        {
            app.Map("/upload-file", map =>
            {
                var uploadHandler = kernel.Get <UploadCallbackHandler>();

                map.Run(async context =>
                {
                    if (!context.Request.Method.Equals("POST", StringComparison.OrdinalIgnoreCase))
                    {
                        context.Response.StatusCode = 404;
                    }
                    else if (!context.Request.User.IsAuthenticated())
                    {
                        context.Response.StatusCode = 403;
                    }
                    else
                    {
                        var form = await context.Request.ReadFormAsync();

                        string roomName     = form["room"];
                        string connectionId = form["connectionId"];
                        string file         = form["file"];
                        string fileName     = form["filename"];
                        string contentType  = form["type"];

                        BinaryBlob binaryBlob = BinaryBlob.Parse(file);

                        if (String.IsNullOrEmpty(contentType))
                        {
                            contentType = "application/octet-stream";
                        }

                        var stream = new MemoryStream(binaryBlob.Data);

                        await uploadHandler.Upload(context.Request.User.GetUserId(),
                                                   connectionId,
                                                   roomName,
                                                   fileName,
                                                   contentType,
                                                   stream);
                    }
                });
            });
        }
Пример #24
0
        public void ClaimUidProperty()
        {
            // Arrange
            var token = new AntiForgeryToken();

            // Act & assert - 1
            Assert.Null(token.ClaimUid);

            // Act & assert - 2
            BinaryBlob blob = new BinaryBlob(32);

            token.ClaimUid = blob;
            Assert.Equal(blob, token.ClaimUid);

            // Act & assert - 3
            token.ClaimUid = null;
            Assert.Null(token.ClaimUid);
        }
        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);
        }
Пример #27
0
        /// <summary>
        /// Get Digest History
        /// </summary>
        /// <typeparam name="T">T</typeparam>
        /// <param name="blob">Blob</param>
        /// <param name="objectId">Object Identifier</param>
        /// <returns>Log History</returns>
        public static T GetDigest <T>(this BinaryBlob <T> blob, string objectId)
        {
            Contract.Requires <ArgumentException>(!string.IsNullOrWhiteSpace(objectId));

            try
            {
                using (var perf = new PerformanceMonitor())
                {
                    perf.Append(objectId);
                    return(blob.Get(objectId));
                }
            }
            catch (Exception ex)
            {
                var log = new LogCore();
                log.Log(ex, EventTypes.Warning, (int)ServiceFault.NotInDigest);
            }

            return(default(T));
        }
    public void TryValidateTokenSet_ClaimUidMismatch()
    {
        // Arrange
        var httpContext = new DefaultHttpContext();
        var identity    = GetAuthenticatedIdentity("the-user");

        httpContext.User = new ClaimsPrincipal(identity);

        var cookieToken = new AntiforgeryToken()
        {
            IsCookieToken = true
        };
        var fieldtoken = new AntiforgeryToken()
        {
            SecurityToken = cookieToken.SecurityToken,
            IsCookieToken = false,
            ClaimUid      = new BinaryBlob(256)
        };

        var differentToken        = new BinaryBlob(256);
        var mockClaimUidExtractor = new Mock <IClaimUidExtractor>();

        mockClaimUidExtractor.Setup(o => o.ExtractClaimUid(It.Is <ClaimsPrincipal>(c => c.Identity == identity)))
        .Returns(Convert.ToBase64String(differentToken.GetData()));

        var tokenProvider = new DefaultAntiforgeryTokenGenerator(
            claimUidExtractor: mockClaimUidExtractor.Object,
            additionalDataProvider: null);

        string expectedMessage =
            "The provided antiforgery token was meant for a different " +
            "claims-based user than the current user.";

        // Act
        string message;
        var    result = tokenProvider.TryValidateTokenSet(httpContext, cookieToken, fieldtoken, out message);

        // Assert
        Assert.False(result);
        Assert.Equal(expectedMessage, message);
    }
Пример #29
0
        public void GenerateFormToken_ClaimsBasedIdentity()
        {
            // Arrange
            var cookieToken = new AntiForgeryToken()
            {
                IsSessionToken = true
            };
            var httpContext = new Mock <HttpContext>().Object;
            var identity    = GetAuthenticatedIdentity("some-identity");

            var config = new AntiForgeryOptions();

            byte[] data = new byte[256 / 8];
            using (var rng = RandomNumberGenerator.Create())
            {
                rng.GetBytes(data);
            }
            var base64ClaimUId   = Convert.ToBase64String(data);
            var expectedClaimUid = new BinaryBlob(256, data);

            var mockClaimUidExtractor = new Mock <IClaimUidExtractor>();

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

            var tokenProvider = new AntiForgeryTokenProvider(
                config: config,
                claimUidExtractor: mockClaimUidExtractor.Object,
                additionalDataProvider: null);

            // Act
            var fieldToken = tokenProvider.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 GenerateRequestToken_ClaimsBasedIdentity()
    {
        // Arrange
        var cookieToken = new AntiforgeryToken()
        {
            IsCookieToken = true
        };

        var identity    = GetAuthenticatedIdentity("some-identity");
        var httpContext = new DefaultHttpContext();

        httpContext.User = new ClaimsPrincipal(identity);

        byte[] data = new byte[256 / 8];
        RandomNumberGenerator.Fill(data);
        var base64ClaimUId   = Convert.ToBase64String(data);
        var expectedClaimUid = new BinaryBlob(256, data);

        var mockClaimUidExtractor = new Mock <IClaimUidExtractor>();

        mockClaimUidExtractor.Setup(o => o.ExtractClaimUid(It.Is <ClaimsPrincipal>(c => c.Identity == identity)))
        .Returns(base64ClaimUId);

        var tokenProvider = new DefaultAntiforgeryTokenGenerator(
            claimUidExtractor: mockClaimUidExtractor.Object,
            additionalDataProvider: null);

        // Act
        var fieldToken = tokenProvider.GenerateRequestToken(httpContext, cookieToken);

        // Assert
        Assert.NotNull(fieldToken);
        Assert.Equal(cookieToken.SecurityToken, fieldToken.SecurityToken);
        Assert.False(fieldToken.IsCookieToken);
        Assert.Equal("", fieldToken.Username);
        Assert.Equal(expectedClaimUid, fieldToken.ClaimUid);
        Assert.Equal("", fieldToken.AdditionalData);
    }
        public void SecurityTokenProperty()
        {
            // Arrange
            AntiForgeryToken token = new AntiForgeryToken();

            // Act & assert - 1
            BinaryBlob securityToken = token.SecurityToken;
            Assert.NotNull(securityToken);
            Assert.Equal(AntiForgeryToken.SecurityTokenBitLength, securityToken.BitLength);
            Assert.Equal(securityToken, token.SecurityToken); // check that we're not making a new one each property call

            // Act & assert - 2
            securityToken = new BinaryBlob(64);
            token.SecurityToken = securityToken;
            Assert.Equal(securityToken, token.SecurityToken);

            // Act & assert - 3
            token.SecurityToken = null;
            securityToken = token.SecurityToken;
            Assert.NotNull(securityToken);
            Assert.Equal(AntiForgeryToken.SecurityTokenBitLength, securityToken.BitLength);
            Assert.Equal(securityToken, token.SecurityToken); // check that we're not making a new one each property call
        }
        public void GetDigest()
        {
            var random = new Random();
            var digest = new LogHistory <MessageDisplay>()
            {
                Count       = random.Next(),
                GeneratedOn = DateTime.UtcNow,
                MaximumDate = DateTime.UtcNow.AddSeconds(random.Next()),
                MinimumDate = DateTime.UtcNow.AddMinutes(random.Next()),
            };
            var blob = new BinaryBlob <LogHistory <MessageDisplay> >(CloudStorageAccount.DevelopmentStorageAccount);

            var objectId = string.Format("happy{0}doodie", random.Next());

            blob.Save(objectId, digest);

            var item = blob.GetDigest <LogHistory <MessageDisplay> >(objectId);

            Assert.AreEqual <int>(digest.Count, item.Count);
            Assert.AreEqual <DateTime?>(digest.GeneratedOn, item.GeneratedOn);
            Assert.AreEqual <DateTime?>(digest.MaximumDate, item.MaximumDate);
            Assert.AreEqual <DateTime?>(digest.MinimumDate, item.MinimumDate);
        }
Пример #33
0
        public void ValidateTokens_ClaimUidMismatch()
        {
            // Arrange
            var            httpContext  = new Mock <HttpContext>().Object;
            ClaimsIdentity identity     = new GenericIdentity("the-user");
            var            sessionToken = new AntiForgeryToken()
            {
                IsSessionToken = true
            };
            var fieldtoken = new AntiForgeryToken()
            {
                SecurityToken  = sessionToken.SecurityToken,
                IsSessionToken = false,
                ClaimUid       = new BinaryBlob(256)
            };

            var differentToken        = new BinaryBlob(256);
            var mockClaimUidExtractor = new Mock <IClaimUidExtractor>();

            mockClaimUidExtractor.Setup(o => o.ExtractClaimUid(identity))
            .Returns(Convert.ToBase64String(differentToken.GetData()));

            var tokenProvider = new TokenProvider(
                config: null,
                claimUidExtractor: mockClaimUidExtractor.Object,
                additionalDataProvider: null);

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

            Assert.Equal(
                @"The provided anti-forgery token was meant for a different claims-based user than the current user.",
                ex.Message);
        }
Пример #34
0
        public TimingDataViewModel LoadTimingDataFromBinaryBlob(string BinaryBlobName)
        {
            if (!BinaryBlobLookupTable.ContainsKey(BinaryBlobName))
            {
                return(null);
            }

            BinaryBlob Blob = BinaryBlobLookupTable[BinaryBlobName];

            using (MemoryStream BlobStream = new MemoryStream(BinaryBlobBytes, Blob.Offset, Blob.CompressedSize))
                using (GZipStream DecompressionStream = new GZipStream(BlobStream, CompressionMode.Decompress))
                {
                    byte[] DecompressedBytes = new byte[Blob.DecompressedSize];
                    using (MemoryStream DecompressedStream = new MemoryStream(DecompressedBytes))
                    {
                        DecompressionStream.CopyTo(DecompressedStream);
                        DecompressedStream.Seek(0, SeekOrigin.Begin);
                        using (BinaryReader Reader = new BinaryReader(DecompressedStream))
                        {
                            return(FromBinaryReader(Reader));
                        }
                    }
                }
        }
Пример #35
0
        public void SecurityTokenProperty()
        {
            // Arrange
            AntiForgeryToken token = new AntiForgeryToken();

            // Act & assert - 1
            BinaryBlob securityToken = token.SecurityToken;

            Assert.NotNull(securityToken);
            Assert.Equal(AntiForgeryToken.SecurityTokenBitLength, securityToken.BitLength);
            Assert.Equal(securityToken, token.SecurityToken); // check that we're not making a new one each property call

            // Act & assert - 2
            securityToken       = new BinaryBlob(64);
            token.SecurityToken = securityToken;
            Assert.Equal(securityToken, token.SecurityToken);

            // Act & assert - 3
            token.SecurityToken = null;
            securityToken       = token.SecurityToken;
            Assert.NotNull(securityToken);
            Assert.Equal(AntiForgeryToken.SecurityTokenBitLength, securityToken.BitLength);
            Assert.Equal(securityToken, token.SecurityToken); // check that we're not making a new one each property call
        }
Пример #36
0
        public void SecurityTokenProperty_PropertySetter_DoesNotUseDefaults()
        {
            // Arrange
            var token = new AntiForgeryToken();

            // Act
            var securityToken = new BinaryBlob(64);
            token.SecurityToken = securityToken;

            // Assert
            Assert.Equal(securityToken, token.SecurityToken);
        }
Пример #37
0
        public void ValidateTokens_ClaimUidMismatch()
        {
            // Arrange
            var httpContext = new Mock<HttpContext>().Object;
            var identity = GetAuthenticatedIdentity("the-user");
            var sessionToken = new AntiForgeryToken() { IsSessionToken = true };
            var fieldtoken = new AntiForgeryToken()
            {
                SecurityToken = sessionToken.SecurityToken,
                IsSessionToken = false,
                ClaimUid = new BinaryBlob(256)
            };

            var differentToken = new BinaryBlob(256);
            var mockClaimUidExtractor = new Mock<IClaimUidExtractor>();
            mockClaimUidExtractor.Setup(o => o.ExtractClaimUid(identity))
                                 .Returns(Convert.ToBase64String(differentToken.GetData()));

            var tokenProvider = new AntiForgeryTokenProvider(
                config: null,
                claimUidExtractor: mockClaimUidExtractor.Object,
                additionalDataProvider: null);

            // Act & assert
            var ex =
                Assert.Throws<InvalidOperationException>(
                    () => tokenProvider.ValidateTokens(httpContext, identity, sessionToken, fieldtoken));
            Assert.Equal(
                @"The provided anti-forgery token was meant for a different claims-based user than the current user.",
                ex.Message);
        }
Пример #38
0
        public void GenerateFormToken_ClaimsBasedIdentity()
        {
            // Arrange
            var cookieToken = new AntiForgeryToken() { IsSessionToken = true };
            var httpContext = new Mock<HttpContext>().Object;
            var identity = GetAuthenticatedIdentity("some-identity");

            var config = new AntiForgeryOptions();

            byte[] data = new byte[256 / 8];
            using (var rng = RandomNumberGenerator.Create())
            {
                rng.GetBytes(data);
            }
            var base64ClaimUId = Convert.ToBase64String(data);
            var expectedClaimUid = new BinaryBlob(256, data);

            var mockClaimUidExtractor = new Mock<IClaimUidExtractor>();
            mockClaimUidExtractor.Setup(o => o.ExtractClaimUid(identity))
                                 .Returns(base64ClaimUId);

            var tokenProvider = new AntiForgeryTokenProvider(
                config: config,
                claimUidExtractor: mockClaimUidExtractor.Object,
                additionalDataProvider: null);

            // Act
            var fieldToken = tokenProvider.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(HttpContext httpContext, AntiforgeryToken sessionToken, AntiforgeryToken fieldToken)
        {
            if (httpContext == null)
            {
                throw new ArgumentNullException(nameof(httpContext));
            }

            if (sessionToken == null)
            {
                throw new ArgumentNullException(
                    nameof(sessionToken),
                    "Session token must be provided");
            }

            if (fieldToken == null)
            {
                throw new ArgumentNullException(
                    nameof(fieldToken),
                    "Field token must be provided");
            }

            // Do the tokens have the correct format?
            if (!sessionToken.IsSessionToken || fieldToken.IsSessionToken)
            {
                throw new InvalidOperationException("Security tokens swapped");
            }

            var bytes = Encoding.UTF8.GetBytes(CookieString);
            var cookieTokenValidation = new BinaryBlob(bytes.Length * 8, bytes);

            if (!cookieTokenValidation.Equals(sessionToken.SecurityToken))
            {
                throw new InvalidOperationException("Invalid cookie token");
            }

            bytes = Encoding.UTF8.GetBytes(FieldString);
            var headerTokenValidation = new BinaryBlob(bytes.Length * 8, bytes);

            if (!headerTokenValidation.Equals(fieldToken.SecurityToken))
            {
                throw new InvalidOperationException("Invalid field token");
            }
        }
        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 GetDigestObjectIdInvalid()
        {
            var blob = new BinaryBlob <LogHistory <MessageDisplay> >(CloudStorageAccount.DevelopmentStorageAccount);

            blob.GetDigest <LogHistory <MessageDisplay> >(StringHelper.NullEmptyWhiteSpace());
        }
        public void TryValidateTokenSet_ClaimUidMismatch()
        {
            // Arrange
            var httpContext = new DefaultHttpContext();
            var identity = GetAuthenticatedIdentity("the-user");
            httpContext.User = new ClaimsPrincipal(identity);

            var cookieToken = new AntiforgeryToken() { IsCookieToken = true };
            var fieldtoken = new AntiforgeryToken()
            {
                SecurityToken = cookieToken.SecurityToken,
                IsCookieToken = false,
                ClaimUid = new BinaryBlob(256)
            };

            var differentToken = new BinaryBlob(256);
            var mockClaimUidExtractor = new Mock<IClaimUidExtractor>();
            mockClaimUidExtractor.Setup(o => o.ExtractClaimUid(It.Is<ClaimsPrincipal>(c => c.Identity == identity)))
                                 .Returns(Convert.ToBase64String(differentToken.GetData()));

            var tokenProvider = new DefaultAntiforgeryTokenGenerator(
                claimUidExtractor: mockClaimUidExtractor.Object,
                additionalDataProvider: null);

            string expectedMessage =
                "The provided antiforgery token was meant for a different " +
                "claims-based user than the current user.";

            // Act
            string message;
            var result = tokenProvider.TryValidateTokenSet(httpContext, cookieToken, fieldtoken, out message);

            // Assert
            Assert.False(result);
            Assert.Equal(expectedMessage, message);
        }
Пример #43
0
        public void GetHashCodeTest()
        {
            // Arrange
            byte[] blobData = new byte[] { 0x01, 0x02, 0x03, 0x04 };
            int expectedHashCode = BitConverter.ToInt32(blobData, 0);

            BinaryBlob blob = new BinaryBlob(32, blobData);

            // Act
            int actualHashCode = blob.GetHashCode();

            // Assert
            Assert.Equal(expectedHashCode, actualHashCode);
        }
Пример #44
0
        public void Equals_Null_ReturnsFalse()
        {
            // Arrange
            object blobA = new BinaryBlob(32);
            object blobB = null;

            // Act & assert
            Assert.NotEqual(blobA, blobB);
        }
Пример #45
0
 public CaptchaToken(BinaryBlob value)
 {
     Value = value;
 }
Пример #46
0
        public void Equals_SameData_ReturnsTrue()
        {
            // Arrange
            object blobA = new BinaryBlob(32, new byte[] { 0x01, 0x02, 0x03, 0x04 });
            object blobB = new BinaryBlob(32, new byte[] { 0x01, 0x02, 0x03, 0x04 });

            // Act & assert
            Assert.Equal(blobA, blobB);
        }
        public void GenerateRequestToken_ClaimsBasedIdentity()
        {
            // Arrange
            var cookieToken = new AntiforgeryToken() { IsCookieToken = true };

            var identity = GetAuthenticatedIdentity("some-identity");
            var httpContext = new DefaultHttpContext();
            httpContext.User = new ClaimsPrincipal(identity);

            byte[] data = new byte[256 / 8];
            using (var rng = RandomNumberGenerator.Create())
            {
                rng.GetBytes(data);
            }
            var base64ClaimUId = Convert.ToBase64String(data);
            var expectedClaimUid = new BinaryBlob(256, data);

            var mockClaimUidExtractor = new Mock<IClaimUidExtractor>();
            mockClaimUidExtractor.Setup(o => o.ExtractClaimUid(It.Is<ClaimsPrincipal>(c => c.Identity == identity)))
                                 .Returns(base64ClaimUId);

            var tokenProvider = new DefaultAntiforgeryTokenGenerator(
                claimUidExtractor: mockClaimUidExtractor.Object,
                additionalDataProvider: null);

            // Act
            var fieldToken = tokenProvider.GenerateRequestToken(httpContext, cookieToken);

            // Assert
            Assert.NotNull(fieldToken);
            Assert.Equal(cookieToken.SecurityToken, fieldToken.SecurityToken);
            Assert.False(fieldToken.IsCookieToken);
            Assert.Equal("", fieldToken.Username);
            Assert.Equal(expectedClaimUid, fieldToken.ClaimUid);
            Assert.Equal("", fieldToken.AdditionalData);
        }