Create() public static method

Creates a new JsonSerializer instance using the specified JsonSerializerSettings.
public static Create ( JsonSerializerSettings settings ) : JsonSerializer
settings JsonSerializerSettings The settings to be applied to the .
return JsonSerializer
Exemplo n.º 1
0
        private async Task <T> GetInternal <T>(string url, string instanceName = Settings.DEFAULT_SERVICE_NAME) where T : class
        {
            var response = await GetRaw(url, instanceName).ConfigureAwait(false);

            Console.WriteLine($"{response.RequestMessage.Method} - {url} - {(int) response.StatusCode}");

            //for now
            if (response.StatusCode == HttpStatusCode.NotFound || response.StatusCode == HttpStatusCode.ServiceUnavailable)
            {
                await Task.Delay(1000).ConfigureAwait(false);

                return(null);
            }

            if (response.StatusCode != HttpStatusCode.OK)
            {
                throw new InvalidOperationException($"Call failed: {(int) response.StatusCode} - {response.ReasonPhrase}");
            }

            using (var stream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false))
            {
                var serializer = JsonSerializer.Create(serializerSettings);

                return(serializer.Deserialize <T>(new JsonTextReader(new StreamReader(stream))));
            }
        }
Exemplo n.º 2
0
        private async Task <T> GetInternal <T>(string url) where T : class
        {
            if (!url.StartsWith("http://"))
            {
                url = $"http://localhost:{port}{url}";
            }

            var response = await httpClient.GetAsync(url);

            Console.WriteLine($"{response.RequestMessage.Method} - {url} - {(int) response.StatusCode}");

            //for now
            if (response.StatusCode == HttpStatusCode.NotFound || response.StatusCode == HttpStatusCode.ServiceUnavailable)
            {
                await Task.Delay(1000);

                return(null);
            }

            if (response.StatusCode != HttpStatusCode.OK)
            {
                throw new InvalidOperationException($"Call failed: {(int) response.StatusCode} - {response.ReasonPhrase}");
            }

            using (var stream = await response.Content.ReadAsStreamAsync())
            {
                var serializer = JsonSerializer.Create(serializerSettings);

                return(serializer.Deserialize <T>(new JsonTextReader(new StreamReader(stream))));
            }
        }
Exemplo n.º 3
0
        public JsonMessageSerializer(
            IEventMapper messageMapper)
        {
            this.messageMapper = messageMapper;

            var settings = new JsonSerializerSettings
            {
                TypeNameHandling = TypeNameHandling.Auto,
                Converters       = new JsonConverter[] { new Newtonsoft.Json.Converters.StringEnumConverter(), new IdJsonConverter() },
                Error            = new EventHandler <Newtonsoft.Json.Serialization.ErrorEventArgs>(HandleError),
                ContractResolver = new PrivateSetterContractResolver(),
                //TraceWriter = new TraceWriter(),
                MissingMemberHandling = MissingMemberHandling.Ignore,
                NullValueHandling     = NullValueHandling.Include
            };

            this.writerCreator = (stream =>
            {
                var streamWriter = new StreamWriter(stream, Encoding.UTF8);
                return(new JsonTextWriter(streamWriter)
                {
                    // better for displaying
                    Formatting = Formatting.Indented
                });
            });

            this.readerCreator = (stream =>
            {
                var streamReader = new StreamReader(stream, Encoding.UTF8);
                return(new JsonTextReader(streamReader));
            });

            ContentType    = "Json";
            jsonSerializer = NewtonSerializer.Create(settings);
        }
Exemplo n.º 4
0
        public object[] Deserialize(Stream stream, IList <Type> messageTypes)
        {
            Guard.AgainstNull(stream, "stream");
            Guard.AgainstNull(messageTypes, "messageTypes");

            var jsonSerializer = NewtonSerializer.Create(settings);

            jsonSerializer.ContractResolver = messageContractResolver;
            jsonSerializer.Binder           = new MessageSerializationBinder(messageMapper, messageTypes);

            if (IsArrayStream(stream))
            {
                var arrayReader = readerCreator(stream);
                return(jsonSerializer.Deserialize <object[]>(arrayReader));
            }

            if (messageTypes.Any())
            {
                return(DeserializeMultipleMesageTypes(stream, messageTypes, jsonSerializer).ToArray());
            }

            var simpleReader = readerCreator(stream);

            return(new[]
            {
                jsonSerializer.Deserialize <object>(simpleReader)
            });
        }
