Default JSON serializer for request bodies Doesn't currently use the SerializeAs attribute, defers to Newtonsoft's attributes
Inheritance: ISerializer
Ejemplo n.º 1
0
        public void SendingCommandObjectSetsCommandOnBus()
        {
            var messageBus = new Mock<INewMessageBus>();
            Message message = null;
            messageBus.Setup(m => m.Publish(It.IsAny<Message>())).Callback<Message>(m => message = m);
            var serializer = new JsonNetSerializer();
            var traceManager = new Mock<ITraceManager>();
            var connection = new Connection(messageBus.Object,
                                            serializer,
                                            "signal",
                                            "connectonid",
                                            new[] { "a", "signal", "connectionid" },
                                            new string[] { },
                                            traceManager.Object);

            connection.Send("a", new Command
            {
                Type = CommandType.AddToGroup,
                Value = "foo"
            });

            Assert.NotNull(message);
            Assert.True(message.IsCommand);
            var command = serializer.Parse<Command>(message.Value);
            Assert.Equal(CommandType.AddToGroup, command.Type);
            Assert.Equal(@"{""Name"":""foo"",""Cursor"":null}", command.Value);
        }
Ejemplo n.º 2
0
        public void SendUrlTriggersReceivedEvent()
        {
            var tcs = new TaskCompletionSource<string>();
            var request = new Mock<IRequest>();
            var form = new NameValueCollection();
            form["data"] = "This is my data";
            var qs = new NameValueCollection();
            qs["connectionId"] = "1";
            request.Setup(m => m.QueryString).Returns(qs);
            request.Setup(m => m.Form).Returns(form);
            request.Setup(m => m.Url).Returns(new Uri("http://test/echo/send"));
            var counters = new Mock<IPerformanceCounterManager>();
            var heartBeat = new Mock<ITransportHeartbeat>();
            var json = new JsonNetSerializer();
            var hostContext = new HostContext(request.Object, null);
            var transportConnection = new Mock<ITransportConnection>();
            var traceManager = new Mock<ITraceManager>();
            traceManager.Setup(m => m[It.IsAny<string>()]).Returns(new System.Diagnostics.TraceSource("foo"));
            var transport = new Mock<ForeverTransport>(hostContext, json, heartBeat.Object, counters.Object, traceManager.Object)
            {
                CallBase = true
            };

            transport.Object.Received = data =>
            {
                tcs.TrySetResult(data);
                return TaskAsyncHelper.Empty;
            };

            transport.Object.ProcessRequest(transportConnection.Object).Wait();

            Assert.Equal("This is my data", tcs.Task.Result);
        }
Ejemplo n.º 3
0
		public static IElasticClient GetFixedReturnClient(
			object response,
			int statusCode = 200,
			Func<ConnectionSettings, ConnectionSettings> modifySettings = null,
			string contentType = "application/json",
			Exception exception = null)
		{
			var serializer = new JsonNetSerializer(new ConnectionSettings());
			byte[] fixedResult;

			if (contentType == "application/json")
			{
				using (var ms = new MemoryStream())
				{
					serializer.Serialize(response, ms);
					fixedResult = ms.ToArray();
				}
			}
			else
			{
				fixedResult = Encoding.UTF8.GetBytes(response.ToString());
			}

			var connection = new InMemoryConnection(fixedResult, statusCode, exception);
			var connectionPool = new SingleNodeConnectionPool(new Uri("http://localhost:9200"));
			var defaultSettings = new ConnectionSettings(connectionPool, connection)
				.DefaultIndex("default-index");
			var settings = (modifySettings != null) ? modifySettings(defaultSettings) : defaultSettings;
			return new ElasticClient(settings);
		}
Ejemplo n.º 4
0
        public void Should_serialize_to_json()
        {
            var o = new JsonTester { Foo = "bar", Bar = new JsonTester { Baz = 2 }, Baz = 1 };
            var serialized = new JsonNetSerializer().Serialize(o);

            Assert.That(serialized, Is.EqualTo("{\"Foo\":\"bar\",\"Bar\":{\"Foo\":null,\"Bar\":null,\"Baz\":2},\"Baz\":1}"));
        }
Ejemplo n.º 5
0
        protected override void ApplicationStartup(Nancy.TinyIoc.TinyIoCContainer container, Nancy.Bootstrapper.IPipelines pipelines)
        {
            base.ApplicationStartup(container, pipelines);

            //Enable CSRF protection
            Nancy.Security.Csrf.Enable(pipelines);

            // Enabled cookie sessions
            Nancy.Session.CookieBasedSessions.Enable(pipelines);

            //Setup frame and origin options ( https://www.owasp.org/index.php/List_of_useful_HTTP_headers )
            //may be overwritten by server (apache,ngix,iis,..) for config see https://developer.mozilla.org/en-US/docs/Web/HTTP/X-Frame-Options
            pipelines.AfterRequest.AddItemToEndOfPipeline((ctx) =>
            {
                if (ctx.Response.StatusCode == HttpStatusCode.InternalServerError) return;

                ctx.Response.Headers.Add("X-Frame-Options", "SAMEORIGIN");
                ctx.Response.Headers.Add("X-Download-Options", "noopen"); // IE extension
                ctx.Response.Headers.Add("X-Content-Type-Options", "nosniff");
                ctx.Response.Headers.Add("X-XSS-Protection", "1; mode=block");
            });

            // Retain the casing in serialization of nancy json
            Nancy.Json.JsonSettings.RetainCasing = true;

            StaticConfiguration.CaseSensitive = false;

            // Enable debugging of nancy
            StaticConfiguration.EnableRequestTracing = false;

            // Dummy call to force the include of the Nancy.Serialization.JsonNet dll
            JsonNetSerializer a = new JsonNetSerializer();
            a.CanSerialize("{}");
        }
Ejemplo n.º 6
0
        public void SendingCommandObjectSetsCommandOnBus()
        {
            var messageBus = new Mock<IMessageBus>();
            var counters = new Mock<IPerformanceCounterWriter>();
            Message message = null;
            messageBus.Setup(m => m.Publish(It.IsAny<Message>())).Returns<Message>(m =>
            {
                message = m;
                return TaskAsyncHelper.Empty;
            });

            var serializer = new JsonNetSerializer();
            var traceManager = new Mock<ITraceManager>();
            var connection = new Connection(messageBus.Object,
                                            serializer,
                                            "signal",
                                            "connectonid",
                                            new[] { "a", "signal", "connectionid" },
                                            new string[] { },
                                            traceManager.Object,
                                            counters.Object);

            connection.Send("a", new Command
            {
                Type = CommandType.AddToGroup,
                Value = "foo"
            });

            Assert.NotNull(message);
            Assert.True(message.IsCommand);
            var command = serializer.Parse<Command>(message.Value);
            Assert.Equal(CommandType.AddToGroup, command.Type);
            Assert.Equal("foo", command.Value);
        }
Ejemplo n.º 7
0
 public ContentSerializerFactory()
 {
     Serializers = new Dictionary<string, IContentSerializer>();
     DefaultSerializer = new JsonNetSerializer();
     RegisterContentSerializer(DefaultSerializer);
     RegisterContentSerializer(new JavaBinSerializer());
 }
