public void Serialize_FieldToken_WithClaimUid_TokenRoundTripSuccessful()
        {
            // Arrange
            var testSerializer = new AntiForgeryTokenSerializer(_dataProtector.Object);

            //"01" // Version
            //+ "705EEDCC7D42F1D6B3B98A593625BB4C" // SecurityToken
            //+ "00" // IsSessionToken
            //+ "01" // IsClaimsBased
            //+ "6F1648E97249AA58754036A67E248CF044F07ECFB0ED387556CE029A4F9A40E0" // ClaimUid
            //+ "05" // AdditionalData length header
            //+ "E282AC3437"; // AdditionalData ("€47") as UTF8
            var token = new AntiForgeryToken()
            {
                SecurityToken = _securityToken,
                IsSessionToken = false,
                ClaimUid = _claimUid,
                AdditionalData = "€47"
            };

            // Act
            var actualSerializedData = testSerializer.Serialize(token);
            var deserializedToken = testSerializer.Deserialize(actualSerializedData);

            // Assert
            AssertTokensEqual(token, deserializedToken);
            _dataProtector.Verify();
        }
Beispiel #2
0
		private static AntiForgeryWorker CreateSingletonAntiForgeryWorker()
		{
			IAntiForgeryConfig config = new AntiForgeryConfigWrapper();
			IAntiForgeryTokenSerializer serializer = new AntiForgeryTokenSerializer(MachineKey45CryptoSystem.Instance);
			ITokenStore tokenStore = new AntiForgeryTokenStore(config, serializer);
			IClaimUidExtractor claimUidExtractor = new ClaimUidExtractor(config, ClaimsIdentityConverter.Default);
			ITokenValidator validator = new TokenValidator(config, claimUidExtractor);
			return new AntiForgeryWorker(serializer, config, tokenStore, validator);
		}
        public void Deserialize_BadToken_Throws(string serializedToken)
        {
            // Arrange
            var testSerializer = new AntiForgeryTokenSerializer(_dataProtector.Object);

            // Act & assert
            var ex = Assert.Throws<InvalidOperationException>(() => testSerializer.Deserialize(serializedToken));
            Assert.Equal(@"The anti-forgery token could not be decrypted.", ex.Message);
        }
Beispiel #4
0
        private static AntiForgeryWorker CreateSingletonAntiForgeryWorker()
        {
            // initialize the dependency chain

            IAntiForgeryConfig          config     = new AntiForgeryConfigWrapper();
            IAntiForgeryTokenSerializer serializer = new AntiForgeryTokenSerializer(MachineKey45CryptoSystem.Instance);
            ITokenStore        tokenStore          = new AntiForgeryTokenStore(config, serializer);
            IClaimUidExtractor claimUidExtractor   = new ClaimUidExtractor(config, ClaimsIdentityConverter.Default);
            ITokenValidator    tokenValidator      = new TokenValidator(config, claimUidExtractor);

            return(new AntiForgeryWorker(serializer, config, tokenStore, tokenValidator));
        }
        public ActionResult Index3(int?id)
        {
            AntiForgeryTokenSerializer serializer = new AntiForgeryTokenSerializer(new MachineKey45CryptoSystem());
            string cookieValue = "k5v9fu6On-EhZ_YOzY1voQROMQFuwZgb77zr00OB3Z20or_AD1ZP6mB17oVQ4xV7ld2U_pvPDHoc8zOimJG4t7XVQQA1";
            var    cookieToken = serializer.Deserialize(cookieValue);
            var    formToken2  = serializer.Deserialize("ZgFqPlKwjNHB1imWLFWOhfxo-MXpLk4hr2J1yhmPt12dPsEgyREn3VO1IMjqUcZ4gkHV6dORMDMkORxsGhaB_yGU_iJ8-ozRyGnNHtwRHLYEtpTi0");
            var    formToken   = serializer.Deserialize("ykbb3V33vI9ogyiq6UOo9a2g6iJGt8jz3Y5b5B-1qlTA1rBsV1N7mVpa6Uk2jPtHsWVG3R0rQgxfMr756HcjnTXg2dXY3-fCZmjdI51YK3gyTZWA0");

            //Console.WriteLine(formToken.SecurityToken);
            //Console.WriteLine(formToken2.SecurityToken);
            //Console.WriteLine(cookieToken.SecurityToken);
            ViewBag.form1  = formToken.SecurityToken;
            ViewBag.form2  = formToken2.SecurityToken;
            ViewBag.cookie = cookieToken.SecurityToken;
            return(View());
        }
        private static AntiForgeryWorker CreateSingletonAntiForgeryWorker()
        {
            // initialize the dependency chain

            // The 'Instance' property can return null, in which case we should fall back to using
            // the 4.0 crypto code paths. We need to use an 'if' block rather than the null coalescing
            // operator due to a CLR bug (DevDiv #424203).
            ICryptoSystem cryptoSystem = MachineKey45CryptoSystem.Instance;
            if (cryptoSystem == null)
            {
                cryptoSystem = new MachineKey40CryptoSystem();
            }

            IAntiForgeryConfig config = new AntiForgeryConfigWrapper();
            IAntiForgeryTokenSerializer serializer = new AntiForgeryTokenSerializer(cryptoSystem);
            ITokenStore tokenStore = new AntiForgeryTokenStore(config, serializer);
            IClaimUidExtractor claimUidExtractor = new ClaimUidExtractor(config, ClaimsIdentityConverter.Default);
            ITokenValidator tokenValidator = new TokenValidator(config, claimUidExtractor);

            return new AntiForgeryWorker(serializer, config, tokenStore, tokenValidator);
        }