Exemplo n.º 5
0
        /// <summary>
        /// Initializes a new instance of the <see cref="HttpBasedAzureFunction"/> class.
        /// </summary>
        /// <param name="httpCorrelation">The correlation service to provide information of related requests.</param>
        /// <param name="logger">The logger instance to write diagnostic messages throughout the execution of the HTTP trigger.</param>
        /// <exception cref="ArgumentNullException">Thrown when the <paramref name="httpCorrelation"/> is <c>null</c></exception>
        protected HttpBasedAzureFunction(HttpCorrelation httpCorrelation, ILogger logger)
        {
            Guard.NotNull(httpCorrelation, nameof(httpCorrelation), "Requires an HTTP correlation instance");
            _httpCorrelation = httpCorrelation;

            Logger = logger ?? NullLogger.Instance;

            var jsonSettings = new JsonSerializerSettings
            {
                MaxDepth          = 10,
                NullValueHandling = NullValueHandling.Ignore,
                TypeNameHandling  = TypeNameHandling.None
            };

            jsonSettings.Converters.Add(new StringEnumConverter());
            JsonSerializer = JsonSerializer.Create(jsonSettings);

            var jsonOptions = new JsonSerializerOptions
            {
                MaxDepth         = 10,
                IgnoreNullValues = true
            };

            jsonOptions.Converters.Add(new JsonStringEnumConverter());
            OutputFormatters = new FormatterCollection <IOutputFormatter> {
                new SystemTextJsonOutputFormatter(jsonOptions)
            };
        }
 static JsonSerializer BuildJsonSerializer(JsonSerializerSettings jsonSerializerSettings)
 {
     if (jsonSerializerSettings == null)
     {
         return(Serializer.JsonSerializer);
     }
     return(JsonSerializer.Create(jsonSerializerSettings));
 }
Exemplo n.º 7
0
        public JsonSerialization(JsonSerializerSettings settings)
        {
            _serializer = JsonSerializer.Create(settings);

            _serializer.Converters.Add(new StringEnumConverter());

            Culture     = CultureInfo.InvariantCulture;
            ContentType = ContentTypes.ApplicationJson;
        }
Exemplo n.º 8
0
 /// <summary>
 /// Transforms serialized data back to the requested object type
 /// </summary>
 /// <typeparam name="TObj">Type of object to reconstruct</typeparam>
 /// <param name="data">Data to be de-serialized</param>
 /// <param name="offset">Offset to start reading from</param>
 /// <returns>De-serialized object</returns>
 public TObj Deserialize <TObj>(byte[] data, int offset)
 {
     using (var stream = new MemoryStream(data, offset, data.Length - offset))
         using (var reader = new StreamReader(stream))
             using (var jsonReader = new JsonTextReader(reader))
             {
                 return(NewtonsoftJsonSerializer.Create(Settings).Deserialize <TObj>(jsonReader));
             }
 }
Exemplo n.º 9
0
        protected virtual void Serialize(JsonWriter writer, object graph)
        {
            using (writer)
            {
                var serializer = JsonNetSerializer.Create(_settings);

                serializer.Binder = new EventSerializationBinder(_eventMapperFunc());
                serializer.Serialize(writer, graph);
            }
        }
Exemplo n.º 10
0
        public IReadOnlyList <TodoTask> GetCompletedTasksOrderedByAddedDate(bool includeCompletedTasks = false)
        {
            var activeTasks = _fileManager.GetCompletedTasksContents();

            return(activeTasks
                   .Select(a => JsonSerializer.Create()
                           .Deserialize <TodoTask>(new JsonTextReader(new StringReader(a))))
                   .OrderByDescending(a => a.Id)
                   .ToList());
        }
Exemplo n.º 11
0
        /// <summary>
        /// Initialises a new instance of the <see cref="NewtonsoftJsonResultOutputFormatter" /> class.
        /// </summary>
        /// <param name="settings">The JSON serializer settings.</param>
        public NewtonsoftJsonResultOutputFormatter(JsonSerializerSettings settings)
        {
            this._bodyJsonSerializer = JsonSerializer.Create(settings);

            this._supportedMediaTypes = new List <MediaType>
            {
                new MediaType(MediaTypeHeaderValues.ApplicationJson.ToString()),
                new MediaType(MediaTypeHeaderValues.TextJson.ToString()),
                new MediaType(MediaTypeHeaderValues.ApplicationAnyJsonSyntax.ToString()),
            };
        }
Exemplo n.º 12
0
 /// <summary>
 /// Transforms the supplied object to the serializer output data type
 /// </summary>
 /// <typeparam name="TObj">Type of object to be serialized</typeparam>
 /// <param name="obj">Object instance to be serialized</param>
 /// <returns>Serialized data</returns>
 public byte[] Serialize <TObj>(TObj obj)
 {
     using (var stream = new MemoryStream())
         using (var writer = new StreamWriter(stream))
             using (var jsonWriter = new JsonTextWriter(writer))
             {
                 NewtonsoftJsonSerializer.Create(Settings).Serialize(writer, obj);
                 jsonWriter.Flush();
                 return(stream.ToArray());
             }
 }
