示例#1
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            // use sql server db in production and sqlite db in development
            if (_env.IsProduction())
            {
                services.AddDbContext <DataContext>();
            }
            else
            {
                services.AddDbContext <DataContext, SqliteDataContext>();
            }

            services.AddCors();
            services.AddControllers();
            services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies());
            services.AddCorrelationId();

            // configure strongly typed settings objects
            var appSettingsSection = _configuration.GetSection("AppSettings");

            services.Configure <AppSettings>(appSettingsSection);

            // configure jwt authentication
            var appSettings = appSettingsSection.Get <AppSettings>();
            var key         = Encoding.ASCII.GetBytes(appSettings.Secret);

            services.AddAuthentication(x =>
            {
                x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                x.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
            }).AddJwtBearer(x =>
            {
                x.Events = new JwtBearerEvents
                {
                    OnTokenValidated = context =>
                    {
                        var userService = context.HttpContext.RequestServices.GetRequiredService <IUserService>();
                        var userId      = int.Parse(context.Principal.Identity.Name);
                        var user        = userService.GetById(userId);
                        if (user == null)
                        {
                            // return unauthorized if user no longer exists
                            context.Fail("Unauthorized");
                        }
                        return(Task.CompletedTask);
                    },
                };
                x.RequireHttpsMetadata      = false;
                x.SaveToken                 = true;
                x.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey         = new SymmetricSecurityKey(key),
                    ValidateIssuer           = false,
                    ValidateAudience         = false
                };
            });
            services.AddSwaggerGen(
                c =>
            {
                c.SwaggerDoc(
                    "v1",
                    new OpenApiInfo
                {
                    Title   = "My API",
                    Version = "v1"
                });
                // disable bearer auth
                if (1 == 0)
                {
                    c.AddSecurityDefinition(
                        "Bearer",
                        new OpenApiSecurityScheme
                    {
                        In          = ParameterLocation.Header,
                        Description = "Please insert JWT with Bearer into field",
                        Name        = "Authorization",
                        Type        = SecuritySchemeType.ApiKey
                    });
                    c.AddSecurityRequirement(
                        new OpenApiSecurityRequirement
                    {
                        {
                            new OpenApiSecurityScheme
                            {
                                Reference = new OpenApiReference
                                {
                                    Type = ReferenceType
                                           .SecurityScheme,
                                    Id = "Bearer"
                                }
                            },
                            new string[] { }
                        }
                    });
                }
            });
            services.AddSwaggerGenNewtonsoftSupport();

            // configure DI for application services
            services.AddScoped <IUserService, UserService>();

            services.AddAuthorization(config =>
            {
                config.AddPolicy(Policies.Admin, Policies.AdminPolicy());
                config.AddPolicy(Policies.User, Policies.UserPolicy());
            });
        }