public bool WriteLog(LogLevels logLevels, string message, string correlation, Dictionary <string, object> exceptionParams = null)
 {
     try
     {
         LogEngine.SendLog(logLevels, correlation, message, false, exceptionParams);
     }
     catch //error on logengine must be not send application in error
     {
         return(false);
     }
     return(true);
 }
        public async Task Invoke(HttpContext context)
        {
            PerformanceCounter performance = null;

            try
            {
                performance = new PerformanceCounter(context.Request.Path);
                context.Request.EnableBuffering();

                // Leave the body open so the _next middleware can read it.
                using (var reader = new StreamReader(context.Request.Body, Encoding.UTF8, false, 1024, true))
                {
                    // Leggo il body
                    body = await reader.ReadToEndAsync();

                    // Reset the request body stream position so the _next middleware can read it
                    context.Request.Body.Position = 0;
                }

                await next(context);
            }
            catch (Exception ex)
            {
                var correlation = context.GetCorrelation();

                var exceptionParams = new Dictionary <string, object>
                {
                    //{"Request uri", new Uri(new Uri(context.Request.Host.ToUriComponent()), context.Request.Path)},
                    { "Request uri", new Uri(context.Request.GetDisplayUrl()) },
                    { "Request method", context.Request.Method },
                    { "Request headers", context.Request.Headers },
                    { "Request body", body }
                };

                // Log exception e request
                LogEngine.SendLog(LogLevels.ERROR, correlation, ex.ToString(), false, exceptionParams);

                // Ritorno un messaggio di risposta standard con i dettagli dell'errore.
                await HandleExceptionAsync(context, ex);
            }
            finally
            {
                performance?.Stop();
            }
        }