Exemplo n.º 13
0
        protected virtual T Deserialize <T>(JsonReader reader)
        {
            using (reader)
            {
                var serializer = JsonNetSerializer.Create(_settings);

                serializer.ContractResolver = new EventContractResolver(_eventMapperFunc(), _eventFactoryFunc());

                return((T)serializer.Deserialize(reader, typeof(T)));
            }
        }
 public override object ReadJson (JsonReader reader, Type type, object existingValue, JsonSerializer serializer)
 {
     var jobj = JObject.Load(reader);
     var typeName = (string)jobj.Property(JsonLinkedContext.TypePropName);
     if (typeName != null) {
         jobj.Remove(JsonLinkedContext.TypePropName);
         type = serializer.Binder.BindToType(type, typeName);
     }
     var value = existingValue != null && existingValue.GetType() == type ? existingValue : serializer.Create(type);
     serializer.Populate(jobj.CreateReader(), value);
     return value;
 }
Exemplo n.º 15
0
        public void Serialize(object message, Stream stream)
        {
            Guard.AgainstNull(stream, "stream");
            Guard.AgainstNull(message, "message");

            var jsonSerializer = NewtonSerializer.Create(settings);

            jsonSerializer.Binder = new MessageSerializationBinder(messageMapper);
            var jsonWriter = writerCreator(stream);

            jsonSerializer.Serialize(jsonWriter, message);

            jsonWriter.Flush();
        }
Exemplo n.º 16
0
        private FM36Learner GetFm36Learner()
        {
            var fileName = $"SFA.DAS.Payments.EarningEvents.AcceptanceTests.TestData.FM36Learner.json";

            FM36Learner result;

            using (var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(fileName))
                using (var reader = new StreamReader(stream))
                {
                    result = JsonSerializer.Create().Deserialize <FM36Learner>(new JsonTextReader(reader));
                }

            return(result);
        }
Exemplo n.º 17
0
 JsonSerializer GetDeserialize(Version storedSagaTypeVersion)
 {
     if (versionSpecificSettings == null)
     {
         return(jsonSerializer);
     }
     return(deserializers.GetOrAdd(storedSagaTypeVersion, _ =>
     {
         var settings = versionSpecificSettings(sagaDataType, storedSagaTypeVersion);
         if (settings != null)
         {
             return JsonSerializer.Create(settings);
         }
         return jsonSerializer;
     }));
 }
Exemplo n.º 18
0
        public static T ExecuteRequest <T>(string url, Method method, T body, RestClient client, IDictionary <string, object> requestParameters)
            where T : new()
        {
            var request = new RestRequest(url, method);

            if (requestParameters != null)
            {
                foreach (var requestParameter in requestParameters)
                {
                    request.AddParameter(requestParameter.Key, requestParameter.Value);
                }
            }

            if (ShouldAddBody(method))
            {
                var serializer = new NewtonsoftJsonSerializer(
                    JsonSerializer.Create(
                        new JsonSerializerSettings
                {
                    NullValueHandling = NullValueHandling.Ignore
                }));

                request.JsonSerializer = serializer;
                request.RequestFormat  = DataFormat.Json;
                request.AddBody(body);
            }

            //Fixed bug that prevents RestClient for adding custom headers to the request
            //https://stackoverflow.com/questions/22229393/why-is-restsharp-addheaderaccept-application-json-to-a-list-of-item

            client.ClearHandlers();
            client.AddHandler("application/json", new JsonDeserializer());
            var result = ExectueRequest <T>(method, client, request);

            if (result.ErrorException != null)
            {
                throw new WebException("REST client encountered an error: " + result.ErrorMessage, result.ErrorException);
            }
            // This is a hack in order to allow this method to work for simple types as well
            // one example of this is the GetRevisionRaw method
            if (RequestingSimpleType <T>())
            {
                return(result.Content as dynamic);
            }
            return(result.Data);
        }
Exemplo n.º 19
0
                public static string SerializeObject <T>(T value)
                {
                    var sb             = new StringBuilder(256);
                    var sw             = new StringWriter(sb, CultureInfo.InvariantCulture);
                    var jsonSerializer = JsonSerializer.Create(new JsonSerializerSettings
                    {
                        NullValueHandling = NullValueHandling.Ignore,
                        ContractResolver  = new CamelCasePropertyNamesContractResolver(),
                        Formatting        = Formatting.Indented,
                    });

                    using var jsonWrite = new JsonTextWriter(sw)
                          {
                              Indentation = 4
                          };
                    jsonSerializer.Serialize(jsonWrite, value, typeof(T));

                    return(sw.ToString());
                }
