Ejemplo n.º 1
0
        public UsuariosControllerTest()
        {
            _services = new ServiceCollection();
            _services.AddDbContext <ApplicationDbContext>();
            InjecaoDependencias.Configure(_services);
            _serviceProvider = _services.BuildServiceProvider();
            var usuarioService = (IUsuarioService)_serviceProvider.GetService(typeof(IUsuarioService));

            _controller = new UsuariosController(usuarioService);
        }
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddCors(options => options.AddDefaultPolicy(policy => policy.AllowAnyOrigin()));

            services.Configure <IISServerOptions>(options =>
            {
                options.AutomaticAuthentication = false;
            });

            services.AddApplicationInsightsTelemetry();

            services.AddControllers();

            services.AddSwaggerGen(options =>
            {
                options.SwaggerDoc("v1", new OpenApiInfo {
                    Title = "Quality Management API", Version = "v1"
                });
                options.CustomOperationIds(e => $"{string.Join("", e.ActionDescriptor.RouteValues.Values)}");
            });

            services.AddMvc();

            services.AddResponseCompression(options =>
            {
                options.MimeTypes = new[] {
                    "text/html",
                    "text/css",
                    "application/javascript",
                    "text/javascript",
                    "application/json"
                };
                options.EnableForHttps = true;
            });

            InjecaoDependencias.Configurar(services);

            services.AddApiVersioning(o =>
            {
                o.ReportApiVersions = true;
                o.AssumeDefaultVersionWhenUnspecified = true;
                o.DefaultApiVersion = new ApiVersion(1, 0);
            });
        }
Ejemplo n.º 3
0
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext <ApplicationDbContext>();

            InjecaoDependencias.Configure(services);

            var signingConfigurations = new SigningConfigurations();

            services.AddSingleton(signingConfigurations);

            var tokenConfigurations = new TokenConfigurations();

            new ConfigureFromConfigurationOptions <TokenConfigurations>(
                Configuration.GetSection("TokenConfigurations"))
            .Configure(tokenConfigurations);
            services.AddSingleton(tokenConfigurations);


            services.AddAuthentication(authOptions =>
            {
                authOptions.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                authOptions.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
            }).AddJwtBearer(bearerOptions =>
            {
                var paramsValidation = bearerOptions.TokenValidationParameters;
                paramsValidation.IssuerSigningKey = signingConfigurations.Key;
                paramsValidation.ValidAudience    = tokenConfigurations.Audience;
                paramsValidation.ValidIssuer      = tokenConfigurations.Issuer;

                // Valida a assinatura de um token recebido
                paramsValidation.ValidateIssuerSigningKey = true;

                // Verifica se um token recebido ainda é válido
                paramsValidation.ValidateLifetime = true;

                // Tempo de tolerância para a expiração de um token (utilizado
                // caso haja problemas de sincronismo de horário entre diferentes
                // computadores envolvidos no processo de comunicação)
                paramsValidation.ClockSkew = TimeSpan.Zero;
            });

            // Ativa o uso do token como forma de autorizar o acesso
            // a recursos deste projeto
            services.AddAuthorization(auth =>
            {
                auth.AddPolicy("Bearer", new AuthorizationPolicyBuilder()
                               .AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme‌​)
                               .RequireAuthenticatedUser().Build());
            });

            services.AddMvc();

            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new Info
                {
                    Version        = "v1",
                    Title          = "Juntos API Usuários",
                    Description    = "",
                    TermsOfService = "None",
                    Contact        = new Contact()
                    {
                        Name = "Full-stack Developer .Net & Angular", Email = "*****@*****.**", Url = ""
                    }
                });
                c.AddSecurityDefinition("Bearer",
                                        new ApiKeyScheme
                {
                    In          = "header",
                    Description = "Please enter into field the word 'Bearer' following by space and JWT",
                    Name        = "Authorization",
                    Type        = "apiKey"
                });
                c.AddSecurityRequirement(new Dictionary <string, IEnumerable <string> > {
                    { "Bearer", Enumerable.Empty <string>() },
                });
            });
        }