Ejemplo n.º 8
0
        public void Can_Compression() {
            var serialize = new JsonNetSerializer();

            var foo = TestHelper.GetFoo();

            var output1 = new MemoryStream();
            var output2 = new MemoryStream();

            serialize.Serialize(foo, output1);

            var rtl1 = output1.ToArray();

            //compress
            var gzip = new GZipStream(output2, CompressionLevel.Fastest);
            StreamWriter sw2 = new StreamWriter(gzip);
            serialize.Serialize(foo, sw2);

            sw2.Dispose();
            var rtl2 = output2.ToArray();

            //comparing the size
            Assert.True(rtl2.Length < rtl1.Length);

            //decompress
            var gzip2 = new GZipStream(new MemoryStream(rtl2), CompressionMode.Decompress);
            StreamReader sr = new StreamReader(gzip2);
            var foo2 = serialize.Deserialize<Foo>(sr);

            Assert.Equal(foo.ToString(), foo2.ToString());
        }
Ejemplo n.º 9
0
        public void AbortUrlTriggersConnectionAbort()
        {
            var request = new Mock<IRequest>();
            var qs = new NameValueCollection();
            qs["connectionId"] = "1";
            request.Setup(m => m.QueryString).Returns(qs);
            request.Setup(m => m.Url).Returns(new Uri("http://test/echo/abort"));
            string abortedConnectionId = null;
            var counters = new Mock<IPerformanceCounterManager>();
            var heartBeat = new Mock<ITransportHeartbeat>();
            var json = new JsonNetSerializer();
            var hostContext = new HostContext(request.Object, null);
            var transportConnection = new Mock<ITransportConnection>();
            var traceManager = new Mock<ITraceManager>();
            traceManager.Setup(m => m[It.IsAny<string>()]).Returns(new System.Diagnostics.TraceSource("foo"));
            transportConnection.Setup(m => m.Send(It.IsAny<ConnectionMessage>()))
                               .Callback<ConnectionMessage>(m =>
                               {
                                   abortedConnectionId = m.Signal;
                                   var command = m.Value as Command;
                                   Assert.NotNull(command);
                                   Assert.Equal(CommandType.Abort, command.CommandType);
                               })
                               .Returns(TaskAsyncHelper.Empty);

            var transport = new Mock<ForeverTransport>(hostContext, json, heartBeat.Object, counters.Object, traceManager.Object)
            {
                CallBase = true
            };

            transport.Object.ProcessRequest(transportConnection.Object).Wait();

            Assert.Equal("1", abortedConnectionId);
        }
Ejemplo n.º 10
0
        protected FeatureTestBase()
        {
            Bundler.Enable(false);
            BundleTable.Bundles.Clear();

            _configuration = new Dictionary<string, object>();
            Configure(_configuration);

            Config.GetValueFunc = key =>
            {
                object value = null;
                if (!_configuration.TryGetValue(key, out value))
                {
                    throw new InvalidOperationException(
                        string.Format("Test is missing configuration value for key {0}", key));
                }

                return value;
            };

            FormsConfig = new FormsAuthenticationConfiguration
            {
                RedirectUrl = "~/admin/login",
                UserMapper = new FormsAuthenticationUserMapper(Store.OpenSession)
            };

            Serializer = new JsonNetSerializer();
            Deserializer = new JsonNetBodyDeserializer();

            _browser = CreateBrowser();
            Admin = Install("admin");
        }
        public void the_selected_fields()
        {
            var serializer = new JsonNetSerializer();

            var selector = new DeserializeSelector<Target>(serializer);

            selector.SelectFields().ShouldHaveTheSameElementsAs("data");
        }
Ejemplo n.º 12
0
        public void JsonNetCharacterTest1(string str)
        {
            var jsonNetSerializer = new JsonNetSerializer();
            var sut = new TestClass1 {Name = str};
            var result = jsonNetSerializer.ToJson(sut);

            Assert.That(str, Is.EqualTo(sut.Name));
            Assert.That(result.Contains(str));
        }
Ejemplo n.º 13
0
        public void Init()
        {
            var serializer = new JsonNetSerializer(new JsonSerializerSettings
            {
                ContractResolver = new CustomSignalRContractResolverBecauseOfIssue500InSignalR(),
                Formatting = Formatting.None,
                NullValueHandling = NullValueHandling.Ignore,
                Converters = { new IsoDateTimeConverter { DateTimeStyles = DateTimeStyles.RoundtripKind }, { new StringEnumConverter { CamelCaseText = true } } }
            });

            GlobalHost.DependencyResolver.Register(typeof(IJsonSerializer), () => serializer); 
        }
        public void resolve_deserializes_the_first_field()
        {
            var reader = Substitute.For<DbDataReader>();
            var target = Target.Random();
            var serializer = new JsonNetSerializer();
            var json = serializer.ToJson(target);

            var selector = new DeserializeSelector<Target>(serializer);
            reader.GetString(0).Returns(json);

            selector.Resolve(reader, null).ShouldNotBeNull();
        }
Ejemplo n.º 15
0
        public void Should_deserialize_to_specific_type_from_json()
        {
            const string json = "{\"Foo\":\"bar\",\"Bar\":{\"Foo\":null,\"Bar\":null,\"Baz\":2},\"Baz\":1}";
            var deserialized = new JsonNetSerializer().Deserialize<JsonTester>(json);

            Assert.That(deserialized, Is.Not.Null);
            Assert.That(deserialized, Has.Property("Foo").EqualTo("bar"));
            Assert.That(deserialized, Has.Property("Baz").EqualTo(1));
            Assert.That(deserialized, Has.Property("Bar").Not.Null);
            Assert.That(deserialized, Has.Property("Bar").Property("Foo").Null);
            Assert.That(deserialized, Has.Property("Bar").Property("Bar").Null);
            Assert.That(deserialized, Has.Property("Bar").Property("Baz").EqualTo(2));
        }
Ejemplo n.º 16
0
		public static IElasticClient GetFixedReturnClient(object responseJson)
		{
			var serializer = new JsonNetSerializer(new ConnectionSettings());
			byte[] fixedResult;
			using (var ms = new MemoryStream())
			{
				serializer.Serialize(responseJson, ms);
				fixedResult = ms.ToArray();
			}
			var connection = new InMemoryConnection(fixedResult);
			var connectionPool = new SingleNodeConnectionPool(new Uri("http://localhost:9200"));
			var settings = new ConnectionSettings(connectionPool, connection);
			return new ElasticClient(settings);
		}
Ejemplo n.º 17
0
 void Application_Start(object sender, EventArgs e)
 {
     XmlConfigurator.Configure();
     RouteTable.Routes.MapHubs();
     var serializerSettings = new JsonSerializerSettings
     {
         ContractResolver = new FilteredCamelCasePropertyNamesContractResolver
                 {
                     AssembliesToInclude = { typeof(Review).Assembly }
                 }
     };
     var jsonNetSerializer = new JsonNetSerializer(serializerSettings);
     GlobalHost.DependencyResolver.Register(typeof(IJsonSerializer), () => jsonNetSerializer);
 }