Exemplo n.º 20
0
        public static CommandRequest CreateCommandRequest(string AccessSecret, string command, object ObjToSerialise = null)
        {
            CommandRequest cr = new CommandRequest();

            cr.Accesssecret    = AccessSecret;
            cr.Command         = command;
            cr.Commandjsondata = "";

            if (ObjToSerialise != null)
            {
                StringWriter wr       = new StringWriter();
                var          settings = new JsonSerializerSettings();
                settings.StringEscapeHandling = StringEscapeHandling.EscapeHtml;

                (JsonSerializer.Create(settings)).Serialize(wr, ObjToSerialise);
                cr.Commandjsondata = wr.ToString();
            }

            return(cr);
        }
        private static async Task <List <SecretScribe> > ReadFolder()
        {
            try
            {
                string      str  = "encryCode.encry";
                StorageFile file = await ApplicationData.Current.LocalFolder.GetFileAsync(
                    str);

                str = await FileIO.ReadTextAsync(file);

                var json = JsonSerializer.Create();
                var temp = json.Deserialize <List <SecretScribe> >(new JsonTextReader(
                                                                       new StringReader(str)));
                return(temp);
            }
            catch (Exception)
            {
            }
            return(new List <SecretScribe>());
        }
        /// <inheritdoc />
        public JsonCacheSerializer()
        {
            var settings = new JsonSerializerSettings
            {
                TypeNameHandling     = TypeNameHandling.Auto,
                DateTimeZoneHandling = DateTimeZoneHandling.RoundtripKind,
                Formatting           = Formatting.None,
                SerializationBinder  = _serializationBinder,
                ContractResolver     = _contractResolver
            };

            settings.Converters.Add(new ExplicitTypesConverter());
            // Setup the Hashtable serialization
            var contract = settings.ContractResolver.ResolveContract(typeof(Hashtable));

            contract.Converter = new HashtableConverter();
            contract.OnDeserializedCallbacks.Add((o, context) => HashtableConverter.OnDeserialized(o, _serializer));

            _serializer = Serializer.Create(settings);
        }
        public JsonMessageSerializer(
            IEventMapper messageMapper,
            IEventFactory messageFactory,
            JsonConverter[] extraConverters)
        {
            this.messageMapper  = messageMapper;
            this.messageFactory = messageFactory;

            var settings = new JsonSerializerSettings
            {
                TypeNameHandling    = TypeNameHandling.Auto,
                Converters          = new JsonConverter[] { new Newtonsoft.Json.Converters.StringEnumConverter(), new IdJsonConverter() }.Concat(extraConverters).ToArray(),
                Error               = new EventHandler <Newtonsoft.Json.Serialization.ErrorEventArgs>(HandleError),
                ContractResolver    = new EventContractResolver(messageMapper, messageFactory),
                SerializationBinder = new EventSerializationBinder(messageMapper),
                //TraceWriter = new TraceWriter(),
                MissingMemberHandling = MissingMemberHandling.Ignore,
                NullValueHandling     = NullValueHandling.Include
            };

            this.writerCreator = (stream =>
            {
                var streamWriter = new StreamWriter(stream, Utf8NoBom);
                return(new JsonTextWriter(streamWriter)
                {
                    // better for displaying
                    Formatting = Formatting.Indented
                });
            });

            this.readerCreator = (stream =>
            {
                var streamReader = new StreamReader(stream, Utf8NoBom);
                return(new JsonTextReader(streamReader));
            });

            ContentType    = "Json";
            jsonSerializer = NewtonSerializer.Create(settings);
        }
        public JsonMessageSerializer(
            IMessageMapper messageMapper,
            Func <Stream, JsonReader> readerCreator,
            Func <Stream, JsonWriter> writerCreator,
            JsonSerializerSettings settings,
            string contentType)
        {
            this.messageMapper = messageMapper;

            settings = settings ?? new JsonSerializerSettings
            {
                TypeNameHandling = TypeNameHandling.Auto
            };

            this.writerCreator = writerCreator ?? (stream =>
            {
                var streamWriter = new StreamWriter(stream, Encoding.UTF8);
                return(new JsonTextWriter(streamWriter)
                {
                    Formatting = Formatting.None
                });
            });

            this.readerCreator = readerCreator ?? (stream =>
            {
                var streamReader = new StreamReader(stream, Encoding.UTF8);
                return(new JsonTextReader(streamReader));
            });

            if (contentType == null)
            {
                ContentType = ContentTypes.Json;
            }
            else
            {
                ContentType = contentType;
            }
            jsonSerializer = NewtonSerializer.Create(settings);
        }