Beispiel #7
0
        public void Serialize_SessionToken_TokenRoundTripSuccessful()
        {
            // Arrange
            var testSerializer = new AntiForgeryTokenSerializer(_dataProtector.Object);

            //"01" // Version
            //+ "705EEDCC7D42F1D6B3B98A593625BB4C" // SecurityToken
            //+ "01"; // IsSessionToken
            var token = new AntiForgeryToken()
            {
                SecurityToken  = _securityToken,
                IsSessionToken = true
            };

            // Act
            string actualSerializedData = testSerializer.Serialize(token);
            var    deserializedToken    = testSerializer.Deserialize(actualSerializedData);

            // Assert
            AssertTokensEqual(token, deserializedToken);
            _dataProtector.Verify();
        }
Beispiel #8
0
        private static AntiForgeryWorker CreateSingletonAntiForgeryWorker()
        {
            // initialize the dependency chain

            // The 'Instance' property can return null, in which case we should fall back to using
            // the 4.0 crypto code paths. We need to use an 'if' block rather than the null coalescing
            // operator due to a CLR bug (DevDiv #424203).
            ICryptoSystem cryptoSystem = MachineKey45CryptoSystem.Instance;

            if (cryptoSystem == null)
            {
                cryptoSystem = new MachineKey40CryptoSystem();
            }

            IAntiForgeryConfig          config     = new AntiForgeryConfigWrapper();
            IAntiForgeryTokenSerializer serializer = new AntiForgeryTokenSerializer(cryptoSystem);
            ITokenStore        tokenStore          = new AntiForgeryTokenStore(config, serializer);
            IClaimUidExtractor claimUidExtractor   = new ClaimUidExtractor(config, ClaimsIdentityConverter.Default);
            ITokenValidator    tokenValidator      = new TokenValidator(config, claimUidExtractor);

            return(new AntiForgeryWorker(serializer, config, tokenStore, tokenValidator));
        }
        public void Serialize_FieldToken_WithUsername_TokenRoundTripSuccessful()
        {
            // Arrange
            var testSerializer = new AntiForgeryTokenSerializer(_dataProtector.Object);

            //"01" // Version
            //+ "705EEDCC7D42F1D6B3B98A593625BB4C" // SecurityToken
            //+ "00" // IsSessionToken
            //+ "00" // IsClaimsBased
            //+ "08" // Username length header
            //+ "4AC3A972C3B46D65" // Username ("Jérôme") as UTF8
            //+ "05" // AdditionalData length header
            //+ "E282AC3437"; // AdditionalData ("€47") as UTF8
            var token = new AntiForgeryToken()
            {
                SecurityToken = _securityToken,
                IsSessionToken = false,
                Username = "******",
                AdditionalData = "€47"
            };

            // Act
            var actualSerializedData = testSerializer.Serialize(token);
            var deserializedToken = testSerializer.Deserialize(actualSerializedData);

            // Assert
            AssertTokensEqual(token, deserializedToken);
            _dataProtector.Verify();
        }
        public void Serialize_SessionToken_TokenRoundTripSuccessful()
        {
            // Arrange
            var testSerializer = new AntiForgeryTokenSerializer(_dataProtector.Object);

            //"01" // Version
            //+ "705EEDCC7D42F1D6B3B98A593625BB4C" // SecurityToken
            //+ "01"; // IsSessionToken
            var token = new AntiForgeryToken()
            {
                SecurityToken = _securityToken,
                IsSessionToken = true
            };

            // Act
            string actualSerializedData = testSerializer.Serialize(token);
            var deserializedToken = testSerializer.Deserialize(actualSerializedData);

            // Assert
            AssertTokensEqual(token, deserializedToken);
            _dataProtector.Verify();
        }