Ejemplo n.º 18
0
        public void AvoidDeadlockIfCancellationTokenTriggeredBeforeSubscribing()
        {
            var request = new Mock<IRequest>();
            var qs = new NameValueCollection();
            qs["connectionId"] = "1";
            request.Setup(m => m.QueryString).Returns(qs);
            request.Setup(m => m.Url).Returns(new Uri("http://test/echo/connect"));
            var counters = new Mock<IPerformanceCounterManager>();
            var heartBeat = new Mock<ITransportHeartbeat>();
            var json = new JsonNetSerializer();
            var hostContext = new HostContext(request.Object, null);
            var transportConnection = new Mock<ITransportConnection>();
            var traceManager = new Mock<ITraceManager>();
            traceManager.Setup(m => m[It.IsAny<string>()]).Returns(new System.Diagnostics.TraceSource("foo"));

            Func<PersistentResponse, Task<bool>> callback = null;

            transportConnection.Setup(m => m.Receive(It.IsAny<string>(),
                                                     It.IsAny<Func<PersistentResponse, Task<bool>>>(),
                                                     It.IsAny<int>())).Callback<string, Func<PersistentResponse, Task<bool>>, int>((id, cb, max) =>
                                                     {
                                                         callback = cb;
                                                     })
                                                     .Returns(new DisposableAction(() =>
                                                     {
                                                         callback(new PersistentResponse());
                                                     }));

            var transport = new Mock<ForeverTransport>(hostContext, json, heartBeat.Object, counters.Object, traceManager.Object)
            {
                CallBase = true
            };

            var wh = new ManualResetEventSlim();

            transport.Object.BeforeCancellationTokenCallbackRegistered = () =>
            {
                // Trip the cancellation token
                transport.Object.End();
            };

            // Act
            Task.Factory.StartNew(() =>
            {
                transport.Object.ProcessRequest(transportConnection.Object);
                wh.Set();
            });

            Assert.True(wh.Wait(TimeSpan.FromSeconds(2)), "Dead lock!");
        }
		/// <inheritdoc />
		public Task<IMultiSearchResponse> MultiSearchAsync(IMultiSearchRequest request)
		{
			return this.Dispatcher.DispatchAsync<IMultiSearchRequest, MultiSearchRequestParameters, MultiSearchResponse, IMultiSearchResponse>(
				request,
				(p, d) =>
				{
					var converter = CreateMultiSearchDeserializer(p);
					var serializer = new JsonNetSerializer(this.ConnectionSettings, converter);
					var json = serializer.SerializeToBytes(p).Utf8String();
					var creator = new MultiSearchCreator((r, s) => serializer.Deserialize<MultiSearchResponse>(s));
					request.RequestParameters.DeserializationOverride(creator);
					return this.LowLevelDispatch.MsearchDispatchAsync<MultiSearchResponse>(p, json);
				}
			);
		}
Ejemplo n.º 20
0
        public void get_with_concrete_type()
        {
            var serializer = new JsonNetSerializer();
            var camaro = new NulloIdentityMapTests.Camaro();

            var json = serializer.ToJson(camaro);

            var map = new DirtyTrackingIdentityMap(serializer, null);

            map.Get<NulloIdentityMapTests.Car>(camaro.Id, typeof(NulloIdentityMapTests.Camaro), json)
                .ShouldBeOfType<NulloIdentityMapTests.Camaro>()
                .Id.ShouldBe(camaro.Id);


        }
Ejemplo n.º 21
0
        public static IConfigure UsingSignalR(this IConfigure configure)
        {
            GlobalHost.DependencyResolver = new BifrostDependencyResolver(Configure.Instance.Container);
            RouteTable.Routes.MapHubs();

            var serializerSettings = new JsonSerializerSettings
            {
                ContractResolver = new FilteredCamelCasePropertyNamesContractResolver(),
                Converters = { new ConceptConverter(), new ConceptDictionaryConverter() }
            };
            var jsonNetSerializer = new JsonNetSerializer(serializerSettings);
            GlobalHost.DependencyResolver.Register(typeof(IJsonSerializer), () => jsonNetSerializer); 

            return Configure.Instance;
        }
Ejemplo n.º 22
0
        public void get_with_concrete_type()
        {
            var serializer = new JsonNetSerializer();
            var camaro = new Camaro();

            var json = serializer.ToJson(camaro);

            var map = new NulloIdentityMap(serializer);

            map.Get<Car>(camaro.Id, typeof (Camaro), json, null)
                .ShouldBeOfType<Camaro>()
                .Id.ShouldBe(camaro.Id);

            
        }
Ejemplo n.º 23
0
        public void JsonNetPerformanceTests(int docCount, bool warmup)
        {
            Trace.WriteLine($"JsonNetPerformanceTests: warmup={docCount}, count={docCount}");
            var docs = new Fixture().CreateMany<TestDocument>(docCount).ToList();
            MiniProfiler.Start();
            var mp = MiniProfiler.Current;
            Trace.WriteLine("performance test on: " + docs.Count() + " docs");

            var jilSserializer = new JilSerializer();
            Trace.WriteLine("start JIL");
            if (warmup) jilSserializer.ToJson(new Fixture().Create<TestDocument>()); // warmup
            using (mp.Step("JIL serialization"))
            {
                1.Times(i =>
                {
                    foreach (var doc in docs)
                        jilSserializer.ToJson(doc);
                });
            }

            var jsonNetSerializer = new JsonNetSerializer();
            Trace.WriteLine("start JSONNET");
            if (warmup) jsonNetSerializer.ToJson(new Fixture().Create<TestDocument>()); // warmup
            using (mp.Step("JSONNET serialization"))
            {
                1.Times(i =>
                {
                    foreach (var doc in docs)
                        jsonNetSerializer.ToJson(doc);
                });
            }

            var textSerializer = new ServiceStackTextSerializer();
            Trace.WriteLine("start JSONNET");
            if (warmup) textSerializer.ToJson(new Fixture().Create<TestDocument>()); // warmup
            using (mp.Step("SERVICESTACK serialization"))
            {
                1.Times(i =>
                {
                    foreach (var doc in docs)
                        textSerializer.ToJson(doc);
                });
            }

            Trace.WriteLine($"trace: {mp.RenderPlainText()}");
            MiniProfiler.Stop();
        }
Ejemplo n.º 24
0
 private void Upload(School obj)
 {
     try
     {
         using (var webClient = new WebClient())
         {
             webClient.UseDefaultCredentials = true;
             string stringify = new JsonNetSerializer().Stringify(obj);
             var result = webClient.UploadString(new Uri(new
                                                             Uri("http://www.schoolsnearme.co.uk"), "/api/SchoolsUpload"), "POST", stringify);
         }
     }
     catch (Exception e)
     {
         throw new Exception("Error encountered while stopping indexing", e);
     }
 }
Ejemplo n.º 25
0
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();

            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
            AuthConfig.RegisterAuth();

            Database.SetInitializer(new ScrumBoardDatabaseInitializer());

            var serializer = new JsonNetSerializer(new JsonSerializerSettings
            {
                ReferenceLoopHandling = ReferenceLoopHandling.Ignore
            });
            GlobalHost.DependencyResolver.Register(typeof(IJsonSerializer), () => serializer);
        }
