Exemplo n.º 1
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            // The following line enables Application Insights telemetry collection.
            services.AddApplicationInsightsTelemetry();

            services.AddControllers();

            // Register Api
            services.AddScoped <IAuthService, AuthService>();
            services.AddScoped <IOidcService, OidcService>();
            services.AddScoped <IJwtGenerator, JwtGenerator>();
            services.AddScoped <IJwtValidator, JwtValidator>();
            services.AddScoped <IJwtDecoder, JwtDecoder>();

            // Register Infrastructure
            InfrastructureRegister.RegisterDbContext(services, Configuration.GetConnectionString("DefaultConnection"));
            InfrastructureRegister.RegisterRepository(services);

            // Register Core
            CoreRegister.RegisterServices(services);

            // Register Identity & Authentication
            services.AddIdentity <User, Role>()
            .AddEntityFrameworkStores <ApplicationDbContext>()
            .AddDefaultTokenProviders();

            services
            .AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultScheme             = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
            })
            .AddJwtBearer(cfg =>
            {
                cfg.TokenValidationParameters = 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"])),
                    ClockSkew        = TimeSpan.Zero // remove delay of token when expire
                };
            });

            // Register the Swagger generator, defining 1 or more Swagger documents
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo {
                    Title = "API", Version = "v1"
                });
            });
        }