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)
        {
            JwtConfigSection jwtConfig = Configuration.GetSection("jwt").Get <JwtConfigSection>();

            services.AddSingleton(jwtConfig);

            services.AddDbContext <CodeChallengeDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("CodeChallengeDb")));

            services.AddScoped <ICompanyService, CompanyService>();

            services.AddAutoMapper(Assembly.GetExecutingAssembly());

            services.AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
            }).AddJwtBearer(options =>
            {
                options.TokenValidationParameters = new TokenValidationParameters()
                {
                    ValidIssuer              = jwtConfig.Issuer,
                    ValidAudience            = jwtConfig.Audience,
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey         = new SymmetricSecurityKey(Convert.FromBase64String(jwtConfig.Key)),
                };
            });

            services.AddCors();

            services.AddMvc()
            .AddMvcOptions(options =>
            {
                AuthorizationPolicy policy = new AuthorizationPolicyBuilder()
                                             .RequireAuthenticatedUser()
                                             .Build();
                options.Filters.Add(new AuthorizeFilter(policy));
            })
            .AddFluentValidation(fv => fv.RegisterValidatorsFromAssemblyContaining <CompanyForAddDtoValidator>())
            .SetCompatibilityVersion(CompatibilityVersion.Version_2_2);

            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new Info {
                    Title = "CodeChallenge API", Version = "v1"
                });
                c.AddSecurityDefinition("Bearer", new ApiKeyScheme
                {
                    Description = "JWT Authorization header using the Bearer scheme. Example: \"Authorization: Bearer {token}\". Get token from POST /Account/Login",
                    Name        = "Authorization",
                    In          = "header",
                    Type        = "apiKey"
                });
                c.OperationFilter <SecurityRequirementsOperationFilter>();
            });
        }
 public AccountController(JwtConfigSection jwtConfig)
 {
     _jwtConfig = jwtConfig;
 }