Beispiel #11
0
        static void Main()
        {
            var cookieToken = new AntiForgeryToken()
            {
                // SecurityToken will be populated automatically.
                IsSessionToken = true
            };

            // Console.WriteLine(cookieToken.SecurityToken);

            byte[] newByte = new byte[]
            {
                1,
                36,
                255,
                6,
                166,
                145,
                62,
                221,
                232,
                38,
                102,
                166,
                8,
                143,
                125,
                165,
                243,
                0,
                0,
                0,
                0,
            };

            string[] _purposes = new string[] { "System.Web.Helpers.AntiXsrf.AntiForgeryToken.v1" };

            var test1 = MachineKey.Protect(newByte, _purposes);
            var test2 = MachineKey.Protect(newByte, _purposes);


            Console.WriteLine(AreByteArraysEqual(test1, test2));;

            var x1 = HttpServerUtility.UrlTokenEncode(MachineKey.Protect(newByte, _purposes));
            var x2 = HttpServerUtility.UrlTokenEncode(MachineKey.Protect(newByte, _purposes));

            Console.WriteLine(x1);
            Console.WriteLine(x2);
            var x3 = MachineKey.Unprotect(HttpServerUtility.UrlTokenDecode(x1), _purposes);
            var x4 = MachineKey.Unprotect(HttpServerUtility.UrlTokenDecode(x2), _purposes);

            Console.WriteLine(x3);
            Console.WriteLine(x4);

            Console.WriteLine(AreByteArraysEqual(x3, x4));;


            return;

            AntiForgeryToken formToken = new AntiForgeryToken()
            {
                SecurityToken  = cookieToken.SecurityToken,
                IsSessionToken = false
            };
            AntiForgeryTokenSerializer serializer = new AntiForgeryTokenSerializer(new MachineKey45CryptoSystem());
            var formVal1 = serializer.Serialize(formToken);

            Console.WriteLine(formVal1);
            //Console.WriteLine(formToken.ClaimUid);
            serializer.Deserialize(formVal1).SecurityToken.GetData().OutputByteArray();
            Console.WriteLine();
            Console.WriteLine();
            var formVal2 = serializer.Serialize(formToken);

            Console.WriteLine(formVal2);
            // Console.WriteLine(formToken.ClaimUid);
            serializer.Deserialize(formVal2).SecurityToken.GetData().OutputByteArray();
            Console.WriteLine();
            Console.WriteLine();
            var cookieVal = serializer.Serialize(cookieToken);

            Console.WriteLine(cookieVal);
            serializer.Deserialize(cookieVal).SecurityToken.GetData().OutputByteArray();

            var cookieVal2 = serializer.Serialize(cookieToken);

            Console.WriteLine(cookieVal2);
            serializer.Deserialize(cookieVal2).SecurityToken.GetData().OutputByteArray();


            return;

            //string cookieValue = "emTIesw2uxjqSIp8y67CHsMc_cxMxEJMO-CVy3tQLnJQPD2Fjywsi8k1hppsm8XkM5T0ZU8q0WUP4dgk7IngZl3jzDZuBt97n0a5-PUENqk1";
            //string fromValue1 = "";
            //string fromValue2 = "";
            ////var cookieToken = serializer.Deserialize(cookieValue);
            ////var formToken2 = serializer.Deserialize("ZgFqPlKwjNHB1imWLFWOhfxo-MXpLk4hr2J1yhmPt12dPsEgyREn3VO1IMjqUcZ4gkHV6dORMDMkORxsGhaB_yGU_iJ8-ozRyGnNHtwRHLYEtpTi0");
            //var formToken = serializer.Deserialize("UMTdP94vuMVKtLnzzxrGVLt7lVM_51-psWSI79cGa6gGn1KDRwCDJ8j9Z-O4am9i6pD06jQX5fALSxxqsQB-3L4DHwYudWoQoOApexREUz6P_nOECzbdgQlK5-kX9Xkd0");
            //Console.WriteLine(formToken.SecurityToken);
            ////Console.WriteLine(formToken2.SecurityToken);
            ////Console.WriteLine(cookieToken.SecurityToken);
            //return;

            var builderx = new ContainerBuilder();

            builderx.RegisterType <ConsoleOutput> ().As <IOutput> ().InstancePerLifetimeScope();
            var containerx = builderx.Build();

            using (var scope1 = containerx.BeginLifetimeScope(MatchingScopeLifetimeTags.RequestLifetimeScopeTag))
            {
                var outputer = scope1.Resolve <IOutput>();
                outputer.Write("hello");
            }

            return;

            var str = "[quote=(yuan)]123123";

            str = Regex.Replace(str, @"\[quote=(.+?)\]", String.Empty, RegexOptions.Compiled | RegexOptions.IgnoreCase);
            Console.WriteLine(str);
            str = "[quote=(yuan)]123123";
            Console.WriteLine(Regex.Matches(str, @"\[quote=(.+?)\]").Count);
            foreach (Match item in Regex.Matches(str, @"\[quote=(.+?)\]"))
            {
                Console.WriteLine(item.Groups.Count);
            }
            return;

            string sentence = "the quick brown fox jumps over the lazy dog";

            // Split the string into individual words.
            string[] words = sentence.Split(' ');

            // Prepend each word to the beginning of the
            // new sentence to reverse the word order.
            string reversed = words.Aggregate((workingSentence, next) =>
            {
                Console.WriteLine("current: " + workingSentence + "\t" + next);
                return(next + " " + workingSentence);
            });

            Console.WriteLine(reversed);

            //Mapper.Configuration.AssertConfigurationIsValid();

            return;

            // Lambda expression as executable code.
            Func <int, bool> deleg = i => i < 5;

            // Invoke the delegate and display the output.
            Console.WriteLine("deleg(4) = {0}", deleg(4));

            // Lambda expression as data in the form of an expression tree.
            System.Linq.Expressions.Expression <Func <int, bool> > expr = i => i < 5;
            // Compile the expression tree into executable code.
            Func <int, bool> deleg2 = expr.Compile();

            // Invoke the method and print the output.
            Console.WriteLine("deleg2(4) = {0}", deleg2(4));
            return;

            var routeValues = new RouteValueDictionary
            {
                { "Namespaces", "Nop.Plugin.Widgets.NivoSlider.Controllers" },
                { "area", null },
                { "widgetZone", "home_top" }
            };

            var props = TypeDescriptor.GetProperties(routeValues);

            foreach (PropertyDescriptor item in props)
            {
                Console.WriteLine(item.Name + " " + item.GetValue(routeValues).ToString());
            }
            Console.WriteLine();
            Console.WriteLine();
            var props2 = routeValues.GetType().GetProperties();

            foreach (var item in props2)
            {
                Console.WriteLine(item.Name + " " + item.GetValue(routeValues).ToString());
            }
            return;

            var builder = new ContainerBuilder();

            builder.RegisterType <ConsoleOutput>().AsSelf().As <IOutput>().InstancePerRequest();
            builder.RegisterType <TodayWriter>().As <IDateWriter>().InstancePerMatchingLifetimeScope(MatchingScopeLifetimeTags.RequestLifetimeScopeTag);;

            builder.Register(c => new FakeHttpContext("~")).As <HttpContextBase>().InstancePerLifetimeScope();

            //builder.RegisterSource(new AutofacDemo.Features.AnyConcreteTypeNotAlreadyRegisteredSource());
            builder.RegisterType <PerRequestCacheManager>().As <ICacheManager>().Named <ICacheManager>("nop_cache_per_request").InstancePerLifetimeScope();

            builder.RegisterType <MemoryCacheManager>().As <ICacheManager>().Named <ICacheManager>("nop_cache_static").SingleInstance();

            var container = builder.Build();

            using (var scopeContainer = container.BeginLifetimeScope(MatchingScopeLifetimeTags.RequestLifetimeScopeTag))
            {
                //var myComponent = scopeContainer.Resolve<MyComponent>();
                var myComponent = scopeContainer.Resolve <ConsoleOutput>();
                var pets        = scopeContainer.Resolve <Pet>();
                pets.Output();


                // test for cache
                var iCache = scopeContainer.Resolve <ICacheManager>();
                Console.WriteLine(iCache.GetType());

                iCache = scopeContainer.ResolveNamed <ICacheManager>("nop_cache_static");
                Console.WriteLine(iCache.GetType());

                try
                {
                    iCache = scopeContainer.ResolveNamed <ICacheManager>("nop_cache_static11");
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
            }

            return;

            HandlerFactory hf     = new HandlerFactory();
            var            method = typeof(HandlerFactory).GetMethod("GetHandler");

            Console.WriteLine(method);
            method = method.MakeGenericMethod(typeof(int));
            Console.WriteLine(method.ToString());
            Console.WriteLine(method);
            int x      = 3;
            var result = method.Invoke(hf, null);

            Console.WriteLine(method.IsGenericMethod);
            return;
        }