public void ConfigureServices(IServiceCollection services) { SapphireDatabaseOptions options = new SapphireDatabaseOptions(Configuration.GetSection("Sapphire")); bool usePostgres = Configuration.GetValue <bool>("UsePostgres"); //Register services services.AddSapphireDb(options) .AddContext <RealtimeContext>(cfg => cfg.UseInMemoryDatabase(databaseName: "realtime")) .AddContext <DemoContext>(cfg => { if (usePostgres) { cfg.UseNpgsql("User ID=realtime;Password=pw1234;Host=localhost;Port=5432;Database=realtime;"); } else { cfg.UseInMemoryDatabase("demoCtx"); } }, "demo") .AddContext <AuthDemoContext>(cfg => cfg.UseInMemoryDatabase("authDemo"), "authDemo") .AddActionHandlerConfiguration <UserActionsConfiguration>() .AddModelConfiguration <MessageConfiguration>() .AddMessageFilter("role", (i, parameters) => i.User.IsInRole((string)parameters[0])); // .AddRedisSync(); // .AddHttpSync(); // services.AddMvc(); /* Auth Demo */ services.AddDbContext <IdentityDbContext <AppUser> >(cfg => cfg.UseFileContextDatabase(databaseName: "auth")); services.AddIdentity <AppUser, IdentityRole>(options => { options.Password.RequireDigit = false; options.Password.RequiredLength = 2; options.Password.RequiredUniqueChars = 0; options.Password.RequireLowercase = false; options.Password.RequireNonAlphanumeric = false; options.Password.RequireUppercase = false; }).AddEntityFrameworkStores <IdentityDbContext <AppUser> >(); JwtOptions jwtOptions = new JwtOptions(Configuration.GetSection(nameof(JwtOptions))); services.AddSingleton(jwtOptions); services.AddTransient <JwtIssuer>(); services.AddAuthentication(cfg => { cfg.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; cfg.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; }).AddJwtBearer(cfg => { cfg.TokenValidationParameters = jwtOptions.TokenValidationParameters; cfg.Events = new JwtBearerEvents() { OnAuthenticationFailed = ctx => { ctx.Response.StatusCode = StatusCodes.Status401Unauthorized; return(Task.CompletedTask); }, OnMessageReceived = ctx => { string authorizationToken = ctx.Request.Query["authorization"]; if (!string.IsNullOrEmpty(authorizationToken)) { ctx.Token = authorizationToken; } return(Task.CompletedTask); } }; }); services.AddAuthorization(config => { config.AddPolicy("requireAdmin", b => b.RequireRole("admin")); config.AddPolicy("requireUser", b => b.RequireRole("user")); }); services.AddTransient <Seeder>(); services.AddCors(); }
public JwtIssuer(JwtOptions jwtOptions, UserManager <AppUser> userManager) { this.jwtOptions = jwtOptions; this.userManager = userManager; }