Exemplo n.º 25
0
        private static ClusterConfig ReadConfig(string file)
        {
            try
            {
                Console.WriteLine($"Using configuration file {file}\n");

                var serializer = JsonSerializer.Create(new JsonSerializerSettings
                {
                    ContractResolver = new CamelCasePropertyNamesContractResolver()
                });

                using (var reader = new StreamReader(file, Encoding.UTF8))
                {
                    using (var jsonReader = new JsonTextReader(reader))
                    {
                        return(serializer.Deserialize <ClusterConfig>(jsonReader));
                    }
                }
            }

            catch (JsonSerializationException ex)
            {
                HumanizeJsonParseException(ex);
                throw;
            }

            catch (JsonException ex)
            {
                Console.WriteLine($"Error: {ex.Message}");
                throw;
            }

            catch (IOException ex)
            {
                Console.WriteLine($"Error: {ex.Message}");
                throw;
            }
        }
Exemplo n.º 26
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>();
            // This custom provider allows able to use just [Authorize] instead of having to define [Authorize(AuthenticationSchemes = "Bearer")] above every API controller
            // without this Bearer authorization will not work
            services.AddSingleton <IAuthenticationSchemeProvider, CustomAuthenticationSchemeProvider>();

            services.AddRedis(Configuration);

            services.AddSignalR().AddPushNotifications(Configuration);

            services.AddOptions <PlatformOptions>().Bind(Configuration.GetSection("VirtoCommerce")).ValidateDataAnnotations();
            services.AddOptions <TranslationOptions>().Configure(options =>
            {
                options.PlatformTranslationFolderPath = WebHostEnvironment.MapPath(options.PlatformTranslationFolderPath);
            });
            //Get platform version from GetExecutingAssembly
            PlatformVersion.CurrentVersion = SemanticVersion.Parse(FileVersionInfo.GetVersionInfo(Assembly.GetExecutingAssembly().Location).ProductVersion);

            services.AddPlatformServices(Configuration);
            services.AddSecurityServices();
            services.AddSingleton <LicenseProvider>();

            // The following line enables Application Insights telemetry collection.
            services.AddApplicationInsightsTelemetry();
            services.AddApplicationInsightsTelemetryProcessor <IgnoreSignalRTelemetryProcessor>();

            var mvcBuilder = services.AddMvc(mvcOptions =>
            {
                //Disable 204 response for null result. https://github.com/aspnet/AspNetCore/issues/8847
                var noContentFormatter = mvcOptions.OutputFormatters.OfType <HttpNoContentOutputFormatter>().FirstOrDefault();
                if (noContentFormatter != null)
                {
                    noContentFormatter.TreatNullValueAsNoContent = false;
                }
            }
                                             )
                             .AddNewtonsoftJson(options =>
            {
                //Next line needs to represent custom derived types in the resulting swagger doc definitions. Because default SwaggerProvider used global JSON serialization settings
                //we should register this converter globally.
                options.SerializerSettings.ContractResolver = new PolymorphJsonContractResolver();
                //Next line allow to use polymorph types as parameters in API controller methods
                options.SerializerSettings.Converters.Add(new StringEnumConverter());
                options.SerializerSettings.Converters.Add(new PolymorphJsonConverter());
                options.SerializerSettings.Converters.Add(new ModuleIdentityJsonConverter());
                options.SerializerSettings.PreserveReferencesHandling = PreserveReferencesHandling.None;
                options.SerializerSettings.ReferenceLoopHandling      = ReferenceLoopHandling.Ignore;
                options.SerializerSettings.DateTimeZoneHandling       = DateTimeZoneHandling.Utc;
                options.SerializerSettings.NullValueHandling          = NullValueHandling.Ignore;
                options.SerializerSettings.Formatting = Formatting.None;
            }
                                                );

            services.AddSingleton(js =>
            {
                var serv = js.GetService <IOptions <MvcNewtonsoftJsonOptions> >();
                return(JsonSerializer.Create(serv.Value.SerializerSettings));
            });

            services.AddDbContext <SecurityDbContext>(options =>
            {
                options.UseSqlServer(Configuration.GetConnectionString("VirtoCommerce"));
                // Register the entity sets needed by OpenIddict.
                // Note: use the generic overload if you need
                // to replace the default OpenIddict entities.
                options.UseOpenIddict();
            });

            // Enable synchronous IO if using Kestrel:
            services.Configure <KestrelServerOptions>(options =>
            {
                options.AllowSynchronousIO = true;
            });

            // Enable synchronous IO if using IIS:
            services.Configure <IISServerOptions>(options =>
            {
                options.AllowSynchronousIO = true;
            });

            services.Configure <CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded    = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });

            var authBuilder = services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
                              //Add the second ApiKey auth schema to handle api_key in query string
                              .AddScheme <ApiKeyAuthenticationOptions, ApiKeyAuthenticationHandler>(ApiKeyAuthenticationOptions.DefaultScheme, options => { })
                              .AddCookie();

            services.AddSecurityServices(options =>
            {
            });

            services.AddIdentity <ApplicationUser, Role>(options => options.Stores.MaxLengthForKeys = 128)
            .AddEntityFrameworkStores <SecurityDbContext>()
            .AddDefaultTokenProviders();

            // Configure Identity to use the same JWT claims as OpenIddict instead
            // of the legacy WS-Federation claims it uses by default (ClaimTypes),
            // which saves you from doing the mapping in your authorization controller.
            services.Configure <IdentityOptions>(options =>
            {
                options.ClaimsIdentity.UserNameClaimType = OpenIdConnectConstants.Claims.Subject;
                options.ClaimsIdentity.UserIdClaimType   = OpenIdConnectConstants.Claims.Name;
                options.ClaimsIdentity.RoleClaimType     = OpenIdConnectConstants.Claims.Role;
            });

            // Support commonly used forwarded headers
            // X-Forwarded-For - Holds Client IP (optionally port number) across proxies and ends up in HttpContext.Connection.RemoteIpAddress
            // X-Forwarded-Proto - Holds original scheme (HTTP or HTTPS) even if call traversed proxies and changed and ends up in HttpContext.Request.Scheme
            services.Configure <ForwardedHeadersOptions>(options =>
            {
                options.KnownProxies.Clear();
                options.ForwardedHeaders = Microsoft.AspNetCore.HttpOverrides.ForwardedHeaders.XForwardedProto | Microsoft.AspNetCore.HttpOverrides.ForwardedHeaders.XForwardedFor;
            });

            //Create backup of token handler before default claim maps are cleared
            var defaultTokenHandler = new JwtSecurityTokenHandler();

            JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();
            JwtSecurityTokenHandler.DefaultOutboundClaimTypeMap.Clear();
            authBuilder.AddJwtBearer(options =>
            {
                options.Authority = Configuration["Auth:Authority"];
                options.Audience  = Configuration["Auth:Audience"];

                if (WebHostEnvironment.IsDevelopment())
                {
                    options.RequireHttpsMetadata = false;
                }

                options.IncludeErrorDetails = true;

                X509SecurityKey publicKey = null;
                if (!Configuration["Auth:PublicCertPath"].IsNullOrEmpty())
                {
                    var publicCert = new X509Certificate2(Configuration["Auth:PublicCertPath"]);
                    publicKey      = new X509SecurityKey(publicCert);
                }

                options.TokenValidationParameters = new TokenValidationParameters()
                {
                    NameClaimType            = OpenIdConnectConstants.Claims.Subject,
                    RoleClaimType            = OpenIdConnectConstants.Claims.Role,
                    ValidateIssuer           = !string.IsNullOrEmpty(options.Authority),
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey         = publicKey
                };
            });

            var azureAdSection = Configuration.GetSection("AzureAd");

            if (azureAdSection.GetChildren().Any())
            {
                var options = new AzureAdOptions();
                azureAdSection.Bind(options);

                if (options.Enabled)
                {
                    //TODO: Need to check how this influence to OpennIddict Reference tokens activated by this line below  AddValidation(options => options.UseReferenceTokens());
                    authBuilder.AddOpenIdConnect(options.AuthenticationType, options.AuthenticationCaption,
                                                 openIdConnectOptions =>
                    {
                        openIdConnectOptions.ClientId               = options.ApplicationId;
                        openIdConnectOptions.Authority              = $"{options.AzureAdInstance}{options.TenantId}";
                        openIdConnectOptions.UseTokenLifetime       = true;
                        openIdConnectOptions.RequireHttpsMetadata   = false;
                        openIdConnectOptions.SignInScheme           = IdentityConstants.ExternalScheme;
                        openIdConnectOptions.SecurityTokenValidator = defaultTokenHandler;
                    });
                }
            }

            services.AddOptions <Core.Security.AuthorizationOptions>().Bind(Configuration.GetSection("Authorization")).ValidateDataAnnotations();
            var authorizationOptions = Configuration.GetSection("Authorization").Get <Core.Security.AuthorizationOptions>();
            var platformOptions      = Configuration.GetSection("VirtoCommerce").Get <PlatformOptions>();

            // Register the OpenIddict services.
            // Note: use the generic overload if you need
            // to replace the default OpenIddict entities.
            services.AddOpenIddict()
            .AddCore(options =>
            {
                options.UseEntityFrameworkCore()
                .UseDbContext <SecurityDbContext>();
            }).AddServer(options =>
            {
                // Register the ASP.NET Core MVC binder used by OpenIddict.
                // Note: if you don't call this method, you won't be able to
                // bind OpenIdConnectRequest or OpenIdConnectResponse parameters.
                options.UseMvc();

                // Enable the authorization, logout, token and userinfo endpoints.
                options.EnableTokenEndpoint("/connect/token")
                .EnableUserinfoEndpoint("/api/security/userinfo");

                // Note: the Mvc.Client sample only uses the code flow and the password flow, but you
                // can enable the other flows if you need to support implicit or client credentials.
                options.AllowPasswordFlow()
                .AllowRefreshTokenFlow()
                .AllowClientCredentialsFlow();

                options.SetRefreshTokenLifetime(authorizationOptions?.RefreshTokenLifeTime);
                options.SetAccessTokenLifetime(authorizationOptions?.AccessTokenLifeTime);

                options.AcceptAnonymousClients();

                // Configure Openiddict to issues new refresh token for each token refresh request.
                options.UseRollingTokens();

                // Make the "client_id" parameter mandatory when sending a token request.
                //options.RequireClientIdentification();

                // When request caching is enabled, authorization and logout requests
                // are stored in the distributed cache by OpenIddict and the user agent
                // is redirected to the same page with a single parameter (request_id).
                // This allows flowing large OpenID Connect requests even when using
                // an external authentication provider like Google, Facebook or Twitter.
                options.EnableRequestCaching();

                options.DisableScopeValidation();

                // During development or when you explicitly run the platform in production mode without https, need to disable the HTTPS requirement.
                if (WebHostEnvironment.IsDevelopment() || platformOptions.AllowInsecureHttp || !Configuration.IsHttpsServerUrlSet())
                {
                    options.DisableHttpsRequirement();
                }

                // Note: to use JWT access tokens instead of the default
                // encrypted format, the following lines are required:
                options.UseJsonWebTokens();

                var bytes = File.ReadAllBytes(Configuration["Auth:PrivateKeyPath"]);
                X509Certificate2 privateKey;
                if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
                {
                    // https://github.com/dotnet/corefx/blob/release/2.2/Documentation/architecture/cross-platform-cryptography.md
                    // macOS cannot load certificate private keys without a keychain object, which requires writing to disk. Keychains are created automatically for PFX loading, and are deleted when no longer in use. Since the X509KeyStorageFlags.EphemeralKeySet option means that the private key should not be written to disk, asserting that flag on macOS results in a PlatformNotSupportedException.
                    privateKey = new X509Certificate2(bytes, Configuration["Auth:PrivateKeyPassword"], X509KeyStorageFlags.MachineKeySet);
                }
                else
                {
                    privateKey = new X509Certificate2(bytes, Configuration["Auth:PrivateKeyPassword"], X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.EphemeralKeySet);
                }
                options.AddSigningCertificate(privateKey);
            });

            services.Configure <IdentityOptions>(Configuration.GetSection("IdentityOptions"));

            //always  return 401 instead of 302 for unauthorized  requests
            services.ConfigureApplicationCookie(options =>
            {
                options.Events.OnRedirectToLogin = context =>
                {
                    context.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
                    return(Task.CompletedTask);
                };
                options.Events.OnRedirectToAccessDenied = context =>
                {
                    context.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
                    return(Task.CompletedTask);
                };
            });

            services.AddAuthorization(options =>
            {
                //We need this policy because it is a single way to implicitly use the two schema (JwtBearer and ApiKey)  authentication for resource based authorization.
                var mutipleSchemaAuthPolicy = new AuthorizationPolicyBuilder().AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme, ApiKeyAuthenticationOptions.DefaultScheme)
                                              .RequireAuthenticatedUser()
                                              .Build();
                //The good article is described the meaning DefaultPolicy and FallbackPolicy
                //https://scottsauber.com/2020/01/20/globally-require-authenticated-users-by-default-using-fallback-policies-in-asp-net-core/
                options.DefaultPolicy = mutipleSchemaAuthPolicy;
            });
            // register the AuthorizationPolicyProvider which dynamically registers authorization policies for each permission defined in module manifest
            services.AddSingleton <IAuthorizationPolicyProvider, PermissionAuthorizationPolicyProvider>();
            //Platform authorization handler for policies based on permissions
            services.AddSingleton <IAuthorizationHandler, DefaultPermissionAuthorizationHandler>();
            // Default password validation service implementation
            services.AddScoped <IPasswordCheckService, PasswordCheckService>();

            services.AddOptions <LocalStorageModuleCatalogOptions>().Bind(Configuration.GetSection("VirtoCommerce"))
            .PostConfigure(options =>
            {
                options.DiscoveryPath = Path.GetFullPath(options.DiscoveryPath ?? "modules");
            })
            .ValidateDataAnnotations();
            services.AddModules(mvcBuilder);

            services.AddOptions <ExternalModuleCatalogOptions>().Bind(Configuration.GetSection("ExternalModules")).ValidateDataAnnotations();
            services.AddExternalModules();

            //Assets
            var assetsProvider = Configuration.GetSection("Assets:Provider").Value;

            if (assetsProvider.EqualsInvariant(AzureBlobProvider.ProviderName))
            {
                services.AddOptions <AzureBlobOptions>().Bind(Configuration.GetSection("Assets:AzureBlobStorage")).ValidateDataAnnotations();
                services.AddAzureBlobProvider();
            }
            else
            {
                services.AddOptions <FileSystemBlobOptions>().Bind(Configuration.GetSection("Assets:FileSystem"))
                .PostConfigure(options =>
                {
                    options.RootPath = WebHostEnvironment.MapPath(options.RootPath);
                }).ValidateDataAnnotations();

                services.AddFileSystemBlobProvider();
            }

            //HangFire
            services.AddHangfire(Configuration);

            // Register the Swagger generator
            services.AddSwagger();
        }
