Ejemplo n.º 1
0
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            app.UseStaticFiles();
            SecurityToken outToken = null;

            Log.Information("Startup::Configure");

            app.UseExceptionHandler(appBuilder =>
            {
                app.Use(async(context, next) =>
                {
                    //If request == /api/*
                    if (context.Request.Path.Value.Split('/')[1] == "api" && context.Request.Path.Value.Split('/')[2] == "info" || context.Request.Path.Value.Split('/')[2] == "token" ||
                        context.Request.Path.Value.Split('/')[1] == "swagger")
                    {
                        await next();
                    }
                    else
                    {
                        var bearer = context.Request.Headers.Where(x => x.Key == "Authorization").ToList();
                        if (bearer.Count > 0)
                        {
                            var headerToken = new JwtSecurityTokenHandler().ValidateToken(
                                bearer.First().Value.ToString().Replace("Bearer ", ""),
                                new TokenValidationParameters
                            {
                                ValidateIssuer           = true,
                                ValidateAudience         = true,
                                ValidateLifetime         = true,
                                ValidateIssuerSigningKey = true,
                                ValidIssuer      = Configuration["Jwt:Issuer"],
                                ValidAudience    = Configuration["Jwt:Issuer"],
                                IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Jwt:Key"]))
                            }, out outToken);
                            if (headerToken.IsInRole("Administrator"))
                            {
                                await next();
                            }
                            else
                            {
                                context.Response.StatusCode  = 401;
                                context.Response.ContentType = "application/json";

                                _ = context.Response.WriteAsync(JsonConvert.SerializeObject(new MessageHelpers <ConnectionInfo>
                                {
                                    Status = 401,
                                    Data   = null
                                }));
                            }
                        }
                        else
                        {
                            context.Response.StatusCode  = 401;
                            context.Response.ContentType = "application/json";

                            _ = context.Response.WriteAsync(JsonConvert.SerializeObject(new MessageHelpers <ConnectionInfo>
                            {
                                Status = 401,
                                Data   = null
                            }));
                        }
                    }
                    var error = context.Features[typeof(IExceptionHandlerFeature)] as IExceptionHandlerFeature;

                    //when authorization has failed, should retrun a json message to client
                    if (error != null && error.Error is SecurityTokenExpiredException)
                    {
                        context.Response.StatusCode  = 401;
                        context.Response.ContentType = "application/json";

                        _ = context.Response.WriteAsync(JsonConvert.SerializeObject(new MessageHelpers <ConnectionInfo>
                        {
                            Status = 401,
                            Data   = null
                        }));
                    }
                    //when orther error, retrun a error message json to client
                    else if (error != null && error.Error != null)
                    {
                        context.Response.StatusCode  = 500;
                        context.Response.ContentType = "application/json";
                        _ = context.Response.WriteAsync(JsonConvert.SerializeObject(new MessageHelpers <ConnectionInfo>
                        {
                            Status = 500,
                            Data   = null
                        }));
                    }
                    //when no error, do next.
                    else
                    {
                        await next();
                    }
                });
            });


            try
            {
                if (env.EnvironmentName == "Development")
                {
                    app.UseDeveloperExceptionPage();
                }
                else
                {
                    app.UseMiddleware <ExceptionHandler>();
                }

                app.UseCors("CorsPolicy-public"); //apply to every request
                app.UseAuthentication();          //needs to be up in the pipeline, before MVC
                app.UseAuthorization();

                app.UseMvc();

                //Swagger API documentation
                app.UseSwagger();


                app.UseSwaggerUI(c =>
                {
                    c.SwaggerEndpoint("/swagger/v1/swagger.json", "ApiNCoreEApplication1 API V1");
                    c.SwaggerEndpoint("/swagger/v2/swagger.json", "ApiNCoreEApplication1 API V2");
                    c.DisplayOperationId();
                    c.DisplayRequestDuration();
                    //c.InjectStylesheet(SwaggerUIPath, SwaggerUIStyleSheet);
                    c.InjectStylesheet("/Assets/CustomUI.css");
                });

                //migrations and seeds from json files
                using (var serviceScope = app.ApplicationServices.GetRequiredService <IServiceScopeFactory>().CreateScope())
                {
                    if (Configuration["ConnectionStrings:UseInMemoryDatabase"] == "False" && !serviceScope.ServiceProvider.GetService <ApiNCoreEApplication1Context>().AllMigrationsApplied())
                    {
                        if (Configuration["ConnectionStrings:UseMigrationService"] == "True")
                        {
                            serviceScope.ServiceProvider.GetService <ApiNCoreEApplication1Context>().Database.Migrate();
                        }
                    }
                    //it will seed tables on aservice run from json files if tables empty
                    if (Configuration["ConnectionStrings:UseSeedService"] == "True")
                    {
                        serviceScope.ServiceProvider.GetService <ApiNCoreEApplication1Context>().EnsureSeeded();
                    }
                }
            }
            catch (Exception ex)
            {
                Log.Error(ex.Message);
            }
        }