Ejemplo n.º 26
0
        public MartenDatabaseFixture()
        {
            DocumentStore = DocumentStore
                            .For(_ =>
            {
                _.Connection("host=dev-machine;database=marten_ut_database;password=admin;username=postgres");

                var serializer = new JsonNetSerializer();

                var dcr = new DefaultContractResolver();

                dcr.DefaultMembersSearchFlags |= BindingFlags.NonPublic;

                serializer.Customize(i =>
                {
                    i.ContractResolver = dcr;
                });
                _.Serializer(serializer);
            });
        }
        protected ElasticsearchSinkTestsBase()
        {
            _seenHttpPosts = new List <string>();
            _seenHttpHeads = new List <int>();
            _seenHttpPuts  = new List <Tuple <Uri, string> >();

            var connectionPool = new SingleNodeConnectionPool(new Uri("http://localhost:9200"));

            _connection = new ConnectionStub(_seenHttpPosts, _seenHttpHeads, _seenHttpPuts, () => _templateExistsReturnCode);
            _serializer = JsonNetSerializer.Default(LowLevelRequestResponseSerializer.Instance, new ConnectionSettings(connectionPool, _connection));

            _options = new ElasticsearchSinkOptions(connectionPool)
            {
                BatchPostingLimit = 2,
                //Period = TinyWait,
                Connection   = _connection,
                Serializer   = _serializer,
                PipelineName = "testPipe",
            };
        }
Ejemplo n.º 28
0
        public void Init()
        {
            var serializer = new JsonNetSerializer(new JsonSerializerSettings
            {
                ContractResolver  = new CustomSignalRContractResolverBecauseOfIssue500InSignalR(),
                Formatting        = Formatting.None,
                NullValueHandling = NullValueHandling.Ignore,
                Converters        =
                {
                    new IsoDateTimeConverter {
                        DateTimeStyles = DateTimeStyles.RoundtripKind
                    },
                    new StringEnumConverter  {
                        CamelCaseText = true
                    }
                }
            });

            GlobalHost.DependencyResolver.Register(typeof(IJsonSerializer), () => serializer);
        }
Ejemplo n.º 29
0
        public void Encode_Should_Encode_To_Token_With_Extra_Headers()
        {
            var extraHeaders = new Dictionary <string, object>
            {
                { "foo", "bar" }
            };
            const string key      = TestData.Secret;
            var          toEncode = TestData.Customer;
            const string expected = TestData.TokenWithExtraHeaders;

            var algorithm  = new HMACSHA256Algorithm();
            var urlEncoder = new JwtBase64UrlEncoder();
            var serializer = new JsonNetSerializer();
            var encoder    = new JwtEncoder(algorithm, serializer, urlEncoder);

            var actual = encoder.Encode(extraHeaders, toEncode, key);

            actual.Should()
            .Be(expected, "because the same data encoded with the same key must result in the same token");
        }
Ejemplo n.º 30
0
        public void DecodeToObject_Should_Throw_Exception_Before_NotBefore_Becomes_Valid()
        {
            var serializer       = new JsonNetSerializer();
            var dateTimeProvider = new UtcDateTimeProvider();
            var validTor         = new JwtValidator(serializer, dateTimeProvider);
            var urlEncoder       = new JwtBase64UrlEncoder();
            var decoder          = new JwtDecoder(serializer, validTor, urlEncoder);

            var now = dateTimeProvider.GetNow();
            var nbf = UnixEpoch.GetSecondsSince(now.AddHours(1));

            var encoder = new JwtEncoder(new HMACSHA256Algorithm(), serializer, urlEncoder);
            var token   = encoder.Encode(new { nbf }, TestData.Key);

            Action decodeNotActiveJwt =
                () => decoder.DecodeToObject <Customer>(token, TestData.Key, verify: true);

            decodeNotActiveJwt.Should()
            .Throw <SignatureVerificationException>();
        }
Ejemplo n.º 31
0
        public void DecodeToObject_Should_Throw_Exception_On_Null_Expiration_Claim_MultipleKeys()
        {
            const string key = TestData.Key;

            var serializer = new JsonNetSerializer();
            var validator  = new JwtValidator(serializer, new UtcDateTimeProvider());

            var urlEncoder = new JwtBase64UrlEncoder();
            var decoder    = new JwtDecoder(serializer, validator, urlEncoder);

            var encoder = new JwtEncoder(new HMACSHA256Algorithm(), serializer, urlEncoder);
            var token   = encoder.Encode(new { exp = (object)null }, key);

            Action encodeJwtWithNullExpField =
                () => decoder.DecodeToObject <Customer>(token, new[] { key }, verify: true);

            encodeJwtWithNullExpField.Should()
            .Throw <SignatureVerificationException>()
            .WithMessage("Claim 'exp' must be a number.", "because the invalid 'exp' must result in an exception on decoding");
        }
Ejemplo n.º 32
0
        /// <summary>
        /// Generates JWT
        /// </summary>
        /// <param name="id"></param>
        /// <param name="secret"></param>
        /// <returns>JWT string</returns>
        public static string GenerateToken(int id, string secret)
        {
            var   add12HoursUtc = DateTime.UtcNow.AddHours(12);
            Int32 unixTimestamp = (Int32)(add12HoursUtc.Subtract(new DateTime(1970, 1, 1))).TotalSeconds;

            IJwtAlgorithm     algorithm  = new HMACSHA256Algorithm();
            IJsonSerializer   serializer = new JsonNetSerializer();
            IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder();
            IJwtEncoder       encoder    = new JwtEncoder(algorithm, serializer, urlEncoder);

            var payload = new Dictionary <string, object>
            {
                { "id", id },
                { "exp", unixTimestamp }
            };

            var token = encoder.Encode(payload, secret);

            return(token);
        }
Ejemplo n.º 33
0
 public static string CreateJWT(PayloadJWT payload)
 {
     try
     {
         if (string.IsNullOrEmpty(secretJWT))
         {
             secretJWT = ConfigurationManager.AppSettings["secretJWT"] != null ? ConfigurationManager.AppSettings["secretJWT"] : initVector;
         }
         IJwtAlgorithm     algorithm  = new HMACSHA256Algorithm(); // symmetric
         IJsonSerializer   serializer = new JsonNetSerializer();
         IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder();
         IJwtEncoder       encoder    = new JwtEncoder(algorithm, serializer, urlEncoder);
         var token = encoder.Encode(payload, secretJWT);
         return(token);
     }
     catch (Exception)
     {
         return("Error");
     }
 }
        public void Deserializes()
        {
            // arrange
            var expectedResult = new SerializerWorks
            {
                BecauseItsAwesome = true,
                Inception = new SerializerWorks {
                    BecauseItsAwesome = true
                }
            };

            var input = "{\"BecauseItsAwesome\":true,\"Inception\":{\"BecauseItsAwesome\":true}}";

            var sut = new JsonNetSerializer();
            // act
            var result = sut.Deserialize(input, expectedResult.GetType());

            // assert
            result.ShouldBeEquivalentTo(expectedResult);
        }
Ejemplo n.º 35
0
        public void DecodeToObject_Should_Throw_Exception_On_Null_NotBefore_Claim()
        {
            var key = _fixture.Create <string>();

            var serializer = new JsonNetSerializer();
            var validator  = new JwtValidator(serializer, new UtcDateTimeProvider());

            var urlEncoder = new JwtBase64UrlEncoder();
            var decoder    = new JwtDecoder(serializer, validator, urlEncoder);

            var encoder = new JwtEncoder(new HMACSHA256Algorithm(), serializer, urlEncoder);
            var token   = encoder.Encode(new { nbf = (object)null }, key);

            Action encodeJwtWithNullExpField =
                () => decoder.DecodeToObject <Customer>(token, key, verify: true);

            encodeJwtWithNullExpField.Should()
            .Throw <SignatureVerificationException>()
            .WithMessage("Claim 'nbf' must be a number.", "because the invalid 'nbf' must result in an exception on decoding");
        }