Exemplo n.º 27
0
 public JsonContentDeserializer(JsonSerializerSettings settings = null)
 {
     _settings   = settings;
     _serializer = JsonSerializer.Create(_settings);
 }
Exemplo n.º 28
0
 private static JsonSerializer _createJsonSerializer(JsonSerializerSettings jsonSerializerSettings)
 {
     return(jsonSerializerSettings == null?JsonSerializer.CreateDefault() : JsonSerializer.Create(jsonSerializerSettings));
 }
Exemplo n.º 29
0
        public static CommandResponse PostCommandRequest(CommandRequest request, string url = "http://localhost:8033/command")
        {
            bool isRetry = false;

            //Ok!
retry:
            try
            {
                {
                    HttpClient client = new HttpClient();
                    client.Timeout = TimeSpan.FromSeconds(15);
                    StringWriter wr = new StringWriter();
                    JsonSerializer.Create().Serialize(wr, request);
                    HttpContent content = new StringContent(wr.ToString());
                    content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json");

                    var    task       = client.PostAsync(url, content).GetAwaiter().GetResult();
                    string jsonResult = task.Content.ReadAsStringAsync().GetAwaiter().GetResult();
                    #if DEBUG
                    Console.WriteLine("---");
                    Console.WriteLine(jsonResult);
                    Console.WriteLine("---");
                    #endif
                    return(JsonConvert.DeserializeObject <CommandResponse>(jsonResult, new JsonSerializerSettings()
                    {
                        StringEscapeHandling = StringEscapeHandling.EscapeNonAscii,
                        Formatting = Formatting.None
                    }));
                }
                isRetry = false;
            }
            catch (HttpRequestException httpRequestException)
            {
                if (httpRequestException.Message.Contains("target machine actively refused"))
                {
                }
                else if (httpRequestException.Message.Contains("An error occurred while sending the request"))
                {
                    Console.WriteLine("Failed to send request to " + url);
                    //Damn it.
                    if (!isRetry)
                    {
                        isRetry = true;
                        goto retry;
                    }
                    else
                    {
                        isRetry = false;
                    }
                }
                else if (httpRequestException.Message.Contains("established connection was aborted by the software in your host machine"))
                {
                    //Damn it.
                    if (!isRetry)
                    {
                        isRetry = true;
                        goto retry;
                    }
                    else
                    {
                        isRetry = false;
                    }
                }
                else
                {
                    Console.WriteLine(httpRequestException);
                }
            }
            catch (Exception exception)
            {
                Console.WriteLine(exception);
            }
            return(CommandResponse.Failed());
        }
 public JsonNetSerializer(JsonSerializerSettings settings)
 {
     ContentType = "application/json";
     _serializer = JsonSerializer.Create(settings);
 }
Exemplo n.º 31
0
 public Serializer()
 {
     this.serializer = JsonSerializer.Create(Serialization.GetSettings());
 }