hemtros
10/16/2019 - 10:36 PM

API Startup.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using CAT.Security.Common.AppConfig;
using CAT.Security.BLL;
using CAT.Security.CompositionRoot;
using AutoMapper;
using CAT.Security.API.ViewModels;
using CAT.Security.Common.DTOs;
using Microsoft.AspNetCore.Mvc.Versioning;
using System.Reflection;
using System.IO;
using System.Text;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
using CAT.Security.API.Extensions;
using CAT.Security.Common.Options;
using Microsoft.AspNetCore.Server.IIS;
using Microsoft.AspNetCore.Http;
using System.Security.Principal;
using System.Security.Claims;

namespace CAT.Security.API
{
    public class Startup
    {
        private string _securityCorsPolicy = "CorsPolicy";
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
            _dependencyMapper = new DependencyMapper();
        }

        public IConfiguration Configuration { get; }

        private IDependencyMapper _dependencyMapper;

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddCors(options =>
            {
                options.AddPolicy(_securityCorsPolicy,
                builder =>
                {
                    builder.AllowAnyOrigin()
                           .AllowAnyMethod()
                           .AllowAnyHeader();
                });
            });

            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2)
                            .AddJsonOptions(options =>
                            {
                                options.SerializerSettings.NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore;
                            });

            services.AddApiVersioning(a =>
            {
                a.ApiVersionReader = new HeaderApiVersionReader("api-version");
                a.AssumeDefaultVersionWhenUnspecified = true;
            });

            var securitySection = Configuration.GetSection("Security");
            services.Configure<AppSecuritySettings>(securitySection);

            var key = Encoding.ASCII.GetBytes(securitySection.Get<AppSecuritySettings>()?.TokenSecret);

            services.AddAuthentication(x =>
            {
                x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
            })
            .AddJwtBearer(x =>
            {
                x.RequireHttpsMetadata = false;
                x.SaveToken = true;
                x.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey = new SymmetricSecurityKey(key),
                    ValidateIssuer = false,
                    ValidateAudience = false,
                    ClockSkew = TimeSpan.Zero
                };
                x.Events = new JwtBearerEvents
                {
                    OnAuthenticationFailed = context =>
                    {
                        var exType = context.Exception.GetType();
                        if (exType == typeof(SecurityTokenExpiredException))
                        {
                            context.Response.Headers.Add("X-Token-Status", "expired");
                        }
                        else if(exType == typeof(SecurityTokenInvalidSignatureException))
                        {
                            context.Response.Headers.Add("X-Token-Status", "invalid-signature");
                        }
                        return Task.CompletedTask;
                    }
                };
            });

            //services.AddAuthentication(IISServerDefaults.AuthenticationScheme);
            //use this if we want to add policies
            //services.AddAuthorization();

            InitializeAppDependencies(services);
            services.AddAutoMapper(typeof(AutoMapper.MappingProfile));

            services.AddSwaggerGen(a =>
            {
                a.SwaggerDoc(
                    "APISpecs",
                        new Microsoft.OpenApi.Models.OpenApiInfo()
                        {
                            Title = "API",
                            Version = "1"
                        });
                a.ResolveConflictingActions(apiDescriptions => apiDescriptions.First());

                
                var xmlCommentsFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
                var xmlCommentsFullPath = Path.Combine(AppContext.BaseDirectory, xmlCommentsFile);
                a.IncludeXmlComments(xmlCommentsFullPath);
                
            });
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseSwagger();


            app.UseSwaggerUI(a =>
            {
                a.SwaggerEndpoint("/myapi/swagger/CATSecurityAPISpecs/swagger.json",
                                  "My API");
                a.RoutePrefix = "docs";
            });


            app.UseCors(_securityCorsPolicy);
            app.UseCatJwtCookieAuthentication();
            app.UseAuthentication();
            app.UseMvc();
        }

        private void InitializeAppDependencies(IServiceCollection services)
        {
            _dependencyMapper.AddAppConfigurationService(services);
            _dependencyMapper.AddDataConfigurationService(services);
            _dependencyMapper.AddUserService(services);
            _dependencyMapper.AddRoleService(services);
            _dependencyMapper.AddUserRoleService(services);
            _dependencyMapper.AddAssignmentService(services);
            _dependencyMapper.AddSellingBusinessUnitService(services);
            _dependencyMapper.AddUserAssignmentService(services);
            _dependencyMapper.AddFunctionActionService(services);
            _dependencyMapper.AddPermissionService(services);
            _dependencyMapper.AddAppSecureRefreshService(services);
            _dependencyMapper.AddOrganizationService(services);
            _dependencyMapper.AddRolePermissionService(services);
            _dependencyMapper.AddTransactionLogService(services);
            _dependencyMapper.AddAssociateUserService(services);
            _dependencyMapper.AddUserAttributeService(services);
            _dependencyMapper.AddUserSettingsService(services);
            _dependencyMapper.AddBetaProgramService(services);
            _dependencyMapper.AddSecurityService(services);
            _dependencyMapper.AddUserMigrationService(services);
            _dependencyMapper.AddMarketService(services);
            _dependencyMapper.AddMarketListRegionService(services);
            _dependencyMapper.AddRegionService(services);
        }
    }
}