// This method gets called by the runtime. Use this method to add services to the container. // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940 public void ConfigureServices(IServiceCollection services) { services.AddMvc(); services.AddIdentityServer() .AddDeveloperSigningCredential() .AddInMemoryIdentityResources(IdentResources.GetIdentityResources()) .AddInMemoryApiResources(ApiResources.GetApiResources()) .AddInMemoryClients(Clients.GetClients()) .AddTestUsers(Users.GetUsers()); services.AddCors(options => { // this defines a CORS policy called "default" options.AddPolicy("default", policy => { policy.WithOrigins("http://localhost:5504") .AllowAnyHeader() .AllowAnyMethod(); }); }); }
public static IIdentityServerBuilder AddCustomIdentityServerServices(this IServiceCollection services, IWebHostEnvironment env, GlobalSettings globalSettings) { services.AddTransient <IDiscoveryResponseGenerator, DiscoveryResponseGenerator>(); services.AddSingleton <StaticClientStore>(); services.AddTransient <IAuthorizationCodeStore, AuthorizationCodeStore>(); var issuerUri = new Uri(globalSettings.BaseServiceUri.InternalIdentity); var identityServerBuilder = services .AddIdentityServer(options => { options.Endpoints.EnableIntrospectionEndpoint = false; options.Endpoints.EnableEndSessionEndpoint = false; options.Endpoints.EnableUserInfoEndpoint = false; options.Endpoints.EnableCheckSessionEndpoint = false; options.Endpoints.EnableTokenRevocationEndpoint = false; options.IssuerUri = $"{issuerUri.Scheme}://{issuerUri.Host}"; options.Caching.ClientStoreExpiration = new TimeSpan(0, 5, 0); if (env.IsDevelopment()) { options.Authentication.CookieSameSiteMode = Microsoft.AspNetCore.Http.SameSiteMode.Unspecified; } }) .AddInMemoryCaching() .AddInMemoryApiResources(ApiResources.GetApiResources()) .AddInMemoryApiScopes(ApiScopes.GetApiScopes()) .AddClientStoreCache <ClientStore>() .AddCustomTokenRequestValidator <CustomTokenRequestValidator>() .AddProfileService <ProfileService>() .AddResourceOwnerValidator <ResourceOwnerPasswordValidator>() .AddPersistedGrantStore <PersistedGrantStore>() .AddClientStore <ClientStore>() .AddIdentityServerCertificate(env, globalSettings); services.AddTransient <ICorsPolicyService, CustomCorsPolicyService>(); return(identityServerBuilder); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddControllers(); ConfigureDatabaseServices(services); services.AddSingleton <IResourceOwnerPasswordValidator, ResourceOwnerPasswordValidator>(); services.AddSingleton <IProfileService, ProfileService>(); services.AddIdentityServer() .AddDeveloperSigningCredential() .AddInMemoryIdentityResources(new IdentityResource[] { new IdentityResources.OpenId() }) .AddInMemoryApiResources(ApiResources.GetApiResources()) .AddInMemoryClients(Clients.Get()) .AddJwtBearerClientAuthentication() .AddProfileService <ProfileService>(); // local api endpoint services.AddLocalApiAuthentication(); }
private object GetResult(ApiResources resource) { try { return(EbApiHelper.GetResult(resource, this.Api, MessageProducer3, this, this.FileClient)); } catch (Exception ex) { if (ex is ExplicitExitException) { this.Api.ApiResponse.Message.Status = "Success"; this.Api.ApiResponse.Message.Description = ex.Message; this.Api.ApiResponse.Message.ErrorCode = ApiErrorCode.ExplicitExit; } else { this.Api.ApiResponse.Message.Status = "Error"; this.Api.ApiResponse.Message.Description = $"Failed to execute Resource '{resource.Name}' " + ex.Message; } throw new ApiException("[GetResult] ," + ex.Message); } }
public static int Seed(ConfigurationDbContext context) { var missingClients = Clients.Where(x => !context.Clients.Any(y => y.ClientId == x.ClientId)); context.Clients.AddRange(missingClients.Select(x => x.ToEntity())); var missingApiResources = ApiResources.Where(x => !context.ApiResources.Any(y => y.Name == x.Name)); context.ApiResources.AddRange(missingApiResources.Select(x => x.ToEntity())); var missingApiScopes = ApiScopes.Where(x => !context.ApiScopes.Any(y => y.Name == x.Name)); context.ApiScopes.AddRange(missingApiScopes.Select(x => x.ToEntity())); var missingIdentityResources = IdentityResources.Where(x => !context.IdentityResources.Any(y => y.Name == x.Name)); foreach (var idr in missingIdentityResources) { var idrToEntity = idr.ToEntity(); if (idrToEntity.Name == IdentityServerConstants.StandardScopes.OpenId || idrToEntity.Name == IdentityServerConstants.StandardScopes.Profile) { idrToEntity.NonEditable = true; } context.IdentityResources.Add(idrToEntity); } try { context.SaveChanges(); } catch (Exception) { return(1); } return(0); }
// the below code is how the setup for the sessions /// <summary> /// retrieves the name /// </summary> /// <param name="id"></param> /// <returns>the display name at id "x"</returns> public string FetchName(int id) { ApiResources Name = _context.ApiResources.Find(id); return(Name.DisplayName); }
public void ConfigureServices(IServiceCollection services) { var provider = services.BuildServiceProvider(); // Options services.AddOptions(); // Settings var globalSettings = new GlobalSettings(); ConfigurationBinder.Bind(Configuration.GetSection("GlobalSettings"), globalSettings); services.AddSingleton(s => globalSettings); services.Configure <IpRateLimitOptions>(Configuration.GetSection("IpRateLimitOptions")); services.Configure <IpRateLimitPolicies>(Configuration.GetSection("IpRateLimitPolicies")); // Repositories services.AddSingleton <IUserRepository, SqlServerRepos.UserRepository>(); services.AddSingleton <ICipherRepository, SqlServerRepos.CipherRepository>(); services.AddSingleton <IDeviceRepository, SqlServerRepos.DeviceRepository>(); services.AddSingleton <IGrantRepository, SqlServerRepos.GrantRepository>(); services.AddSingleton <IOrganizationRepository, SqlServerRepos.OrganizationRepository>(); services.AddSingleton <IOrganizationUserRepository, SqlServerRepos.OrganizationUserRepository>(); services.AddSingleton <ISubvaultRepository, SqlServerRepos.SubvaultRepository>(); services.AddSingleton <ISubvaultUserRepository, SqlServerRepos.SubvaultUserRepository>(); services.AddSingleton <IFolderRepository, SqlServerRepos.FolderRepository>(); // Context services.AddScoped <CurrentContext>(); // Caching services.AddMemoryCache(); // Rate limiting services.AddSingleton <IIpPolicyStore, MemoryCacheIpPolicyStore>(); services.AddSingleton <IRateLimitCounterStore, MemoryCacheRateLimitCounterStore>(); // IdentityServer var identityServerBuilder = services.AddIdentityServer(options => { options.Endpoints.EnableAuthorizeEndpoint = false; options.Endpoints.EnableIntrospectionEndpoint = false; options.Endpoints.EnableEndSessionEndpoint = false; options.Endpoints.EnableUserInfoEndpoint = false; options.Endpoints.EnableCheckSessionEndpoint = false; options.Endpoints.EnableTokenRevocationEndpoint = false; }) .AddInMemoryApiResources(ApiResources.GetApiResources()) .AddInMemoryClients(Clients.GetClients()); services.AddTransient <ICorsPolicyService, AllowAllCorsPolicyService>(); if (Environment.IsProduction()) { var identityServerCert = CoreHelpers.GetCertificate(globalSettings.IdentityServer.CertificateThumbprint); identityServerBuilder.AddSigningCredential(identityServerCert); } else { identityServerBuilder.AddTemporarySigningCredential(); } services.AddScoped <IResourceOwnerPasswordValidator, ResourceOwnerPasswordValidator>(); services.AddScoped <IProfileService, ProfileService>(); services.AddSingleton <IPersistedGrantStore, PersistedGrantStore>(); // Identity services.AddTransient <ILookupNormalizer, LowerInvariantLookupNormalizer>(); services.AddJwtBearerIdentity(options => { options.User = new UserOptions { RequireUniqueEmail = true, AllowedUserNameCharacters = null // all }; options.Password = new PasswordOptions { RequireDigit = false, RequireLowercase = false, RequiredLength = 8, RequireNonAlphanumeric = false, RequireUppercase = false }; options.ClaimsIdentity = new ClaimsIdentityOptions { SecurityStampClaimType = "securitystamp", UserNameClaimType = ClaimTypes.Email }; options.Tokens.ChangeEmailTokenProvider = TokenOptions.DefaultEmailProvider; }, jwtBearerOptions => { jwtBearerOptions.Audience = "bitwarden"; jwtBearerOptions.Issuer = "bitwarden"; jwtBearerOptions.TokenLifetime = TimeSpan.FromDays(10 * 365); jwtBearerOptions.TwoFactorTokenLifetime = TimeSpan.FromMinutes(10); var keyBytes = Encoding.ASCII.GetBytes(globalSettings.JwtSigningKey); jwtBearerOptions.SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(keyBytes), SecurityAlgorithms.HmacSha256); }) .AddUserStore <UserStore>() .AddRoleStore <RoleStore>() .AddTokenProvider <AuthenticatorTokenProvider>(TwoFactorProviderType.Authenticator.ToString()) .AddTokenProvider <EmailTokenProvider <User> >(TokenOptions.DefaultEmailProvider); var jwtIdentityOptions = provider.GetRequiredService <IOptions <JwtBearerIdentityOptions> >().Value; services.AddAuthorization(config => { config.AddPolicy("Application", policy => { policy.AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme, "Bearer2"); policy.RequireAuthenticatedUser(); policy.RequireClaim(ClaimTypes.AuthenticationMethod, jwtIdentityOptions.AuthenticationMethod); }); config.AddPolicy("TwoFactor", policy => { policy.AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme, "Bearer2"); policy.RequireAuthenticatedUser(); policy.RequireClaim(ClaimTypes.AuthenticationMethod, jwtIdentityOptions.TwoFactorAuthenticationMethod); }); }); services.AddScoped <AuthenticatorTokenProvider>(); // Services services.AddSingleton <IMailService, SendGridMailService>(); services.AddSingleton <ICipherService, CipherService>(); services.AddScoped <IUserService, UserService>(); services.AddScoped <IPushService, PushSharpPushService>(); services.AddScoped <IDeviceService, DeviceService>(); services.AddScoped <IBlockIpService, AzureQueueBlockIpService>(); services.AddScoped <IOrganizationService, OrganizationService>(); // Cors services.AddCors(config => { config.AddPolicy("All", policy => policy.AllowAnyHeader().AllowAnyMethod().AllowAnyOrigin().SetPreflightMaxAge(TimeSpan.FromDays(1))); }); // MVC services.AddMvc(config => { config.Filters.Add(new ExceptionHandlerFilterAttribute()); config.Filters.Add(new ModelStateValidationFilterAttribute()); // Allow JSON of content type "text/plain" to avoid cors preflight var textPlainMediaType = MediaTypeHeaderValue.Parse("text/plain"); foreach (var jsonFormatter in config.InputFormatters.OfType <JsonInputFormatter>()) { jsonFormatter.SupportedMediaTypes.Add(textPlainMediaType); } }).AddJsonOptions(options => options.SerializerSettings.ContractResolver = new DefaultContractResolver()); }
private async Task UpdateScopesByApiResourceId(IEnumerable <string> apiScopes, ApiResources apiResource, IDbConnection con, IDbTransaction t) { if (apiScopes.IsNullOrEmpty()) { await RemoveApiScopeByApiResourceId(apiResource.Id, con, t); } else { var dbItems = await GetScopesByApiResourceId(apiResource.Id, con, t); var existingItems = dbItems.ToList(); var updatedItems = apiScopes.ToList(); if (existingItems.IsNullOrEmpty()) { await InsertApiScopeByApiResourceId(updatedItems, apiResource, con, t); } else { var newItems = updatedItems.Where(c => !existingItems.Exists(d => d.Scope == c)); await InsertApiScopeByApiResourceId(newItems, apiResource, con, t); } var deleteItems = existingItems.Where(c => !updatedItems.Exists(d => d == c.Scope)); await RemoveApiScopes(deleteItems, con, t); //find updated var itemsToUpdate = existingItems.Where(c => updatedItems.Exists(d => d == c.Scope)); if (itemsToUpdate.IsNullOrEmpty()) { return; } foreach (var dbItem in itemsToUpdate) { var newItem = updatedItems.SingleOrDefault(c => c == dbItem.Scope); var updateItem = newItem.MapApiScopes(); updateItem.Id = dbItem.Id; //update detail con.Execute( $"update {_options.DbSchema}.ApiResourceScopes set [Scope]=@Scope where id=@id;", updateItem, commandType: CommandType.Text, transaction: t); } } }
private async Task InsertApiScopeByApiResourceId(IEnumerable <string> apiScopes, ApiResources apiResource, IDbConnection con, IDbTransaction t) { if (!apiScopes.Any()) { return; } foreach (var scope in apiScopes) { var item = new ApiResourceScopes() { Scope = scope, ApiResourceId = apiResource.Id }; var scopeId = await con.ExecuteScalarAsync <int>($"insert into {_options.DbSchema}.ApiResourceScopes " + $"(ApiResourceId,[Scope]) " + $"values (@ApiResourceId,@Scope);{_options.GetLastInsertID}", item, commandType : CommandType.Text, transaction : t); } }
public async Task AddApiResource(ApiResource entity) { await ApiResources.InsertOneAsync(entity); }
public async Task <IEnumerable <ApiResource> > FindApiResourcesByScopeAsync(IEnumerable <string> scopeNames) => await Task.FromResult(ApiResources.Where(e => scopeNames.Contains(e.Name)));
public async Task <ApiResource> FindApiResourceAsync(string name) => await Task.FromResult( ApiResources.FirstOrDefault(e => e.Name.Equals(name, StringComparison.Ordinal)));