Ejemplo n.º 36
0
        public string RefreshToken(string tokenString)
        {
            IJsonSerializer   serializer = new JsonNetSerializer();
            IDateTimeProvider provider   = new UtcDateTimeProvider();
            IJwtValidator     validator  = new JwtValidator(serializer, provider);
            IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder();

            try
            {
                IJwtDecoder decoder = new JwtDecoder(serializer, validator, urlEncoder);
                // var json = decoder.Decode(tokenString, Secret, verify: true);
                var payload = decoder.DecodeToObject <IDictionary <string, object> >(tokenString, Secret, verify: true);
                return("ok");
            }
            catch (System.Exception)
            {
                //失效或者过期或者不合法
                return("401");
            }
        }
Ejemplo n.º 37
0
        public string Encrypt(string encryptStr)
        {
            TimeSpan ts      = DateTime.Now - new DateTime(1970, 1, 1, 0, 0, 0, 0);
            long     seconds = Convert.ToInt64(ts.TotalSeconds);
            //载荷(payload)
            var payload = new Dictionary <string, object>()
            {
                { "iss", "ut" },//发行人
                { "sub", "ideuser" },
                { "jti", encryptStr },
                { "iat", seconds },
                { "exp", seconds },
            };
            IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder(); //Base64编解码
            IJsonSerializer   serializer = new JsonNetSerializer();   //序列化和反序列
            IJwtAlgorithm     algorithm  = new HMACSHA256Algorithm(); //HMACSHA256加密
            IJwtEncoder       encoder    = new JwtEncoder(algorithm, serializer, urlEncoder);

            return(encoder.Encode(payload, secret));
        }
Ejemplo n.º 38
0
        static void Encrypt()
        {
            #region 1) 加密

            double exp     = (DateTime.UtcNow.AddSeconds(10) - new DateTime(1970, 1, 1)).TotalSeconds;
            var    payload = new Dictionary <string, object>
            {
                { "UserId", 123 },
                { "UserName", "admin" },
                { "exp", exp + 100 }
            };
            var               secret     = "GQDstcKsx0NHjPOuXOYg5MbeJ1XT0uFiwDVvVBrk";//不要泄露
            IJwtAlgorithm     algorithm  = new HMACSHA256Algorithm();
            IJsonSerializer   serializer = new JsonNetSerializer();
            IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder();
            IJwtEncoder       encoder    = new JwtEncoder(algorithm, serializer, urlEncoder);
            var               token      = encoder.Encode(payload, secret);
            Console.WriteLine(token);
            #endregion
        }
