public static IServiceCollection SwaggerConfiguration(this IServiceCollection services) { services.AddSwaggerGen( options => { options.SwaggerDoc("v1", new OpenApiInfo { Title = "UniAtHome.API", Version = "v1" }); options.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme() { Name = "Authorization", Type = SecuritySchemeType.ApiKey, Scheme = "Bearer", BearerFormat = "JWT", In = ParameterLocation.Header, Description = "JWT Authorization header using the Bearer scheme." }); var securityScheme = new OpenApiSecurityScheme { Reference = new OpenApiReference { Id = "Bearer", Type = ReferenceType.SecurityScheme } }; var requirements = new OpenApiSecurityRequirement { { securityScheme, new List <string>() } }; options.AddSecurityRequirement(requirements); } ); return(services); }
public void Apply(OpenApiOperation operation, OperationFilterContext context) { var secure = context.ApiDescription.ActionDescriptor.FilterDescriptors.Any(x => x.Filter is AuthorizeFilter); if (!secure) { return; } if (operation.Security == null) { operation.Security = new List <OpenApiSecurityRequirement>(); } var oAuthRequirements = new OpenApiSecurityRequirement { { new OpenApiSecurityScheme { Type = SecuritySchemeType.OAuth2 }, new Collection <string>() } }; operation.Security.Add(oAuthRequirements); }
/// <inheritdoc /> public List <OpenApiSecurityRequirement> GetOpenApiSecurityRequirement(MethodInfo element, NamingStrategy namingStrategy = null) { var attributes = element.GetCustomAttributes <OpenApiSecurityAttribute>(inherit: false); if (!attributes.Any()) { return(new List <OpenApiSecurityRequirement>()); } var requirements = new List <OpenApiSecurityRequirement>(); foreach (var attr in attributes) { var scheme = new OpenApiSecurityScheme() { Type = attr.SchemeType, Description = attr.Description, Name = GetSecuritySchemeName(attr), In = GetSecuritySchemeLocation(attr), Scheme = GetSecuritySchemeScheme(attr, namingStrategy), BearerFormat = GetSecurityBearerFormat(attr), Flows = GetSecurityOAuthFlows(attr), OpenIdConnectUrl = GetSecurityOpenIdConnectUrl(attr), Reference = GetSecurityReference(attr), }; var value = GetSecurityOAuthScopes(attr, scheme.Flows); var requirement = new OpenApiSecurityRequirement(); requirement.Add(scheme, value); requirements.Add(requirement); } return(requirements); }
/// <summary> /// Adds a global security requirement /// </summary> /// <param name="swaggerGenOptions"></param> /// <param name="securityRequirement"> /// A dictionary of required schemes (logical AND). Keys must correspond to schemes defined through AddSecurityDefinition /// If the scheme is of type "oauth2", then the value is a list of scopes, otherwise it MUST be an empty array /// </param> public static void AddSecurityRequirement( this SwaggerGenOptions swaggerGenOptions, OpenApiSecurityRequirement securityRequirement) { swaggerGenOptions.SwaggerGeneratorOptions.SecurityRequirements.Add(securityRequirement); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddControllers(); //X509Certificate2 signingCert = new X509Certificate2("devcert.pfx", "123456"); //X509SecurityKey privateKey = new X509SecurityKey(signingCert); //var credential = new SigningCredentials(privateKey, SecurityAlgorithms.RsaSha256Signature); //var key = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(Configuration["JwtBearer:SecurityKey"])); //var credential = new SigningCredentials(key, SecurityAlgorithms.HmacSha256); services.AddIdentityServer() //.AddSigningCredential(credential) //.AddDeveloperSigningCredential(false)//生产环境 .AddDeveloperSigningCredential() .AddInMemoryApiScopes(Config.GetApiScopes()) .AddInMemoryClients(Config.GetClients()); services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) .AddJwtBearer(JwtBearerDefaults.AuthenticationScheme, options => { options.Authority = "http://localhost:5000/"; //开发环境:指定为发布后的访问地址 //options.Authority = "http://192.168.1.4:8080/";//生产环境:指定为发布后的访问地址 options.RequireHttpsMetadata = false; options.TokenValidationParameters = new TokenValidationParameters { // ValidateIssuerSigningKey = true, ValidateAudience = false, //ValidateIssuerSigningKey=false //IssuerSigningKey = new X509SecurityKey(new System.Security.Cryptography.X509Certificates.X509Certificate2()) }; //IdentityModelEventSource.ShowPII = true; //options.MetadataAddress = "http://localhost:8080/.well-known/openid-configuration";// //options.Configuration = new Microsoft.IdentityModel.Protocols.OpenIdConnect.OpenIdConnectConfiguration(); options.Audience = Config.ImageMan; }); //services.AddAuthorization(options => //{ // options.AddPolicy("ApiScope", policy => // { // policy.RequireAuthenticatedUser(); // policy.RequireClaim("scope", Config.ImageMan); // }); //}); //services.AddSingleton<ICorsPolicyService>((container) => //{ // { // var logger = container.GetRequiredService<ILogger<DefaultCorsPolicyService>>(); // return new DefaultCorsPolicyService(logger) // { // AllowAll = true // }; // }; //}); services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new OpenApiInfo { Version = "v1", Title = "ToDo API", Description = "A simple example ASP.NET Core Web API", TermsOfService = new Uri("https://example.com/terms"), Contact = new OpenApiContact { Name = "Shayne Boyer", Email = string.Empty, Url = new Uri("https://twitter.com/spboyer"), }, License = new OpenApiLicense { Name = "Use under LICX", Url = new Uri("https://example.com/license"), } }); //Bearer 的scheme定义 var securityScheme = new OpenApiSecurityScheme() { Description = "JWT Authorization header using the Bearer scheme. Example: \"Authorization: Bearer {token}\"", Name = "Authorization", //参数添加在头部 In = ParameterLocation.Header, //使用Authorize头部 Type = SecuritySchemeType.Http, //内容为以 bearer开头 Scheme = "bearer", BearerFormat = "JWT" }; //把所有方法配置为增加bearer头部信息 var securityRequirement = new OpenApiSecurityRequirement { { new OpenApiSecurityScheme { Reference = new OpenApiReference { Type = ReferenceType.SecurityScheme, Id = "bearerAuth" } }, new string[] {} } }; //注册到swagger中 c.AddSecurityDefinition("bearerAuth", securityScheme); c.AddSecurityRequirement(securityRequirement); }); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { //Swagger services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new OpenApiInfo { Title = "Seuphone", Version = "v1" }); var securitySchema = new OpenApiSecurityScheme { Description = "JWT Authorization header using the Bearer scheme. Example: \"Authorization: Bearer {token}\"", Name = "Authorization", In = ParameterLocation.Header, Type = SecuritySchemeType.Http, Scheme = "bearer", Reference = new OpenApiReference { Type = ReferenceType.SecurityScheme, Id = "Bearer" } }; c.AddSecurityDefinition("Bearer", securitySchema); var securityRequirement = new OpenApiSecurityRequirement(); securityRequirement.Add(securitySchema, new[] { "Bearer" }); c.AddSecurityRequirement(securityRequirement); var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml"; var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile); c.IncludeXmlComments(xmlPath, includeControllerXmlComments: true); }); // Disabling CORS for enable api access from react client web pages services.AddCors(options => { options.AddPolicy("CorsPolicy", builder => builder .AllowAnyOrigin() .AllowAnyMethod() .AllowAnyHeader() //.AllowCredentials() ); }); services.AddControllers(); // JWT var appSettingsSection = Configuration.GetSection("AppSettings"); services.Configure <AppSettings>(appSettingsSection); 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.RequireHttpsMetadata = false; x.SaveToken = true; x.TokenValidationParameters = new TokenValidationParameters { ClockSkew = TimeSpan.FromMinutes(30), ValidateIssuerSigningKey = true, IssuerSigningKey = new SymmetricSecurityKey(key), ValidateIssuer = false, ValidateAudience = false }; }); services.AddDbContext <SeuphoneApiContext>(options => options.UseSqlServer(Configuration.GetConnectionString("SeuphoneApiContext"), builder => builder.MigrationsAssembly("Seuphone.Api"))); // auto seed db services.AddScoped <SeedingService>(); // Add services on startup services.AddScoped <IUserService, UserService>(); services.AddScoped <OrderService, OrderService>(); services.AddScoped <MailService, MailService>(); // json serialization for nested object // enum serialization to show string value instead of index integer services.AddControllers().AddNewtonsoftJson(options => { options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore; options.SerializerSettings.Converters.Add(new StringEnumConverter()); } ); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { // Add Iservice services.AddTransient <ILoginService, LoginService>(); // Add JWToken //Add authen fixbug cannot get Claims services.AddAuthentication(o => { o.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; o.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; }).AddJwtBearer(cfg => { cfg.RequireHttpsMetadata = false; cfg.SaveToken = true; cfg.TokenValidationParameters = new TokenValidationParameters { ValidIssuer = Configuration["Tokens:Issuer"], ValidAudience = Configuration["Tokens:Issuer"], IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Tokens:Key"])) }; }); // Add Swagger services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new OpenApiInfo { Title = "API Demo", // Version = "1.0", //Description = "This API Customer", //Contact = new OpenApiContact //{ // Name = "DamNgocSon", // Email = "*****@*****.**", // Url = new Uri("https://sonlanggtu.github.io/"), //} }); c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme { In = ParameterLocation.Header, Description = "Please insert JWT with Bearer into field", Name = "Authorization", Type = SecuritySchemeType.ApiKey }); var result = new OpenApiSecurityRequirement(); c.AddSecurityRequirement(new OpenApiSecurityRequirement() { { new OpenApiSecurityScheme { Reference = new OpenApiReference { Type = ReferenceType.SecurityScheme, Id = "Bearer" }, Scheme = "oauth2", Name = "Bearer", In = ParameterLocation.Header, }, new List <string>() } }); }); // Add Controller services.AddControllersWithViews(); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { // Database Setup (Sqlite will be used while in Dev, should be changed to SqlServer in Production) services.AddDbContext <DatabaseContext>( options => options.UseSqlite(Configuration.GetConnectionString("SqliteConnection"))); // options => options.UseSqlServer(Configuration.GetConnectionString("DbConnection"))); // MVC & Other Services services.AddCors(options => { options.AddPolicy("ServerPolicy", builder => { builder.AllowAnyHeader().AllowAnyMethod().AllowCredentials() .SetIsOriginAllowed(origin => new Uri(origin).Host == "localhost"); // .WithOrigins( // Configuration["AppSettings:AllowedOrigins:GameClientOrigin"], // Configuration["AppSettings:AllowedOrigins:GameServerOrigin"] ); }); }); services.AddMvc(); services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies()); // JWT Auth // secret: Configuration["JwtSettings:Secret"], is saved in dotnet user-secrets var key = Encoding.ASCII.GetBytes(Configuration["AppSettings:JwtSettings:Secret"]); services.AddAuthentication(x => { x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; }).AddJwtBearer(x => { x.Events = new CustomJwtBearerEvents(); x.RequireHttpsMetadata = false; x.SaveToken = true; x.TokenValidationParameters = new TokenValidationParameters { ValidateIssuerSigningKey = true, IssuerSigningKey = new SymmetricSecurityKey(key), ValidateIssuer = false, ValidateAudience = false, }; }); // Add Data Access Repositories services.AddScoped <IPlayerRepository, PlayerRepository>(); services.AddScoped <IFriendInviteRepository, FriendInviteRepository>(); services.AddScoped <IFriendsRepository, FriendsRepository>(); services.AddScoped <IMatchdataRepository, MatchdataRepository>(); services.AddScoped <IGameInviteRepository, GameInviteRepository>(); // Add Data Processing Services services.AddScoped <ISessionService, SessionService>(); services.AddScoped <IPlayerService, PlayerService>(); services.AddScoped <IFriendsService, FriendsService>(); services.AddScoped <IEmailService, EmailService>(); services.AddScoped <IMatchdataService, MatchdataService>(); services.AddScoped <IGameInviteService, GameInviteService>(); // Swagger Conf services.AddSwaggerGen(c => { c.SwaggerDoc("GameWebAPIv1", new OpenApiInfo { Version = "v1", Title = "DarkeningAgeGameWebAPI", Description = "LDS 2020 - Game WebService API in ASP.NET Core 3.1", }); var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml"; var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile); c.IncludeXmlComments(xmlPath); var securitySchema = new OpenApiSecurityScheme { Description = "JWT Bearer Authorization", Name = "Authorization", In = ParameterLocation.Header, Type = SecuritySchemeType.Http, Scheme = "bearer", Reference = new OpenApiReference { Type = ReferenceType.SecurityScheme, Id = "Bearer" } }; c.AddSecurityDefinition("Bearer", securitySchema); var securityRequirement = new OpenApiSecurityRequirement(); securityRequirement.Add(securitySchema, new[] { "Bearer" }); c.AddSecurityRequirement(securityRequirement); }); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { ConfigureSettings <Settings>(services); services.RegisterServices(); services.AddDbContext <CiklumDbContext>(opt => opt.UseInMemoryDatabase()); services.AddMvc(); services.AddAutoMapper(typeof(AutoMapping)); var settings = Configuration.GetSection("Settings").Get <Settings>(); services.AddAuthentication(o => { o.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; o.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; o.DefaultSignInScheme = JwtBearerDefaults.AuthenticationScheme; }).AddJwtBearer(options => { options.IncludeErrorDetails = true; options.RequireHttpsMetadata = settings.AuthOptions.RequireHttpsMetadata; options.TokenValidationParameters = new TokenValidationParameters { ValidateIssuer = true, ValidIssuer = settings.AuthOptions.Issuer, ValidateAudience = true, ValidAudience = settings.AuthOptions.Audience, ValidateLifetime = true, ClockSkew = TimeSpan.FromMinutes(settings.AuthOptions.LifeTime), IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(settings.AuthOptions.Key)), ValidateIssuerSigningKey = true, }; }); services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new OpenApiInfo { Version = "v1", Title = "CiklumTest API", Description = "A sample API for testing and prototyping CiklumTest features" }); c.OperationFilter <AddAuthHeaderOperationFilter>(); c.AddSecurityDefinition("Authorization", new OpenApiSecurityScheme() { Description = "JWT Authorization header using the Bearer scheme. Example: \"Authorization: Bearer {token}\"", Name = "Authorization", Type = SecuritySchemeType.Http, BearerFormat = "JWT", In = ParameterLocation.Header, Scheme = "bearer" }); OpenApiSecurityScheme securityScheme = new OpenApiSecurityScheme() { Reference = new OpenApiReference() { Id = "Authorization", Type = ReferenceType.SecurityScheme } }; OpenApiSecurityRequirement securityRequirements = new OpenApiSecurityRequirement() { { securityScheme, new string[] { } }, }; c.IncludeXmlComments("CiklumTest.WebApi.xml"); c.DescribeAllEnumsAsStrings(); }); }
public static IHostBuilder CreateWebHostBuilder(string[] args) { return (Host.CreateDefaultBuilder(args) .ConfigureLogging((hostingContext, logging) => { logging.ClearProviders(); logging.AddConsole(); logging.AddDebug(); logging.AddWTMLogger(); }) .ConfigureWebHostDefaults(webBuilder => { webBuilder.ConfigureServices(x => { var pris = new List <IDataPrivilege> { new DataPrivilegeInfo <VOS_Organization>("组织机构", y => y.OrganizationName), }; x.AddFrameworkService(dataPrivilegeSettings: pris); //x.AddFrameworkService(); x.AddLayui(); x.AddSwaggerGen(c => { c.SwaggerDoc("v1", new OpenApiInfo { Title = "My API", Version = "v1" }); var bearer = new OpenApiSecurityScheme() { Description = "JWT Bearer", Name = "Authorization", In = ParameterLocation.Header, Type = SecuritySchemeType.ApiKey }; c.AddSecurityDefinition("Bearer", bearer); var sr = new OpenApiSecurityRequirement(); sr.Add(new OpenApiSecurityScheme { Reference = new OpenApiReference { Type = ReferenceType.SecurityScheme, Id = "Bearer" } }, new string[] { }); c.AddSecurityRequirement(sr); }); x.AddRazorPages().AddRazorRuntimeCompilation(); }); webBuilder.Configure(x => { var configs = x.ApplicationServices.GetRequiredService <Configs>(); if (configs.IsQuickDebug == true) { x.UseSwagger(); x.UseSwaggerUI(c => { c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1"); }); } x.UseFrameworkService(); }); } )); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1); services.AddSingleton(Configuration); services.AddDbContext <MyDBContext>(options => options.UseSqlServer(Configuration.GetConnectionString("MyDBContext"))); services.AddAutoMapper(typeof(Startup)); services.AddIdentity <Domain.ApplicationUser, IdentityRole>() .AddEntityFrameworkStores <MyDBContext>() .AddDefaultTokenProviders(); // Configure identity options services.Configure <IdentityOptions>(config => { // user var user = config.User; user.RequireUniqueEmail = true; // password var password = config.Password; password.RequiredLength = 5; password.RequireDigit = false; password.RequireUppercase = false; password.RequireLowercase = false; password.RequireNonAlphanumeric = false; }); services.AddSession(options => { options.Cookie.HttpOnly = true; // Make the session cookie essential options.Cookie.IsEssential = true; }); services.AddMvc(); // Add swagger gen services.AddSwaggerGen(c => { c.CustomOperationIds(e => $"{e.ActionDescriptor.RouteValues["controller"]}_{ e.ActionDescriptor.RouteValues["action"] }"); c.MapType <System.DateTime>(() => new OpenApiSchema() { Type = "string", Format = "YYYY-MM-dd HH:mm:ss" }); c.SwaggerDoc("v1", new OpenApiInfo { Title = "Swagger API", Version = "v1" }); // Bearer token authentication OpenApiSecurityScheme securityDefinition = new OpenApiSecurityScheme() { Name = "Bearer", BearerFormat = "JWT", Scheme = "bearer", Description = "Specify the authorization token.", In = ParameterLocation.Header, Type = SecuritySchemeType.Http, }; c.AddSecurityDefinition("jwt_auth", securityDefinition); // Make sure swagger UI requires a Bearer token specified OpenApiSecurityScheme securityScheme = new OpenApiSecurityScheme() { Reference = new OpenApiReference() { Id = "jwt_auth", Type = ReferenceType.SecurityScheme } }; OpenApiSecurityRequirement securityRequirements = new OpenApiSecurityRequirement() { { securityScheme, new string[] { } }, }; c.AddSecurityRequirement(securityRequirements); }); // Enable swagger enum to string conversions services.AddSwaggerGenNewtonsoftSupport(); services.Configure <FormOptions>(options => { options.MultipartBodyLengthLimit = 60000000; }); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { // addDataBase services.AddDbContext <ModelContext>(options => options.UseOracle(Configuration.GetConnectionString("DefaultConnection"))); //addAuthentication var appSettingsSection = Configuration.GetSection("AppSettings"); services.Configure <AppSettings>(appSettingsSection); var appSettings = appSettingsSection.Get <AppSettings>(); var key = Encoding.ASCII.GetBytes(appSettings.Secret); services.AddAuthentication(m => { m.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; m.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; }).AddJwtBearer(x => { x.RequireHttpsMetadata = false; x.SaveToken = true; x.TokenValidationParameters = new TokenValidationParameters { ValidateIssuerSigningKey = true, IssuerSigningKey = new SymmetricSecurityKey(key), ValidateIssuer = false, ValidateAudience = false, ValidateLifetime = true, ClockSkew = TimeSpan.Zero }; }); services.AddScoped <IUserService, UserService>(); services.AddScoped <IStudentService, StudentService>(); services.AddScoped <IAdminService, AdminService>(); services.AddScoped <IManagerService, ManagerService>(); services.AddCors(options => { options.AddPolicy(MyAllowSpecificOrigins, policy => { policy.WithOrigins("http://localhost:8080", "http://192.168.0.107:8080", "http://47.103.203.188:8080", "http://localhost:8081", "http://localhost:8082") .AllowAnyHeader() .AllowAnyMethod() .AllowCredentials(); }); }); services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2); services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new OpenApiInfo { Title = "My API", Version = "v1" }); //Bearer 的scheme定义 var securityScheme = new OpenApiSecurityScheme() { Description = "JWT Authorization header using the Bearer scheme. Example: \"Authorization: Bearer {token}\". Swagger调试直接粘贴token即可", Name = "Authorization", //参数添加在头部 In = ParameterLocation.Header, //使用Authorize头部 Type = SecuritySchemeType.Http, //内容为以 bearer开头 Scheme = "bearer", BearerFormat = "JWT" }; //把所有方法配置为增加bearer头部信息 var securityRequirement = new OpenApiSecurityRequirement { { new OpenApiSecurityScheme { Reference = new OpenApiReference { Type = ReferenceType.SecurityScheme, Id = "bearerAuth" } }, new string[] {} } }; //注册到swagger中 c.AddSecurityDefinition("bearerAuth", securityScheme); c.AddSecurityRequirement(securityRequirement); }); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddCors(c => { c.AddPolicy("AllowOrigin", options => options.AllowAnyOrigin()); }); services.AddControllers(); // 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.AppSecret); services.AddAuthentication(x => { x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; }) .AddJwtBearer(x => { 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 = "Azakaw Complaints API", Version = "v1" }); var securitySchema = new OpenApiSecurityScheme { Description = "JWT Authorization header using the Bearer scheme. Example: \"Authorization: Bearer {token}\"", Name = "Authorization", In = ParameterLocation.Header, Type = SecuritySchemeType.Http, Scheme = "bearer", Reference = new OpenApiReference { Type = ReferenceType.SecurityScheme, Id = "Bearer" } }; c.AddSecurityDefinition("Bearer", securitySchema); var securityRequirement = new OpenApiSecurityRequirement(); securityRequirement.Add(securitySchema, new[] { "Bearer" }); c.AddSecurityRequirement(securityRequirement); }); services.AddScoped <IUserDataAdapter, UserDataAdapter>(); services.AddScoped <IAuthenticationService, AuthenticationService>(); services.AddScoped <IComplaintDataProvider, ComplaintDataAdapter>(); services.AddScoped <IComplaintService, ComplaintService>(); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddCors(); services.AddControllers(); services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies()); // Configure Options Patternvar var settings = Configuration.GetSection("AppSettings").Get <AppSettings>(); services.Configure <AppSettings>(Configuration.GetSection("AppSettings")); //Add Db Connection string connectionString = Configuration.GetConnectionString("Mysql-Dev"); services.AddDbContext(connectionString); #region Uri Service services.AddHttpContextAccessor(); services.AddSingleton <IUriService>(o => { var accessor = o.GetRequiredService <IHttpContextAccessor>(); var request = accessor.HttpContext.Request; var uri = string.Concat(request.Scheme, "://", request.Host.ToUriComponent()); return(new UriService(uri)); }); #endregion #region JWT //Add Jwt Token services.AddAuthentication(x => { x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; x.DefaultScheme = JwtBearerDefaults.AuthenticationScheme; x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; }) .AddJwtBearer(x => { x.SaveToken = true; x.Events = new JwtBearerEvents { OnTokenValidated = async context => { var userService = context.HttpContext.RequestServices.GetRequiredService <IUserService>(); var userId = int.Parse(context.Principal.Identity.Name); var user = await userService.GetUserByIdAsync(userId); if (user == null) { // return unauthorized if user no longer exists context.Fail("Unauthorized"); } } }; x.TokenValidationParameters = new TokenValidationParameters { ValidateIssuerSigningKey = true, IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(settings.Secret)), ValidateIssuer = false, ValidateAudience = false, RequireExpirationTime = false, ValidateLifetime = true }; }); #endregion #region Swagger //Add Swagger services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new OpenApiInfo { Version = "v1", Title = "MessageBox API", Description = "MessageBox is an offline messaging API developed for Armut interview.", Contact = new OpenApiContact { Name = "Özenç Çelik", Email = "*****@*****.**", Url = new Uri("https://www.linkedin.com/in/%C3%B6zen%C3%A7-%C3%A7elik/"), } }); var security = new OpenApiSecurityRequirement { { new OpenApiSecurityScheme { Reference = new OpenApiReference { Type = ReferenceType.SecurityScheme, Id = "Bearer" } }, new string[] { } } }; c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme { In = ParameterLocation.Header, Description = "JWT Authorization header using the bearer scheme", Name = "Authorization", Type = SecuritySchemeType.ApiKey }); c.AddSecurityRequirement(security); }); #endregion }
/// <summary> /// In default ASP .NET Core has simple IoC container, but can also be used DryIoc container as well. /// </summary> /// <param name="services"></param> public void ConfigureServices(IServiceCollection services) { services.AddControllers() .AddNewtonsoftJson(); services.RegisterMediatR(); services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new OpenApiInfo { Title = "Api", Version = "v1" }); OpenApiSecurityScheme securityDefinition = new OpenApiSecurityScheme() { Name = "Bearer", BearerFormat = "JWT", Scheme = "bearer", Description = "Specify the authorization token.", In = ParameterLocation.Header, Type = SecuritySchemeType.Http, }; c.AddSecurityDefinition("jwt_auth", securityDefinition); OpenApiSecurityScheme securityScheme = new OpenApiSecurityScheme() { Reference = new OpenApiReference() { Id = "jwt_auth", Type = ReferenceType.SecurityScheme } }; OpenApiSecurityRequirement securityRequirements = new OpenApiSecurityRequirement() { { securityScheme, new string[] { } }, }; c.AddSecurityRequirement(securityRequirements); var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml"; var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile); c.IncludeXmlComments(xmlPath); }); services.AddSingleton(Configuration); services.AddSingleton <ISaltGeneratorUtility, SaltGeneratorUtility>(); services.AddSingleton <IEmailAddressValidatorUtility, EmailAddressValidatorUtility>(); services.AddSingleton <IUserPasswordUtility>(new UserPasswordUtility(int.Parse(Configuration["PasswordGenerator:Iterations"]), int.Parse(Configuration["PasswordGenerator:KeySize"]))); services.AddSingleton <JwtSecurityTokenHandler>(); services.AddDbContext <DatabaseContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"))); // Adding Authentication services.AddAuthentication(options => { options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme; }) .AddJwtBearer(options => { options.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:Secret"])) }; }); }
public void ConfigureServices(IServiceCollection services) { services.AddContext(Configuration); services.AddCsRedisCore(Configuration); services.AddSecurity(Configuration); #region AddJwtBearer var jsonWebTokenSettings = services.BuildServiceProvider().GetRequiredService <JsonWebTokenSettings>(); services.AddAuthentication(opts => { opts.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme; opts.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; opts.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; }) .AddCookie(options => { options.LoginPath = "/cms/oauth2/signin"; options.LogoutPath = "/cms/oauth2/signout"; }) .AddJwtBearer(JwtBearerDefaults.AuthenticationScheme, options => { //identityserver4 地址 也就是本项目地址 options.Authority = Configuration["Service:Authority"]; options.RequireHttpsMetadata = false; options.Audience = Configuration["Service:Name"]; options.TokenValidationParameters = new TokenValidationParameters { // The signing key must match! ValidateIssuerSigningKey = true, IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jsonWebTokenSettings.Key)), // Validate the JWT Issuer (iss) claim ValidateIssuer = true, ValidIssuer = jsonWebTokenSettings.Issuer, // Validate the JWT Audience (aud) claim ValidateAudience = true, ValidAudience = jsonWebTokenSettings.Audience, // Validate the token expiry ValidateLifetime = true, // If you want to allow a certain amount of clock drift, set thatValidIssuer here //ClockSkew = TimeSpan.Zero }; //options.TokenValidationParameters = new TokenValidationParameters() //{ // ClockSkew = TimeSpan.Zero //偏移设置为了0s,用于测试过期策略,完全按照access_token的过期时间策略,默认原本为5分钟 //}; //使用Authorize设置为需要登录时,返回json格式数据。 options.Events = new JwtBearerEvents() { OnAuthenticationFailed = context => { //Token expired if (context.Exception.GetType() == typeof(SecurityTokenExpiredException)) { context.Response.Headers.Add("Token-Expired", "true"); } return(Task.CompletedTask); }, OnChallenge = context => { //此处代码为终止.Net Core默认的返回类型和数据结果,这个很重要哦 context.HandleResponse(); string message; ErrorCode errorCode; int statusCode = StatusCodes.Status401Unauthorized; if (context.Error == "invalid_token" && context.ErrorDescription == "The token is expired") { message = "令牌过期"; errorCode = ErrorCode.TokenExpired; statusCode = StatusCodes.Status422UnprocessableEntity; } else if (context.Error == "invalid_token" && context.ErrorDescription.IsNullOrEmpty()) { message = "令牌失效"; errorCode = ErrorCode.TokenInvalidation; } else { message = "请先登录" + context.ErrorDescription; //""认证失败,请检查请求头或者重新登录"; errorCode = ErrorCode.AuthenticationFailed; } context.Response.ContentType = "application/json"; context.Response.StatusCode = statusCode; context.Response.WriteAsync(new UnifyResponseDto(errorCode, message, context.HttpContext).ToString()); return(Task.FromResult(0)); } }; }) .AddGitHub(options => { options.ClientId = Configuration["Authentication:GitHub:ClientId"]; options.ClientSecret = Configuration["Authentication:GitHub:ClientSecret"]; options.Scope.Add("user:email"); options.ClaimActions.MapJsonKey(LinConsts.Claims.AvatarUrl, "avatar_url"); //登录成功后可通过 authenticateResult.Principal.FindFirst(ClaimTypes.Uri)?.Value; 得到GitHub头像 options.ClaimActions.MapJsonKey(LinConsts.Claims.BIO, "bio"); options.ClaimActions.MapJsonKey(LinConsts.Claims.BlogAddress, "blog"); }) .AddQQ(options => { options.ClientId = Configuration["Authentication:QQ:ClientId"]; options.ClientSecret = Configuration["Authentication:QQ:ClientSecret"]; }); #endregion services.AddAutoMapper(typeof(UserProfile).Assembly, typeof(PoemProfile).Assembly); services.AddCors(); #region Mvc services.AddControllers(options => { options.ValueProviderFactories.Add(new ValueProviderFactory()); //设置SnakeCase形式的QueryString参数 //options.Filters.Add<LogActionFilterAttribute>(); // 添加请求方法时的日志记录过滤器 options.Filters.Add <LinCmsExceptionFilter>(); // }) .AddNewtonsoftJson(opt => { opt.SerializerSettings.DateFormatString = "yyyy-MM-dd HH:MM:ss"; // 设置自定义时间戳格式 opt.SerializerSettings.Converters = new List <JsonConverter>() { new LinCmsTimeConverter() }; // 设置下划线方式,首字母是小写 opt.SerializerSettings.ContractResolver = new DefaultContractResolver() { NamingStrategy = new SnakeCaseNamingStrategy() { ProcessDictionaryKeys = true }, }; }) .ConfigureApiBehaviorOptions(options => { options.SuppressConsumesConstraintForFormFileParameters = true; //SuppressUseValidationProblemDetailsForInvalidModelStateResponses; //自定义 BadRequest 响应 options.InvalidModelStateResponseFactory = context => { var problemDetails = new ValidationProblemDetails(context.ModelState); var resultDto = new UnifyResponseDto(ErrorCode.ParameterError, problemDetails.Errors, context.HttpContext); return(new BadRequestObjectResult(resultDto) { ContentTypes = { "application/json" } }); }; }); #endregion services.AddDIServices(); #region Swagger //Swagger重写PascalCase,改成SnakeCase模式 services.TryAddEnumerable(ServiceDescriptor.Transient <IApiDescriptionProvider, ApiDescriptionProvider>()); //Register the Swagger generator, defining 1 or more Swagger documents services.AddSwaggerGen(options => { string ApiName = "LinCms.Web"; options.SwaggerDoc("v1", new OpenApiInfo() { Title = ApiName + RuntimeInformation.FrameworkDescription, Version = "v1", Contact = new OpenApiContact { Name = ApiName, Email = "*****@*****.**", Url = new Uri("https://www.cnblogs.com/igeekfan/") }, License = new OpenApiLicense { Name = ApiName + " 官方文档", Url = new Uri( "https://luoyunchong.github.io/vovo-docs/dotnetcore/lin-cms/dotnetcore-start.html") } }); var security = new OpenApiSecurityRequirement() { { new OpenApiSecurityScheme { Reference = new OpenApiReference() { Id = "Bearer", Type = ReferenceType.SecurityScheme } }, Array.Empty <string>() } }; options.AddSecurityRequirement(security); //添加一个必须的全局安全信息,和AddSecurityDefinition方法指定的方案名称要一致,这里是Bearer。 options.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme { Description = "JWT授权(数据将在请求头中进行传输) 参数结构: \"Authorization: Bearer {token}\"", Name = "Authorization", //jwt默认的参数名称 In = ParameterLocation.Header, //jwt默认存放Authorization信息的位置(请求头中) Type = SecuritySchemeType.ApiKey }); try { string xmlPath = Path.Combine(AppContext.BaseDirectory, $"{typeof(Startup).Assembly.GetName().Name}.xml"); options.IncludeXmlComments(xmlPath, true); //实体层的xml文件名 string xmlEntityPath = Path.Combine(AppContext.BaseDirectory, $"{typeof(IEntity).Assembly.GetName().Name}.xml"); options.IncludeXmlComments(xmlEntityPath); //Dto所在类库 string applicationPath = Path.Combine(AppContext.BaseDirectory, $"{typeof(IApplicationService).Assembly.GetName().Name}.xml"); options.IncludeXmlComments(applicationPath); } catch (Exception ex) { Log.Logger.Warning(ex.Message); } }); #endregion //应用程序级别设置 services.Configure <FormOptions>(options => { //单个文件上传的大小限制为8 MB 默认134217728 应该是128MB options.MultipartBodyLengthLimit = 1024 * 1024 * 8; //8MB }); #region 分布式事务一致性CAP IConfigurationSection configurationSection = Configuration.GetSection("ConnectionStrings:MySql"); services.AddCap(x => { x.UseMySql(configurationSection.Value); bool isEnableInMemoryQueue = Configuration["CAP:InMemoryQueue:IsEnabled"].ToBoolean(); if (isEnableInMemoryQueue) { x.UseInMemoryMessageQueue(); } bool isEnableRabbitMq = Configuration["CAP:RabbitMQ:IsEnabled"].ToBoolean(); if (isEnableRabbitMq) { x.UseRabbitMQ(options => { options.HostName = Configuration["CAP:RabbitMQ:HostName"]; options.UserName = Configuration["CAP:RabbitMQ:UserName"]; options.Password = Configuration["CAP:RabbitMQ:Password"]; options.VirtualHost = Configuration["CAP:RabbitMQ:VirtualHost"]; }); } x.UseDashboard(); x.FailedRetryCount = 5; x.FailedThresholdCallback = (type) => { Console.WriteLine( $@"A message of type {type} failed after executing {x.FailedRetryCount} several times, requiring manual troubleshooting. Message name: {type.Message.GetName()}"); }; }); #endregion services.Configure <ForwardedHeadersOptions>(options => { options.ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto; }); //之前请注入AddCsRedisCore,内部实现IDistributedCache接口 services.AddIpRateLimiting(Configuration); services.AddHealthChecks(); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddLocalization(options => { options.ResourcesPath = "Resources"; }); services.Configure <RequestLocalizationOptions>(options => { var supportedCultures = new[] { new CultureInfo("pt"), new CultureInfo("en") }; options.DefaultRequestCulture = new RequestCulture("en"); options.SupportedCultures = supportedCultures; options.SupportedUICultures = supportedCultures; }); services.AddControllers() .AddDataAnnotationsLocalization(options => { options.DataAnnotationLocalizerProvider = (type, factory) => { return(factory.Create(typeof(Messages))); }; }); services.ConfigureOptions <Options.ApiBehavior>(); services.AddAppSettings(); services.AddScoped <ILoggedUser, LoggedUser>(); services.AddScoped <ITokenGenerator, TokenGenerator>(); services.AddScoped <IAuthentication, Authentication>(); services.AddDbContext <QpancContext>(); services.AddIdentity <User, Role>() .AddRoles <Role>() .AddEntityFrameworkStores <QpancContext>() .AddDefaultTokenProviders(); services.AddTriggers(); services.AddSingleton <ISGuid, SGuid>(); services.AddScoped <ISeeder, Seeder>(); JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear(); services.AddAuthentication(options => { options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme; options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; }).AddJwtBearer( authenticationScheme: JwtBearerDefaults.AuthenticationScheme, configureOptions: options => { _provider.GetRequiredService <IConfigureOptions <JwtBearerOptions> >().Configure(options); }); services.ConfigureOptions <Options.JwtBearer>(); services.ConfigureOptions <Options.Cors>(); services.AddCors(); services.AddSwaggerGen(config => { config.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme() { Description = "JWT Authorization header using the Bearer scheme. Example: \"Authorization: Bearer {token}\"", Name = "Authorization", In = ParameterLocation.Header, Type = SecuritySchemeType.ApiKey }); var requirements = new OpenApiSecurityRequirement(); var bearerSchema = new OpenApiSecurityScheme() { Reference = new OpenApiReference { Type = ReferenceType.SecurityScheme, Id = "Bearer" }, Scheme = "oauth2", Name = "Bearer", In = ParameterLocation.Header }; requirements.Add(bearerSchema, new string[] { }); config.AddSecurityRequirement(requirements); config.SwaggerDoc("v1", new OpenApiInfo { Title = "API - QPANC - Quasar, PostgreSQL, ASP.NET Core and Docker", Description = "API - QPANC - Quasar, PostgreSQL, ASP.NET Core and Docker", Version = "v1", Contact = new OpenApiContact { Name = "QPANC - Quasar, PostgreSQL, ASP.NET Core and Docker", Email = "*****@*****.**", Url = new Uri("http://www.tudosobreplantas.com") }, }); }); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { // cors services.AddCors(options => { options.AddPolicy(name: "localhost", builder => { builder.WithOrigins("http://localhost:3000") .AllowAnyHeader() .AllowAnyMethod(); }); }); // httpClient for making http requests services.AddHttpClient("imgbb", c => { // imgbb url with api key parameter c.BaseAddress = new Uri($"https://api.imgbb.com/1/upload?key={Configuration["imgbbApiKey"]}"); }); // add secret for jwt from user secret var jwtSettings = Configuration.GetSection("Jwt").Get <JwtSettings>(); jwtSettings.Secret = Configuration["JwtSecret"]; // inject updated jwtSetting services.AddSingleton(jwtSettings); services.AddControllers() // prevent potential loop warning .AddNewtonsoftJson(options => options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore ); var builder = new SqlConnectionStringBuilder( Configuration.GetConnectionString("Dev")); // add user secret password for DB builder.Password = Configuration["EbayCloneSQLPassword"]; var connectionString = builder.ToString(); // add DbContext and run migrations in EbayClone.Data services.AddDbContext <EbayCloneDbContext>(options => options.UseSqlServer(connectionString, x => x.MigrationsAssembly("EbayClone.Data"))); // add Identity with additional config services.AddIdentity <User, Role>(options => { options.Password.RequiredLength = 8; }) // add EF implementation .AddEntityFrameworkStores <EbayCloneDbContext>() //default token providers - generate tokens for a password reset, 2 factor authentication, change email and telephone .AddDefaultTokenProviders(); // dependency injection for interfaces services.AddScoped <IUnitOfWork, UnitOfWork>(); services.AddTransient <IItemService, ItemService>(); services.AddTransient <IUserService, UserService>(); services.AddTransient <IAuthService, AuthService>(); services.AddTransient <IFilePathService, FilePathService>(); services.AddTransient <IBasketItemService, BasketItemService>(); services.AddTransient <IOrderService, OrderService>(); services.AddTransient <IOrderItemService, OrderItemService>(); services.AddSwaggerGen(options => { options.SwaggerDoc("v1", new OpenApiInfo { Title = "Ebay Clone", Version = "v1" }); // config to test Bearer token through SwaggerUI options.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme { Description = "JWT containing userid claim", Name = "Authorization", In = ParameterLocation.Header, Type = SecuritySchemeType.ApiKey, }); var security = new OpenApiSecurityRequirement { { new OpenApiSecurityScheme { Reference = new OpenApiReference { Id = "Bearer", Type = ReferenceType.SecurityScheme }, UnresolvedReference = true }, new List <string>() } }; options.AddSecurityRequirement(security); }); services.AddAutoMapper(typeof(Startup)); services.AddAuth(jwtSettings); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddControllers(); services.AddSignalR(); services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new OpenApiInfo { Title = "TheWeatherStationAPI", Version = "v1" }); // Bearer token authentication OpenApiSecurityScheme securityDefinition = new OpenApiSecurityScheme() { Name = "Bearer", BearerFormat = "JWT", Scheme = "bearer", }; c.AddSecurityDefinition("jwt_auth", securityDefinition); // Make sure swagger UI requires a Bearer token specified OpenApiSecurityScheme securityScheme = new OpenApiSecurityScheme() { Reference = new OpenApiReference() { Id = "jwt_auth", Type = ReferenceType.SecurityScheme } }; OpenApiSecurityRequirement securityRequirements = new OpenApiSecurityRequirement() { { securityScheme, new string[] { } }, }; c.AddSecurityRequirement(securityRequirements); }); services.AddDbContext <ApiDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"))); // 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.SecretKey); services.AddAuthentication(x => { x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; }) .AddJwtBearer(x => { x.RequireHttpsMetadata = false; x.SaveToken = true; x.TokenValidationParameters = new TokenValidationParameters { ValidateIssuerSigningKey = true, IssuerSigningKey = new SymmetricSecurityKey(key), ValidateIssuer = false, ValidateAudience = false }; }); services.AddControllers().AddNewtonsoftJson(options => options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore ); }
public void ConfigureServices(IServiceCollection services) { services.AddControllers().AddNewtonsoftJson(s => { // to enable patch requests s.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver(); }); // configuring automapper for our application services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies()); // to set the password hash for version 2 compatability services.Configure <PasswordHasherOptions>(options => options.CompatibilityMode = PasswordHasherCompatibilityMode.IdentityV2 ); // In production, the Angular files will be served from this directory services.AddSpaStaticFiles(configuration => { configuration.RootPath = "ClientApp/dist"; }); services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2); // Email sending service sendgrid extension method dependency injection services.AddSendGridEmailSender(); //EnableCORS services.AddCors(options => { options.AddPolicy("EnableCORS", builder => { builder.AllowAnyHeader().AllowAnyMethod().AllowCredentials().Build(); }); }); // Connect to Database services.AddDbContext <ApplicationDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"), b => b.MigrationsAssembly("Generic.Data")), ServiceLifetime.Transient); //Specifiying we are going to use Identity Framework services.AddIdentity <ApplicationUser, IdentityRole>(options => { options.Password.RequireDigit = true; options.Password.RequiredLength = 6; options.Password.RequireNonAlphanumeric = true; options.Password.RequireUppercase = true; options.Password.RequireLowercase = true; options.User.RequireUniqueEmail = true; // Lockout settings options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(5); options.Lockout.MaxFailedAccessAttempts = 5; options.Lockout.AllowedForNewUsers = true; }).AddEntityFrameworkStores <ApplicationDbContext>().AddDefaultTokenProviders(); //Configure Strongly typed Object var appSettingsSection = Configuration.GetSection("AppSettings"); services.Configure <AppSettings>(appSettingsSection); var appsettings = appSettingsSection.Get <AppSettings>(); var Key = Encoding.ASCII.GetBytes(appsettings.Secret); //Authentication MiddleWare services.AddAuthentication(options => { options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; options.DefaultSignInScheme = JwtBearerDefaults.AuthenticationScheme; options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; }).AddJwtBearer(JwtBearerDefaults.AuthenticationScheme, options => { options.RequireHttpsMetadata = false; options.SaveToken = true; options.TokenValidationParameters = new TokenValidationParameters { ValidateIssuerSigningKey = true, //Same Secret key will be used while creating the token ValidateIssuer = true, ValidateAudience = true, ValidIssuer = appsettings.Site, ValidAudience = appsettings.Audience, IssuerSigningKey = new SymmetricSecurityKey(Key) }; }); //Add Swagger Service services.AddSwaggerGen(x => { x.SwaggerDoc("v1", new OpenApiInfo { Title = "SwaggerApi", Version = "v1" }); var security = new OpenApiSecurityRequirement { { new OpenApiSecurityScheme { Reference = new OpenApiReference { Type = ReferenceType.SecurityScheme, Id = "Bearer" }, Scheme = "oauth2", Name = "Bearer", In = ParameterLocation.Header, }, new List <string>() } }; x.AddSecurityDefinition(name: "Bearer", new OpenApiSecurityScheme { Description = "JWT Authorization header using the bearer scheme", Name = "Authorization", In = ParameterLocation.Header, Type = SecuritySchemeType.ApiKey, }); x.AddSecurityRequirement(security); var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml"; var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile); x.IncludeXmlComments(xmlPath); }); // Authorization Middleware services.AddAuthorization(options => { options.AddPolicy("RequireLoggedIn", policy => policy.RequireRole("Admin", "Default").RequireAuthenticatedUser()); options.AddPolicy("RequireAdministratorRole", policy => policy.RequireRole("Admin").RequireAuthenticatedUser()); //options.AddPolicy("RequireInstructorRole", policy => policy.RequireRole("Instructor").RequireAuthenticatedUser()); }); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies()); services.AddCors(); services.AddDbContext <ApplicationDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("ThomasConnection"))); services.AddControllers(); // 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.SecretKey); services.AddAuthentication(x => { x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; }) .AddJwtBearer(x => { x.RequireHttpsMetadata = false; x.SaveToken = true; x.TokenValidationParameters = new TokenValidationParameters { ValidateIssuerSigningKey = true, IssuerSigningKey = new SymmetricSecurityKey(key), ValidateIssuer = false, ValidateAudience = false }; }); // Add swagger Web.API documentation // Doc: https://docs.microsoft.com/da-dk/aspnet/core/tutorials/web-api-help-pages-using-swagger?view=aspnetcore-3.1 services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new OpenApiInfo { Title = "GUI Assignment 3 Models", Version = "v1", Description = "API to manage models." }); // Set the comments path for the Swagger JSON and UI. var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml"; var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile); c.IncludeXmlComments(xmlPath); // Bearer token authentication OpenApiSecurityScheme securityDefinition = new OpenApiSecurityScheme() { Name = "Bearer", BearerFormat = "JWT", Scheme = "bearer", Description = "Specify the authorization token.", In = ParameterLocation.Header, Type = SecuritySchemeType.Http, }; c.AddSecurityDefinition("jwt_auth", securityDefinition); // Make sure swagger UI requires a Bearer token specified OpenApiSecurityScheme securityScheme = new OpenApiSecurityScheme() { Reference = new OpenApiReference() { Id = "jwt_auth", Type = ReferenceType.SecurityScheme } }; OpenApiSecurityRequirement securityRequirements = new OpenApiSecurityRequirement() { { securityScheme, new string[] { } }, }; c.AddSecurityRequirement(securityRequirements); }); }
public void ConfigureServices(IServiceCollection services) { string connectionString = GetConnectionString(); services.AddHttpContextAccessor(); services.AddAuthentication(options => { options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; }) .AddJwtBearer(options => { options.Authority = Configuration.GetValue <string>("JWT:Authority"); options.Audience = Configuration.GetValue <string>("JWT:Audience"); options.RequireHttpsMetadata = false; options.IncludeErrorDetails = true; options.EventsType = typeof(SbJwtBearerEvents); }); services.AddSingleton <IDbAppContextFactory, DbAppContextFactory>(CreateDbAppContextFactory); //Add database context //- Pattern should be using Configuration.GetConnectionString("Schoolbus") directly; see GetConnectionString for more details. services.AddDbContext <DbAppContext>(options => options.UseNpgsql(connectionString)); services.AddCors(); services .AddControllers(options => { var policy = new AuthorizationPolicyBuilder() .RequireAuthenticatedUser() .Build(); options.Filters.Add(new AuthorizeFilter(policy)); }) .AddNewtonsoftJson(options => { options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver(); options.SerializerSettings.Formatting = Newtonsoft.Json.Formatting.Indented; options.SerializerSettings.DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat; options.SerializerSettings.DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc; options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore; }) .SetCompatibilityVersion(CompatibilityVersion.Version_3_0); services.RegisterPermissionHandler(); services.AddScoped <SbJwtBearerEvents>(); // allow for large files to be uploaded services.Configure <FormOptions>(options => { options.MultipartBodyLengthLimit = 1073741824; // 1 GB }); //enable Hangfire services.AddHangfire(configuration => configuration .UseSerilogLogProvider() .SetDataCompatibilityLevel(CompatibilityLevel.Version_170) .UseSimpleAssemblyNameTypeSerializer() .UseRecommendedSerializerSettings() .UsePostgreSqlStorage(connectionString) ); services.AddHangfireServer(options => { options.WorkerCount = 1; }); // Configure Swagger services.AddSwaggerGen(options => { options.SwaggerDoc("v1", new OpenApiInfo { Version = "v1", Title = "School Bus REST API", Description = "School Bus Inspection System" }); var filePath = Path.Combine(System.AppContext.BaseDirectory, "SchoolBusApi.xml"); options.IncludeXmlComments(filePath); var securitySchema = new OpenApiSecurityScheme { Description = "JWT Authorization header using the Bearer scheme. Example: \"Authorization: Bearer {token}\"", Name = "Authorization", In = ParameterLocation.Header, Type = SecuritySchemeType.Http, Scheme = "bearer", Reference = new OpenApiReference { Type = ReferenceType.SecurityScheme, Id = "Bearer" } }; options.AddSecurityDefinition("Bearer", securitySchema); var securityRequirement = new OpenApiSecurityRequirement(); securityRequirement.Add(securitySchema, new[] { "Bearer" }); options.AddSecurityRequirement(securityRequirement); }); // Add application services. services.RegisterApplicationServices(); services.AddHealthChecks() .AddNpgSql(connectionString, name: "SB-DB-Check", failureStatus: HealthStatus.Degraded, tags: new string[] { "pgsql", "db" }); services.AddCCWServiceClient(Configuration); }
// This method gets called by the runtime. Use this method to add services to the container public void ConfigureServices(IServiceCollection services) { // We use in memory database services.AddDbContext <DataContext>(x => x.UseInMemoryDatabase("TestDb")); services.AddCors(); services.AddControllers().AddJsonOptions(x => x.JsonSerializerOptions.IgnoreNullValues = true); // 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.RequireHttpsMetadata = false; x.SaveToken = true; x.TokenValidationParameters = new TokenValidationParameters { ValidateIssuerSigningKey = true, IssuerSigningKey = new SymmetricSecurityKey(key), ValidateIssuer = false, ValidateAudience = false, // set clockskew to zero so tokens expire exactly at token expiration time (instead of 5 minutes later) ClockSkew = TimeSpan.Zero }; }); //Swagger Config services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new OpenApiInfo { Title = "Market API", Version = "v1", Description = "API Test", Contact = new OpenApiContact { Name = "Federico Martinez", Email = string.Empty, Url = new Uri("https://github.com/fega02/eureka-market-api-test"), }, }); var securitySchema = new OpenApiSecurityScheme { Description = "JWT Authorization header using the Bearer scheme. Example: \"Authorization: Bearer {token}\"", Name = "Authorization", In = ParameterLocation.Header, Type = SecuritySchemeType.Http, Scheme = "bearer", Reference = new OpenApiReference { Type = ReferenceType.SecurityScheme, Id = "Bearer" } }; c.AddSecurityDefinition("Bearer", securitySchema); var securityRequirement = new OpenApiSecurityRequirement(); securityRequirement.Add(securitySchema, new[] { "Bearer" }); c.AddSecurityRequirement(securityRequirement); }); // performance api calls configurations services.AddMvc(options => options.EnableEndpointRouting = false); services.AddOptions(); services.AddMemoryCache(); services.Configure <IpRateLimitOptions>(Configuration.GetSection("IpRateLimiting")); services.AddSingleton <IIpPolicyStore, MemoryCacheIpPolicyStore>(); services.AddSingleton <IRateLimitCounterStore, MemoryCacheRateLimitCounterStore>(); services.AddSingleton <IRateLimitConfiguration, RateLimitConfiguration>(); services.AddHttpContextAccessor(); services.AddHttpClient <ClientHttpService>(c => { c.BaseAddress = new Uri(appSettings.URLAPIlphaVantage); }); // Services services.AddScoped <IUserService, UserServices>(); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddControllers(options => options.Filters.Add <NotificationFilter>()); // services.AddDbContext<SisparDataContext>(options => { // //options.UseSqlServer("Server=sql5059.site4now.net;Database=DB_A5E01E_sisparhomolog;User Id=DB_A5E01E_sisparhomolog_admin;Password=metal001;"); // options.UseSqlServer(_config.GetConnectionString("SisparDbConn")); // }); // Bearer ou Basic (Usuario|Senha) em Base64 // var appSettings = appSettingsSection.Get<AppSettings>(); var key = Encoding.ASCII.GetBytes(Configuration["SecurityKey"]); services.AddAuthentication(x => { x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; }) .AddJwtBearer(x => { 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 = "Sispar - Doc", Version = "v1", // Description = "Exemplo de API REST criada com o ASP.NET Core 3.0 para consulta a indicadores econ�micos", Contact = new OpenApiContact { Email = "*****@*****.**", Name = "Factory Solution IT", Url = new Uri("http://factorysolutionit.com.br") } }); var security = new Dictionary <string, IEnumerable <string> > { { "Bearer", new string[] { } } }; var securitySchema = new OpenApiSecurityScheme { Description = "Entre com o token<br>(NÃO ESQUEÇA DO <strong>bearer</strong> na frente)", Name = "Authorization", In = ParameterLocation.Header, Type = SecuritySchemeType.ApiKey, Scheme = "bearer", Reference = new OpenApiReference { Type = ReferenceType.SecurityScheme, Id = "Bearer" } }; c.AddSecurityDefinition("Bearer", securitySchema); var securityRequirement = new OpenApiSecurityRequirement(); securityRequirement.Add(securitySchema, new[] { "Bearer" }); c.AddSecurityRequirement(securityRequirement); }); DependencyResolver.Resolve(services); services.AddMediatR(typeof(Startup)); }
public void ConfigureServices(IServiceCollection services) { AddAutoMapper(services); AddCors(services); string connection = Configuration.GetConnectionString("DefaultConnection"); services.AddDbContext <BaseDbContext>(options => options.UseSqlServer(connection)); #region Identity services.AddIdentity <Manager, IdentityRole>(options => { options.User = new UserOptions { RequireUniqueEmail = true }; // упростил для тестирования options.Password = new PasswordOptions { RequireDigit = false, RequireNonAlphanumeric = false, RequireUppercase = false, RequireLowercase = false, RequiredLength = 3, }; }).AddEntityFrameworkStores <BaseDbContext>(); services.AddAuthentication(options => { options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; }) .AddJwtBearer(options => { options.RequireHttpsMetadata = false; options.SaveToken = true; options.TokenValidationParameters = new TokenValidationParameters { ValidateIssuer = true, ValidIssuer = Configuration["AuthOptions:ISSUER"], ValidateAudience = true, ValidAudience = Configuration["AuthOptions:AUDIENCE"], ValidateLifetime = true, IssuerSigningKey = Configuration["AuthOptions:KEY"].GetSymmetricSecurityKey(), ValidateIssuerSigningKey = true, }; }); services.AddAuthorization(); #endregion services.AddSingleton(Configuration); services.AddScoped <DataScope>(); services.AddScoped <IEntityManager, EntityManager>(); services.AddScoped <IAutorizationService, AutorizationService>(); services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new OpenApiInfo { Title = "Test API", Version = "v1", Contact = new OpenApiContact { Name = "Git Hub", Email = string.Empty, Url = new Uri("https://github.com/MrEveKS/Travel.Shop.Back"), } }); var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml"; var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile); if (File.Exists(xmlPath)) { c.IncludeXmlComments(xmlPath); } var securitySchema = new OpenApiSecurityScheme { Description = "JWT Authorization header using the Bearer scheme. Example: \"Authorization: Bearer {token}\"", Name = "Authorization", In = ParameterLocation.Header, Type = SecuritySchemeType.Http, Scheme = "bearer", Reference = new OpenApiReference { Type = ReferenceType.SecurityScheme, Id = "Bearer" } }; c.AddSecurityDefinition("Bearer", securitySchema); var securityRequirement = new OpenApiSecurityRequirement { { securitySchema, new[] { "Bearer" } } }; c.AddSecurityRequirement(securityRequirement); }); services.AddMvcCore() .AddNewtonsoftJson() .AddApiExplorer(); }
/// <summary> /// Visits <see cref="OpenApiSecurityRequirement"/> and child objects /// </summary> /// <param name="securityRequirement"></param> internal void Walk(OpenApiSecurityRequirement securityRequirement) { _visitor.Visit(securityRequirement); Walk(securityRequirement as IOpenApiExtensible); }
public void ConfigureServices(IServiceCollection services) { services.AddApplicationInsightsTelemetry(); services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) .AddMicrosoftIdentityWebApi(options => { Configuration.Bind("AzureAdB2C", options); options.TokenValidationParameters.NameClaimType = "name"; }, options => { Configuration.Bind("AzureAdB2C", options); }); services.AddControllers().AddJsonOptions(opts => { opts.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter()); }).AddNewtonsoftJson(); services.AddAuthorization(); services.AddSwaggerGen(c => { c.ResolveConflictingActions(apiDescriptions => apiDescriptions.FirstOrDefault()); c.SwaggerDoc("v1", new OpenApiInfo { Title = "StarWars5e.Api", Version = "v1" }); var securitySchema = new OpenApiSecurityScheme { Description = "JWT Authorization header using the Bearer scheme. Example: \"Authorization: Bearer {token}\"", Name = "Authorization", In = ParameterLocation.Header, Type = SecuritySchemeType.Http, Scheme = "bearer", Reference = new OpenApiReference { Type = ReferenceType.SecurityScheme, Id = "Bearer" } }; c.AddSecurityDefinition("Bearer", securitySchema); var securityRequirement = new OpenApiSecurityRequirement { { securitySchema, new[] { "Bearer" } } }; c.AddSecurityRequirement(securityRequirement); }); services.AddCors(options => { options.AddDefaultPolicy( builder => { builder.AllowAnyOrigin() .AllowAnyHeader() .AllowAnyMethod(); }); }); var tableStorage = new AzureTableStorage(Configuration["StorageAccountConnectionString"]); var cloudStorageAccount = CloudStorageAccount.Parse(Configuration["StorageAccountConnectionString"]); var cloudTableClient = cloudStorageAccount.CreateCloudTableClient(); var cloudBlobClient = new BlobServiceClient(Configuration["StorageAccountConnectionString"]); var searchIndexClient = new SearchIndexClient(new Uri("https://sw5esearch.search.windows.net"), new AzureKeyCredential(Configuration["SearchKey"])); var searchClient = new SearchClient(new Uri("https://sw5esearch.search.windows.net"), "searchterms-index", new AzureKeyCredential(Configuration["SearchKey"])); services.AddSingleton <IAzureTableStorage>(tableStorage); services.Scan(scan => scan .FromAssemblies(typeof(Program).GetTypeInfo().Assembly) .AddClasses(true) .AsImplementedInterfaces() .WithSingletonLifetime() ); services.AddSingleton(cloudBlobClient); services.AddSingleton(cloudTableClient); services.AddSingleton(searchIndexClient); services.AddSingleton(searchClient); }
/// <summary> /// Visits <see cref="OpenApiSecurityRequirement"/> /// </summary> public virtual void Visit(OpenApiSecurityRequirement securityRequirement) { }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { #region JWT //services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(options => //{ // options.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters // { // ValidateIssuer = true,//是否验证Issuer // ValidIssuer = Common.JwtTools.JwtSetting.Issuer, // ValidateAudience = true,//是否验证Audience // ValidAudience = Common.JwtTools.JwtSetting.Audience, // ValidateLifetime = true,//是否验证失效时间 // //ClockSkew = TimeSpan.FromSeconds(60), // IssuerSigningKey = new Microsoft.IdentityModel.Tokens.SymmetricSecurityKey(Encoding.UTF8.GetBytes(Common.JwtTools.JwtSetting.SecretKey)) // }; //}); #endregion #region Swagger #if DEBUG services.AddSwaggerGen(options => { foreach (var item in SwaggerDocs) { options.SwaggerDoc(item.Key, new OpenApiInfo { Title = item.Key, Description = item.Value, Version = "1.0" }); } //防止默认组显示到其他组 options.DocInclusionPredicate((docName, apiDesc) => { System.Reflection.MethodInfo methodInfo; if (!apiDesc.TryGetMethodInfo(out methodInfo)) { return(false); } var versions = methodInfo.DeclaringType.GetCustomAttributes(true).OfType <ApiExplorerSettingsAttribute>().Select(x => x.GroupName); if (docName.ToLower() == "default" && versions.FirstOrDefault() == null) { return(true); } return(versions.Any(x => x.ToString() == docName)); }); //增加Bearer var security = new OpenApiSecurityRequirement { { new OpenApiSecurityScheme() { Reference = new OpenApiReference() { Id = "Bearer", Type = ReferenceType.SecurityScheme }, }, new List <string>() } }; options.AddSecurityRequirement(security); options.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme { Description = "权限认证(数据将在请求头中进行传输) 参数结构: \"Bearer {token}\"", Name = "Authorization", //jwt默认的参数名称 In = ParameterLocation.Header, //jwt默认存放Authorization信息的位置(请求头中) Type = SecuritySchemeType.ApiKey }); //注释 //var basePath = Path.GetDirectoryName(typeof(Program).Assembly.Location); var basePath = AppContext.BaseDirectory; options.IncludeXmlComments(Path.Combine(basePath, "Example.API.xml")); }); #endif #endregion services.AddControllers(options => { options.Filters.Add <ExceptionFilter>(); options.Filters.Add <AuthorizationFilter>(); options.Filters.Add <ActionFilter>(); }).AddNewtonsoftJson(options => { options.SerializerSettings.DateFormatString = "yyyy-MM-dd HH:mm:ss"; options.SerializerSettings.Formatting = Newtonsoft.Json.Formatting.None; options.SerializerSettings.ContractResolver = new Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver(); //options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore; }); }
// This method gets called by the runtime. Use this method to add services to the container. public override void ConfigureServices(IServiceCollection services) { base.ConfigureServices(services); var auth0Scheme = "Auth0"; var audience = "Audience"; var domain = "Domain"; var swaggerClientId = "SwaggerClientId"; var defaultPolicy = new AuthorizationPolicyBuilder() .AddAuthenticationSchemes(auth0Scheme) .RequireAuthenticatedUser() .Build(); services.AddAuthentication(options => { options.DefaultAuthenticateScheme = auth0Scheme; options.DefaultChallengeScheme = auth0Scheme; }) .AddJwtBearerArkDefault(auth0Scheme, audience, domain, o => { if (Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") == "SpecFlow") { o.TokenValidationParameters.ValidIssuer = o.Authority; o.Authority = null; //o.TokenValidationParameters.IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(AuthConstants.ClientSecretSpecFlow)); } o.TokenValidationParameters.RoleClaimType = "Role"; }) ; //HealthChecks services.AddHealthChecks() //.AddCheck<ExampleHealthCheck>("Example Web App Demo Health Check", tags: new string[]{ "ArkTools", "WebDemo"}) .AddSimpleInjectorCheck <ExampleHealthCheck>(name: "Example SimpleInjector Check", failureStatus: HealthStatus.Unhealthy, tags: new string[] { "Example" }) .AddSimpleInjectorLambdaCheck <IExampleHealthCheckService>(name: "Example SimpleInjector Lamda Check", (adapter, ctk) => adapter.CheckHealthAsync(ctk), failureStatus: HealthStatus.Unhealthy, tags: new string[] { "Example" }) .AddSqlServer("Data Source=(localdb)\\MSSQLLocalDB;Initial Catalog=Logs;Integrated Security=True;Persist Security Info=False;Pooling=True;MultipleActiveResultSets=True;Connect Timeout=60;Encrypt=False;TrustServerCertificate=True", healthQuery: "SELECT 1;", name: "NLOG DB", tags: new string[] { "NLOG", "SQLServer" }) ; services.AddArkHealthChecksUIOptions(setup => { if (File.Exists(Path.Combine(Environment.CurrentDirectory, "UIHealthChecks.css"))) { setup.AddCustomStylesheet("UIHealthChecks.css"); } if (File.Exists(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "UIHealthChecks.css"))) { setup.AddCustomStylesheet((String)AppDomain.CurrentDomain.BaseDirectory + "UIHealthChecks.css"); } }); services.ArkConfigureSwaggerAuth0(domain, audience, swaggerClientId); services.ArkConfigureSwaggerUI(c => { c.MaxDisplayedTags(100); c.DefaultModelRendering(ModelRendering.Model); c.ShowExtensions(); //c.OAuthAppName("Public API"); }); services.ConfigureSwaggerGen(c => { var dict = new OpenApiSecurityRequirement { { new OpenApiSecurityScheme { Type = SecuritySchemeType.OAuth2 }, new[] { "openid" } } }; c.AddSecurityRequirement(dict); c.AddPolymorphismSupport <Polymorphic>("kind"); //c.OperationFilter<SecurityRequirementsOperationFilter>(); }); }