Esempio n. 3
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            // LogEngine configuration and registration
            LogEngine.Setup(Configuration["LogEngine:Appid"], AppDomain.CurrentDomain);

            LogEngine.SendLog(LogLevels.DEBUG, "START!", null);

            services.AddSingleton <ILogEngineService, LogEngineService>();

            services.AddControllers()
            .ConfigureApiBehaviorOptions(c =>
                                         c.SuppressModelStateInvalidFilter = true) // to explicit management model.isvalid
            .AddNewtonsoftJson(
                options =>
            {
                //options.SerializerSettings.ContractResolver = new DefaultContractResolver(); //enable pascal case
                options.SerializerSettings.NullValueHandling = NullValueHandling.Ignore;
                options.SerializerSettings.Formatting        = Formatting.Indented;
            })
            .AddJsonOptions(opt => opt.JsonSerializerOptions.PropertyNamingPolicy = null)
            .AddDataAnnotationsLocalization       // model data annotation/validation using localization resources
            (
                options =>
            {
                options.DataAnnotationLocalizerProvider = (type, factory) => factory.Create(typeof(Resources));
            }
            );

            services.AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
            }).AddJwtBearer(o =>
            {
                o.TokenValidationParameters = new TokenValidationParameters
                {
                    ClockSkew                = TimeSpan.Zero,
                    RequireAudience          = true,
                    RequireExpirationTime    = true,
                    RequireSignedTokens      = true,
                    ValidIssuer              = Configuration["Oauth:Authority"],
                    ValidAudience            = Configuration["Oauth:Audience"],
                    ValidateAudience         = true,
                    ValidateIssuer           = true,
                    ValidateLifetime         = true,
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKeyResolver = (token, secureToken, kid, _) =>
                    {
                        var issuerDiscoveryEndpoint = new Uri(Configuration["Oauth:DiscoveryEndpoint"]);
                        var publicKeys = RedHatSSO.GetIssuerPublicKeys(issuerDiscoveryEndpoint, (JwtSecurityToken)secureToken);
                        return(publicKeys);
                    }
                };
                o.Events = new JwtBearerEvents()
                {
                    OnTokenValidated       = tv => Task.Run(() => Console.WriteLine(tv.SecurityToken.ToString())),
                    OnAuthenticationFailed = c =>
                    {
                        c.NoResult();
                        c.Response.StatusCode  = (int)HttpStatusCode.Forbidden;
                        c.Response.ContentType = "application/json";

                        return(c.Response.WriteAsync(JsonConvert.SerializeObject(new BaseResponse
                        {
                            Error = new Error()
                            {
                                ErrorCode = (int)HttpStatusCode.Forbidden,
                                ErrorMessage = c.Exception.ToString()
                            },
                            RequestStatus = RequestStatus.KO.ToString()
                        }
                                                                                 )));
                    },
                    OnForbidden = c =>
                    {
                        c.NoResult();
                        c.Response.StatusCode  = (int)HttpStatusCode.Forbidden;
                        c.Response.ContentType = "application/json";

                        return(c.Response.WriteAsync(JsonConvert.SerializeObject(new BaseResponse
                        {
                            Error = new Error()
                            {
                                ErrorCode = (int)HttpStatusCode.Forbidden,
                                ErrorMessage = HttpStatusCode.Forbidden.ToString()
                            },
                            RequestStatus = RequestStatus.KO.ToString()
                        }
                                                                                 )));
                    }
                };
            });

            services.AddAuthorization(options =>
            {
                options.AddPolicy("HasValidAudience", policy => policy.Requirements.Add(new HasScopeRequirement(Configuration["Oauth:Audience"])));
                options.AddPolicy("CanCreate", policy => policy.Requirements.Add(new HasScopeRequirement("create")));
                options.AddPolicy("CanUpdate", policy => policy.Requirements.Add(new HasScopeRequirement("update")));
                options.AddPolicy("CanRead", policy => policy.Requirements.Add(new HasScopeRequirement("read")));
                options.AddPolicy("CanDelete", policy => policy.Requirements.Add(new HasScopeRequirement("delete")));
            });

            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo
                {
                    Title       = "EA.NCOx.Net5Template",
                    Version     = "v1",
                    Description = "<b>Template .NET 5 for Web API</b>"
                });

                // Set the comments path for the Swagger JSON and UI.
                var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
                var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
                c.IncludeXmlComments(xmlPath);

                c.DocumentFilter <SwaggerAddEnumDescriptions>(); //enums custom management

                c.OperationFilter <CustomOperationFilter>();

                c.AddSecurityDefinition("JWT-Auth", new OpenApiSecurityScheme()
                {
                    Description  = "JWT Authorization header using the Bearer scheme",
                    Type         = SecuritySchemeType.Http,
                    In           = ParameterLocation.Header,
                    Name         = "Authorization",
                    BearerFormat = "JWT",
                    Scheme       = "bearer"
                });

                c.AddSecurityRequirement(new OpenApiSecurityRequirement
                {
                    {
                        new OpenApiSecurityScheme
                        {
                            Reference = new OpenApiReference {
                                Type = ReferenceType.SecurityScheme, Id = "JWT-Auth"
                            }
                        },
                        new string[] {}
                    }
                });
            });

            services.AddLocalization(o =>
            {
                // Mettiamo le risorse nella cartella Resources in un assembly separato
                o.ResourcesPath = "Resources";
            });

            // Validators
            services.AddValidators();

            // EntityFramework NCOx DbContext
            services.AddNCOxDbContext(Configuration);

            // EntityFramework NCOx DbContext
            services.AddNCO2DbContext(Configuration);

            // MongoDb Client
            services.AddSingleton <IMongoClient>(_ =>
                                                 new MongoClient(Configuration.GetSection("MONGODB_CONNECTION_STRING").Value));

            services.AddHttpContextAccessor();
            services.AddHttpClient();
            services.AddAutoMapper();

            services.AddBusinessServices(Configuration);

            //authorization
            services.AddSingleton <IAuthorizationHandler, HasScopeHandler>();
            services.AddSingleton <IAuthorizationHandler, HasCustomClaimHandler>();

            Configuration["AssemblyVersion"] = typeof(Startup)?.Assembly?.GetName()?.Version?.NullableToString();
        }