Ejemplo n.º 39
0
        private static TenantToken GetTenantToken(string access_token)
        {
            try
            {
                IJsonSerializer   serializer = new JsonNetSerializer();
                IDateTimeProvider provider   = new UtcDateTimeProvider();
                IJwtValidator     validator  = new JwtValidator(serializer, provider);
                IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder();
                IJwtDecoder       decoder    = new JwtDecoder(serializer, validator, urlEncoder);

                string resultContent = decoder.Decode(access_token, client_secret, verify: false);

                TenantToken tenantToken = JsonConvert.DeserializeObject <TenantToken>(resultContent);
                return(tenantToken);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Ejemplo n.º 40
0
        public void DecodeToObject_Should_DecodeToken_On_Exp_Claim_After_Year2038()
        {
            var serializer       = new JsonNetSerializer();
            var dateTimeProvider = new UtcDateTimeProvider();
            var validator        = new JwtValidator(serializer, dateTimeProvider);
            var urlEncoder       = new JwtBase64UrlEncoder();
            var decoder          = new JwtDecoder(serializer, validator, urlEncoder);

            //Why 2038? https://en.wikipedia.org/wiki/Year_2038_problem
            var post2038   = new DateTime(2038, 1, 19, 3, 14, 8, DateTimeKind.Utc);
            var exp        = (post2038 - new DateTime(1970, 1, 1)).TotalSeconds;
            var payload    = new { exp = exp };
            var encoder    = new JwtEncoder(new HMACSHA256Algorithm(), serializer, urlEncoder);
            var validToken = encoder.Encode(payload, "ABC");

            var expectedPayload = serializer.Serialize(payload);
            var actualPayload   = decoder.Decode(validToken, "ABC", true);

            actualPayload.Should().Be(expectedPayload);
        }
Ejemplo n.º 41
0
        private string GetToken(Dictionary <string, object> payload, bool sessionLifetime = false)
        {
            var secret = _jwtSettings.SecretKey;

            payload.Add(JwtClaimTypes.Issuer, _jwtSettings.Issuer);
            payload.Add(JwtClaimTypes.Audience, _jwtSettings.Audience);
            payload.Add(JwtClaimTypes.IssuedAt, DateTime.UtcNow.ConvertToUnixTimestamp());

            if (!sessionLifetime)
            {
                payload.Add("exp", DateTime.UtcNow.AddDays(30).ConvertToUnixTimestamp());
            }

            IJwtAlgorithm     algorithm  = new HMACSHA256Algorithm();
            IJsonSerializer   serializer = new JsonNetSerializer();
            IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder();
            IJwtEncoder       encoder    = new JwtEncoder(algorithm, serializer, urlEncoder);

            return(encoder.Encode(payload, secret));
        }
        public void persist_a_single_document()
        {
            var user = new User {FirstName = "Magic", LastName = "Johnson"};

            theSession.Store(user);

            theSession.SaveChanges();

            var runner = new CommandRunner(new ConnectionSource());

            var json = runner.QueryScalar<string>("select data from mt_doc_user where id = '{0}'".ToFormat(user.Id));

            json.ShouldNotBeNull();

            var loadedUser = new JsonNetSerializer().FromJson<User>(json);

            user.ShouldNotBeSameAs(loadedUser);
            loadedUser.FirstName.ShouldBe(user.FirstName);
            loadedUser.LastName.ShouldBe(user.LastName);
        }
Ejemplo n.º 43
0
        public static void Import_Patients_to_ElasticDB(Patient_Model_xls patient, string TenantID)
        {
            string indexElastic = TenantID;
            var    serializer   = new JsonNetSerializer();
            var    connection   = Elastic_Utils.ElsaticConnection();

            connection.Delete(indexElastic);
            //bool checkIndex = Elastic_Utils.IfIndexOrTypeExists(indexElastic, connection);


            //if (!checkIndex)
            //{
            //    Console.WriteLine("Index ne postoji");

            //    string settings = Elastic_Utils.BuildIndexSettings();
            //    connection.Put(indexElastic, settings);

            //    string jsonProductMapping = BuildPatientMapping();
            //    string resultProductMapping = connection.Put(new PutMappingCommand(indexElastic, "patient"), jsonProductMapping);
            //}

            //Console.WriteLine("Index exists: " + checkIndex.ToString());

            //bool checkTupe = Elastic_Utils.IfIndexOrTypeExists(indexElastic + "/patient", connection);

            //if (!checkTupe)
            //{
            //    Console.WriteLine("Type ne postoji. ");

            //    string jsonProductMapping = BuildPatientMapping();
            //    string resultProductMapping = connection.Put(new PutMappingCommand(indexElastic, "patient"), jsonProductMapping);

            //    Console.WriteLine("Type Kreiran. ");
            //}

            //Console.WriteLine("Type exists: " + checkTupe.ToString());

            //List<Patient_Model> modelList = new List<Patient_Model>();
            //modelList.Add(patient);
            //Elastic_Utils.BulkType_Generic<Patient_Model>(modelList, connection, serializer, indexElastic, "patient");
        }
Ejemplo n.º 44
0
        public static void Import_Oct_Data_to_ElasticDB(IEnumerable <Oct_Model> octs, string indexName)
        {
            var  serializer   = new JsonNetSerializer();
            var  connection   = Elastic_Utils.ElsaticConnection();
            bool index_exists = Elastic_Utils.IfIndexOrTypeExists(indexName, connection);

            if (!index_exists)
            {
                //create new index
                string settings = Elastic_Utils.BuildIndexSettings();
                connection.Put(indexName, settings);
            }

            bool type_exists = Elastic_Utils.IfIndexOrTypeExists(String.Format("{0}/{1}", indexName, elasticType), connection);

            if (!type_exists)
            {
                string json_oct_mapping = Elastic_Utils.BuildElasticMapping <Oct_Model>(elasticType, new List <ElasticMappingConfigObject>()
                {
                    new ElasticMappingConfigObject {
                        analyzerName = "not_analyzed", fieldName = "id"
                    },
                    new ElasticMappingConfigObject {
                        analyzerName = "autocomplete", fieldName = "treatment_doctor_lanr", searchAnalyzer = "keyword"
                    },
                    new ElasticMappingConfigObject {
                        analyzerName = "autocomplete", fieldName = "oct_doctor_lanr", searchAnalyzer = "keyword"
                    },
                    new ElasticMappingConfigObject {
                        analyzerName = "autocomplete", fieldName = "treatment_doctor_practice_bsnr", searchAnalyzer = "keyword"
                    },
                    new ElasticMappingConfigObject {
                        analyzerName = "autocomplete", fieldName = "patient_insurance_number", searchAnalyzer = "keyword"
                    },
                });

                connection.Put(new PutMappingCommand(indexName, elasticType), json_oct_mapping);
            }

            Elastic_Utils.BulkType <Oct_Model>(octs.ToList(), connection, serializer, indexName, elasticType);
        }
Ejemplo n.º 45
0
        /// <summary>
        /// Decode the access token and calculate the time to request a new token.
        /// A time buffer prevents the edge case of the token expiring before the request could be made.
        /// The buffer will be a fraction of the total time to live - we are using 80%
        /// </summary>
        /// <param name="accessToken">JSON Web Token received from the service</param>
        /// <returns></returns>
        private long CalculateTimeForNewToken(string accessToken)
        {
            // the time of expiration is found by decoding the JWT access token
            // exp is the time of expire and iat is the time of token retrieval
            long timeForNewToken = 0;

            try
            {
                IJsonSerializer   serializer = new JsonNetSerializer();
                IDateTimeProvider provider   = new UtcDateTimeProvider();
                IJwtValidator     validator  = new JwtValidator(serializer, provider);
                IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder();
                IJwtDecoder       decoder    = new JwtDecoder(serializer, validator, urlEncoder);

                var decodedResponse = decoder.Decode(accessToken);

                if (!string.IsNullOrEmpty(decodedResponse))
                {
                    var  token = JObject.Parse(decodedResponse);
                    long exp   = (long)token["exp"];
                    long iat   = (long)token["iat"];

                    double fractonOfTtl = 0.8d;
                    long   timeToLive   = exp - iat;
                    timeForNewToken = Convert.ToInt64(exp - (timeToLive * (1.0d - fractonOfTtl)));
                }
                else
                {
                    throw new Exception("Access token recieved is not a valid JWT");
                }
            }
            catch (TokenExpiredException)
            {
                Log.Debug("CalculateTimeForNewToken():", "Token has expired");
            }
            catch (SignatureVerificationException)
            {
                Log.Debug("CalculateTimeForNewToken():", "Token has invalid signature");
            }
            return(timeForNewToken);
        }
Ejemplo n.º 46
0
        public AjaxResult test2()
        {
            AuthInfo authInfo = new AuthInfo
            {
                IsAdmin = true,
                Roles   = new List <string> {
                    "admin", "owner"
                },
                UserName = "******"
            };

            IJwtAlgorithm     algorithm    = new HMACSHA256Algorithm();
            IJsonSerializer   serializer   = new JsonNetSerializer();
            IBase64UrlEncoder urlEncoder   = new JwtBase64UrlEncoder();
            IJwtEncoder       encoder      = new JwtEncoder(algorithm, serializer, urlEncoder);
            string            encryptToken = encoder.Encode(authInfo, "123456");



            IJwtDecoder decoder = new JwtDecoder(serializer, urlEncoder);
            string      result  = decoder.Decode(encryptToken);


            string token = JwtHelper.CreateJWT(authInfo, "123456");

            AuthInfo tokenAuthInfo = JwtHelper.DecodeJWT <AuthInfo>(token, "123456");



            return(new AjaxResult
            {
                statusCode = 200,
                data = new {
                    authInfo = authInfo,
                    encryptToken = encryptToken,
                    result = JsonHelper.Deserialize <AuthInfo>(result),
                    token = token,
                    tokenAuthInfo = tokenAuthInfo
                }
            });
        }
Ejemplo n.º 47
0
        /// <summary>
        /// 指示指定的控件是否已获得授权
        /// </summary>
        /// <param name="actionContext"></param>
        /// <returns></returns>
        protected override bool IsAuthorized(HttpActionContext actionContext)
        {
            //前端请求api时会将token存放在名为"auth"的请求头中
            var authHeader = from t in actionContext.Request.Headers where t.Key == "Authorization" select t.Value.FirstOrDefault();

            if (authHeader != null)
            {
                const string secretKey = "Hello World";               //加密秘钥
                string       token     = authHeader.FirstOrDefault(); //获取token
                if (!string.IsNullOrEmpty(token))
                {
                    try
                    {
                        byte[]            key        = Encoding.UTF8.GetBytes(secretKey);
                        IJsonSerializer   serializer = new JsonNetSerializer();
                        IDateTimeProvider provider   = new UtcDateTimeProvider();
                        IJwtValidator     validator  = new JwtValidator(serializer, provider);
                        IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder();
                        IJwtDecoder       decoder    = new JwtDecoder(serializer, validator, urlEncoder);
                        //解密
                        var json = decoder.DecodeToObject <AuthInfo>(token, key, verify: true);
                        if (json != null)
                        {
                            //判断口令过期时间
                            if (json.ExpiryDateTime < DateTime.Now)
                            {
                                return(false);
                            }
                            actionContext.RequestContext.RouteData.Values.Add("Authorization", json);
                            return(true);
                        }
                        return(false);
                    }
                    catch (Exception ex)
                    {
                        return(false);
                    }
                }
            }
            return(false);
        }
Ejemplo n.º 48
0
        public async Task <List <Model> > GetModels()
        {
            var modelList = new List <Model>();

            try
            {
                var command = new Command
                {
                    Id     = EnvelopeId.NewId(),
                    To     = Node.Parse("*****@*****.**"),
                    Uri    = new LimeUri("/models"),
                    Method = CommandMethod.Get,
                };

                var envelopeSerializer = new JsonNetSerializer();
                var commandString      = envelopeSerializer.Serialize(command);

                var httpContent = new StringContent(commandString, Encoding.UTF8, "application/json");

                HttpResponseMessage response = await _client.PostAsync("/commands", httpContent);

                response.EnsureSuccessStatusCode();
                string responseBody = await response.Content.ReadAsStringAsync();

                var envelopeResult  = (Command)envelopeSerializer.Deserialize(responseBody);
                var modelCollection = envelopeResult.Resource as DocumentCollection;

                foreach (var model in modelCollection)
                {
                    modelList.Add(model as Model);
                }

                return(modelList);
            }
            catch (HttpRequestException e)
            {
                Console.WriteLine("\nException Caught!");
                Console.WriteLine("Message :{0} ", e.Message);
                return(null);
            }
        }
Ejemplo n.º 49
0
        /// <summary>
        /// Token校验
        /// </summary>
        /// <param name="token"></param>
        /// <returns></returns>
        public static JWTPlayloadInfo CheckToken(string token)
        {
            if (string.IsNullOrEmpty(token))
            {
                return(null);
            }

            IJsonSerializer   serializer = new JsonNetSerializer();
            IDateTimeProvider provider   = new UtcDateTimeProvider();
            IJwtValidator     validator  = new JwtValidator(serializer, provider);

            IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder();
            IJwtDecoder       decoder    = new JwtDecoder(serializer, validator, urlEncoder);

            //获取私钥
            string secret = GetSecret();

            try
            {
                JWTPlayloadInfo playload = decoder.DecodeToObject <JWTPlayloadInfo>(token, secret, true);
                if (playload != null)
                {
                    if (!string.IsNullOrEmpty(playload.aud) && playload.aud.Equals("guest"))
                    {
                        string cacheToken = CacheFactory.GetCache().Get <string>("JWT_TokenCacheKey:Guest");

                        return(Check(playload, cacheToken, token) ? playload : null);
                    }
                    else
                    {
                        string cacheToken = CacheFactory.GetCache().Get <string>(string.Format("JWT_TokenCacheKey:{0}", playload.aud));
                        return(Check(playload, cacheToken, token) ? playload : null);
                    }
                }
            }
            catch (Exception e)
            {
                return(null);
            }
            return(null);
        }
Ejemplo n.º 50
0
        //解密
        public static Dictionary <string, object> Decoder(string jwtstr, string key = null)
        {
            if (string.IsNullOrEmpty(key))
            {
                key = Key;
            }

            try
            {
                IJwtAlgorithm     algorithm  = new HMACSHA256Algorithm();
                IJsonSerializer   serializer = new JsonNetSerializer();
                IDateTimeProvider provider   = new UtcDateTimeProvider();
                IJwtValidator     validator  = new JwtValidator(serializer, provider);
                IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder();
                IJwtDecoder       decoder    = new JwtDecoder(serializer, validator, urlEncoder, algorithm);

                var json = decoder.Decode(jwtstr, key, true);

                //string转化成Dictionary
                //把一个字符串反向生成对应的对象内容
                var result = JsonConvert.DeserializeObject <Dictionary <string, object> >(json);

                if ((DateTime)result["timeout"] < DateTime.Now)
                {
                    throw new Exception("jwt已过期,请重新登录");
                }

                result.Remove("tomeout");
                return(result);
            }
            catch (TokenExpiredException)
            {
                Console.WriteLine("Token has expired");
                throw;
            }
            catch (SignatureVerificationException)
            {
                Console.WriteLine("Token has invalid signature");
                throw;
            }
        }
Ejemplo n.º 51
0
        public static Dictionary <string, object> Verify(string token)
        {
            IJsonSerializer   serializer = new JsonNetSerializer();
            IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder();

            var segments = token.Split('.');

            if (segments.Length != 3)
            {
                throw new Exception("token invalid");
            }

            var header = serializer.Deserialize <Dictionary <string, string> >(
                System.Text.Encoding.UTF8.GetString(urlEncoder.Decode(segments[0])));

            if (header["alg"] != "EK256K")
            {
                throw new Exception("alg should be EK256K but got " + header["alg"]);
            }


            var payload = serializer.Deserialize <Dictionary <string, object> >(
                System.Text.Encoding.UTF8.GetString(urlEncoder.Decode(segments[1])));
            var signature = urlEncoder.Decode(segments[2]);

            var empty            = new Account();
            var recoveredAddress = empty.Recover(segments[0] + "." + segments[1], signature, false);

            var secretOrPublicKey = payload["iss"].ToString();
            var expectedAddress   = Account.PublicKeyToAddress(secretOrPublicKey.HexToByteArray());

            if (recoveredAddress != expectedAddress)
            {
                throw new Exception(recoveredAddress + " signed the signature but we are expecting " + expectedAddress);
            }
            if (payload["iss"].ToString() != secretOrPublicKey)
            {
                throw new Exception("issuer of the token does not match " + secretOrPublicKey);
            }
            return(payload);
        }
Ejemplo n.º 52
0
        public JObject order(Dictionary <string, string> par)
        {
            string url         = ac.BASE_URL + "orders";
            string queryString = string.Join("&", par.Select(x => x.Key + "=" + x.Value).ToArray());

            byte[] queryHashByteArray = SHA512.Create().ComputeHash(Encoding.UTF8.GetBytes(queryString));
            string queryHash          = BitConverter.ToString(queryHashByteArray).Replace("-", "").ToLower();

            var payload = new JwtPayload
            {
                { "access_key", access_key },
                { "nonce", Guid.NewGuid().ToString() },
                { "query_hash", queryHash },
                { "query_hash_alg", "SHA512" },
            };

            IJwtAlgorithm     algorithm       = new HMACSHA256Algorithm();
            IJsonSerializer   serializer      = new JsonNetSerializer();
            IBase64UrlEncoder urlEncoder      = new JwtBase64UrlEncoder();
            IJwtEncoder       encoder         = new JwtEncoder(algorithm, serializer, urlEncoder);
            string            token           = encoder.Encode(payload, secret_key);
            string            authorize_token = "Bearer " + token;

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url + "?" + queryString);

            request.Method = "POST";
            request.Headers.Add("Authorization:" + authorize_token);

            try
            {
                WebResponse  response   = request.GetResponse();
                Stream       dataStream = response.GetResponseStream();
                StreamReader reader     = new StreamReader(dataStream);
                return(JObject.Parse(reader.ReadToEnd()));
            }
            catch (Exception ex)
            {
                _ = ex;
                return(null);
            }
        }
Ejemplo n.º 53
0
        protected override bool AuthorizeCore(HttpContextBase httpContext)
        {
            //前端请求api时会将token存放在名为"auth"的请求头中
            var authHeader = httpContext.Request.Headers.GetValues("auth");

            if (authHeader != null)
            {
                const string secretKey = "Hello World";               //加密秘钥
                string       token     = authHeader.FirstOrDefault(); //获取token
                if (!string.IsNullOrEmpty(token))
                {
                    try
                    {
                        byte[]            key        = Encoding.UTF8.GetBytes(secretKey);
                        IJsonSerializer   serializer = new JsonNetSerializer();
                        IDateTimeProvider provider   = new UtcDateTimeProvider();
                        IJwtValidator     validator  = new JwtValidator(serializer, provider);
                        IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder();
                        IJwtDecoder       decoder    = new JwtDecoder(serializer, validator, urlEncoder);
                        //解密
                        var json = decoder.DecodeToObject <AuthInfo>(token, key, verify: true);
                        if (json != null)
                        {
                            //判断口令过期时间
                            if (json.ExpiryDateTime < DateTime.Now)
                            {
                                return(false);
                            }
                            httpContext.Response.AddHeader("auth", json.ToString());
                            return(true);
                        }
                        return(false);
                    }
                    catch (Exception ex)
                    {
                        return(false);
                    }
                }
            }
            return(false);
        }
        public void when_serializing()
        {
            // Given
            JsonConvert.DefaultSettings = GetJsonSerializerSettings;

            var guid = Guid.NewGuid();
            var data = new { SomeString = "some string value", SomeGuid = guid, NullValue = default(Uri) };
            string expected = string.Format("{{\"someString\":\"some string value\",\"someGuid\":\"{0}\"}}", guid);

            // When
            string actual;
            using (var stream = new MemoryStream())
            {
                ISerializer sut = new JsonNetSerializer();
                sut.Serialize("application/json", data, stream);
                actual = Encoding.UTF8.GetString(stream.ToArray());
            }

            // Then
            Assert.Equal(expected, actual);
        }
Ejemplo n.º 55
0
        //自定义json解析器,只要继承IJsonSerializer接口

        //public class CustomJsonSerializer : IJsonSerializer
        //{
        //    public string Serialize(object obj)
        //    {
        //        return null;
        //        // Implement using favorite JSON Serializer
        //    }

        //    public T Deserialize<T>(string json)
        //    {
        //        //return json;
        //        // Implement using favorite JSON Serializer
        //    }
        //}

        /*
         * 自定义JSON序列化
         *
         * 默认的JSON序列化由JsonNetSerializer完成
         *
         *
         */

        public void Test()
        {
            JsonSerializer customJsonSerializer = new JsonSerializer
            {
                // All json keys start with lowercase characters instead of the exact casing of the model/property. e.g. fullName
                ContractResolver = new CamelCasePropertyNamesContractResolver(),

                // Nice and easy to read, but you can also do Formatting.None to reduce the payload size (by hardly anything...)
                Formatting = Formatting.Indented,

                // The best date/time format/standard.
                DateFormatHandling = DateFormatHandling.IsoDateFormat,

                // Don't add key/values when the value is null.
                NullValueHandling = NullValueHandling.Ignore,

                // Use the enum string-value, not the implicit int value, e.g. "oolor" : "red"
                // Newtonsoft.Json.Converters.Add(new StringEnumConverter())
            };
            IJsonSerializer serializer = new JsonNetSerializer(customJsonSerializer);
        }
        public override Task OnExceptionAsync(ExceptionContext context)
        {
            var exception = context.Exception;

            if (RewriteErrors)
            {
                var rewriter = context.HttpContext.RequestServices.GetRequiredService <IErrorRewriter>();
                exception = rewriter.Rewrite(context, exception, true);
            }
            var serializer = new JsonNetSerializer(JsonNetSerializer.DefaultSettings);
            var content    = serializer.Serialize(exception);
            var result     = new ContentResult()
            {
                Content     = content,
                ContentType = "application/json",
                StatusCode  = (int)HttpStatusCode.InternalServerError,
            };

            context.ExceptionHandled = true;
            return(result.ExecuteResultAsync(context));
        }
Ejemplo n.º 57
0
        public override void Load()
        {
            var settings = new JsonSerializerSettings
                {
                    ContractResolver = new SelectiveCamelCaseContractResolver(),
                    Converters = { new StringEnumConverter() }
                };

            var jsonNetSerializer = new JsonNetSerializer(settings);
            
            GlobalHost.DependencyResolver = new NinjectSignalRDependencyResolver(Kernel);
            GlobalHost.DependencyResolver.Register(typeof(IJsonSerializer), () => jsonNetSerializer);

            var hub = GlobalHost.ConnectionManager.GetHubContext<StatusHub>();

            var repository = Kernel.Get<ILucenePackageRepository>();

            repository.StatusChanged
                .Sample(TimeSpan.FromMilliseconds(250))
                .Subscribe(status => hub.Clients.All.updateStatus(status));
        }
Ejemplo n.º 58
0
        public void Decode_To_Encode_Expired()
        {
            var use = new User()
            {
                Name = "123"
            };
            var serialize        = new JsonNetSerializer();
            var dateTimeProvider = new UtcDateTimeProvider();
            var validTor         = new JwtValidator(serialize, dateTimeProvider);
            var urlEncoder       = new Base64UrlEncoder();
            var endocer          = new JwtEncoder(new HMACSHA256Algorithm(), serialize, urlEncoder);
            var decoder          = new JwtDecoder(serialize, validTor, urlEncoder, new HMACSHAAlgorithmFactory());

            var now    = dateTimeProvider.GetNow();
            var exp    = UnixEpoch.GetSecondsSince(now.AddHours(-1));
            var token  = endocer.Encode(new { exp }, "wss");
            var actual = decoder.Decode(token, "wss", true);
            var name   = nameof(User.Name);

            Assert.NotEmpty(name);
        }
Ejemplo n.º 59
0
 public Dictionary <string, object> DecodeToken(string token, string secret)
 {
     try
     {
         IJsonSerializer   serializer = new JsonNetSerializer();
         IDateTimeProvider provider   = new UtcDateTimeProvider();
         IJwtValidator     validator  = new JwtValidator(serializer, provider);
         IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder();
         IJwtDecoder       decoder    = new JwtDecoder(serializer, validator, urlEncoder, new JWT.Algorithms.HMACSHAAlgorithmFactory());
         var result = decoder.DecodeToObject <Dictionary <string, object> >(token, string.IsNullOrEmpty(secret) ? _tokenSecret : secret, verify: true);
         return(result);
     }
     catch (TokenExpiredException)
     {
         return(null);
     }
     catch
     {
         return(null);
     }
 }
Ejemplo n.º 60
0
        private List<JsonWeek> GetJsonSchedule()
        {
            if (this._jsonWeeks == null)
            {
                this._jsonWeeks = new List<string>()
                {
                //        day 1          day 2         day 3        day 4         day 5         day 6          day 7
                    @"[{'AE':[1,2]}, {'AE':[3,4]}, {'AE':[5,1]}, {'AE':[2,3]}, {'AE':[4,5]}, {'AE':[1,2]}, {'AE':[3,4]}]",
                    @"[{'AE':[5,1]}, {'AE':[2,3]}, {'AE':[4,5]}, {'AE':[1,2]}, {'AE':[3,4]}, {'AE':[5,1]}, {'AE':[2,3]}]",
                    @"[{'AE':[4,5]}, {'AE':[1,2]}, {'AE':[3,4]}, {'AE':[5,1]}, {'AE':[2,3]}, {'AE':[4,5]}, {'AE':[1,2]}]",
                    @"[{'AE':[3,4]}, {'AE':[5,1]}, {'AE':[2,3]}, {'AE':[4,5]}, {'AE':[1,2]}, {'AE':[3,4]}, {'AE':[5,1]}]",
                };
            }

            JsonNetSerializer serializer = new JsonNetSerializer();
            List<JsonWeek> JsonSchedule = new List<JsonWeek>();
            foreach (string jsonWeek in this._jsonWeeks)
            {
                JsonSchedule.Add(new JsonWeek(serializer.Deserialize<List<JsonDay>>(jsonWeek)));
            }
            return JsonSchedule;
        }