Example #1
0
        public static IIdentityServerBuilder AddOperationalStore(
            this IIdentityServerBuilder builder,
            string connectionString,
            Action <OperationalStoreOptions> storeOptionsAction = null,
            Action <TokenCleanupOptions> tokenCleanUpOptions    = null)
        {
            builder.Services.Configure <DatabaseOptions>(dbOptions =>
            {
                dbOptions.ConnectionString = connectionString;
            });


            builder.Services.AddTransient <IPersistedGrantStore, PersistedGrantStore>();

            var storeOptions = new OperationalStoreOptions();

            storeOptionsAction?.Invoke(storeOptions);
            builder.Services.AddSingleton(storeOptions);

            var tokenCleanupOptions = new TokenCleanupOptions();

            tokenCleanUpOptions?.Invoke(tokenCleanupOptions);
            builder.Services.AddSingleton(tokenCleanupOptions);
            builder.Services.AddSingleton <TokenCleanup>();

            return(builder);
        }
Example #2
0
 public TokenCleanupService(
     IPersistentGrantRepository persistentGrantRepository,
     IDeviceFlowCodesRepository deviceFlowCodesRepository,
     IOptions <TokenCleanupOptions> options)
 {
     PersistentGrantRepository = persistentGrantRepository;
     DeviceFlowCodesRepository = deviceFlowCodesRepository;
     Options = options.Value;
 }
        public static IIdentityServerBuilder AddOperationalStore(this IIdentityServerBuilder builder, Action <TokenCleanupOptions> tokenCleanUpOptions = null)
        {
            builder.Services.AddScoped <IPersistedGrantStore, PersistedGrantStore>();
            var tokenCleanupOptions = new TokenCleanupOptions();

            tokenCleanUpOptions?.Invoke(tokenCleanupOptions);
            builder.Services.AddSingleton(tokenCleanupOptions);
            builder.Services.AddSingleton <TokenCleanup>();
            return(builder);
        }
Example #4
0
        public TokenCleanup(IServiceProvider serviceProvider, ILogger logger, TokenCleanupOptions options)
        {
            Guard.ForNull(serviceProvider, nameof(serviceProvider));
            Guard.ForNull(logger, nameof(logger));
            Guard.ForNull(options, nameof(options));
            Guard.ForValueLessThan(options.Interval, 1, nameof(options.Interval));

            _serviceProvider = serviceProvider;
            _logger          = logger;
            _interval        = TimeSpan.FromSeconds(options.Interval);
        }
 public TokenCleanupBackgroundWorker(
     AbpAsyncTimer timer,
     IServiceScopeFactory serviceScopeFactory,
     IOptions <TokenCleanupOptions> options)
     : base(
         timer,
         serviceScopeFactory)
 {
     Options      = options.Value;
     timer.Period = Options.CleanupPeriod;
 }
        public TokenCleanup(IServiceProvider serviceProvider, ILogger <TokenCleanup> logger, TokenCleanupOptions options)
        {
            _options = options ?? throw new ArgumentNullException(nameof(options));
            if (_options.TokenCleanupInterval < 1)
            {
                throw new ArgumentException("Token cleanup interval must be at least 1 second");
            }
            if (_options.TokenCleanupBatchSize < 1)
            {
                throw new ArgumentException("Token cleanup batch size interval must be at least 1");
            }

            _logger          = logger ?? throw new ArgumentNullException(nameof(logger));
            _serviceProvider = serviceProvider ?? throw new ArgumentNullException(nameof(serviceProvider));
        }
Example #7
0
        ///// <summary>
        ///// Configures caching for IClientStore, IResourceStore, and ICorsPolicyService with IdentityServer.
        ///// </summary>
        //public static IIdentityServerBuilder AddMongoDBConfigurationStoreCache(
        //    this IIdentityServerBuilder builder)
        //{
        //    builder.AddInMemoryCaching();
        //    // add the caching decorators
        //    builder.AddClientStoreCache<ClientStore>();
        //    builder.AddResourceStoreCache<ResourceStore>();
        //    builder.AddCorsPolicyCache<CorsPolicyService>();
        //    return builder;
        //}

        /// <summary>
        /// 使用IdentityServer配置IPersistedGrantStore的实现。
        /// </summary>
        public static IIdentityServerBuilder AddMongoDBOperationalStore(
            this IIdentityServerBuilder builder,
            Action <TokenCleanupOptions> tokenCleanUpOptionsAction = null)
        {
            builder.Services.AddTransient <IPersistedGrantStore, PersistedGrantStore>();

            builder.Services.AddSingleton <TokenCleanup>();
            builder.Services.AddSingleton <IHostedService, TokenCleanupHost>();

            var tokenCleanupOptions = new TokenCleanupOptions();

            tokenCleanUpOptionsAction?.Invoke(tokenCleanupOptions);
            builder.Services.AddSingleton(tokenCleanupOptions);

            return(builder);
        }
        public static IIdentityServerBuilder AddMongoDBOperationalStore(this IIdentityServerBuilder builder, Action <TokenCleanupOptions> tokenCleanUpOptions = null)
        {
            ConfigureIgnoreExtraElementsOperationalStore();

            builder.Services.AddScoped <IPersistedGrantDbContext, PersistedGrantDbContext>();

            builder.Services.AddTransient <IPersistedGrantStore, PersistedGrantStore>();

            var tokenCleanupOptions = new TokenCleanupOptions();

            tokenCleanUpOptions?.Invoke(tokenCleanupOptions);
            builder.Services.AddSingleton(tokenCleanupOptions);
            builder.Services.AddSingleton <TokenCleanup>();

            return(builder);
        }
        public static IIdentityServerBuilder AddMongoDbConfigurationStore(
            this IIdentityServerBuilder builder)
        {
            builder.Services.AddTransient <IClientStore, ClientStore>();
            builder.Services.AddTransient <IResourceStore, ResourceStore>();
            builder.Services.AddTransient <ICorsPolicyService, CorsPolicyService>();


            //builder.Services.Configure<string>(configuration);
            builder.Services.AddTransient <IPersistedGrantStore, PersistedGrantStore>();

            var tokenCleanupOptions = new TokenCleanupOptions();

            builder.Services.AddSingleton(tokenCleanupOptions);
            builder.Services.AddSingleton <TokenCleanup>();

            return(builder);
        }
        public static IIdentityServerBuilder AddOperationalStore(
            this IIdentityServerBuilder builder,
            Action <DbContextOptionsBuilder> dbContextOptionsAction = null,
            Action <OperationalStoreOptions> storeOptionsAction     = null,
            Action <TokenCleanupOptions> tokenCleanUpOptions        = null)
        {
            builder.Services.AddDbContext <PersistedGrantDbContext>(dbContextOptionsAction);
            builder.Services.AddScoped <IPersistedGrantDbContext, PersistedGrantDbContext>();

            builder.Services.AddTransient <IPersistedGrantStore, PersistedGrantStore>();

            var storeOptions = new OperationalStoreOptions();

            storeOptionsAction?.Invoke(storeOptions);
            builder.Services.AddSingleton(storeOptions);

            var tokenCleanupOptions = new TokenCleanupOptions();

            tokenCleanUpOptions?.Invoke(tokenCleanupOptions);
            builder.Services.AddSingleton(tokenCleanupOptions);
            builder.Services.AddSingleton <TokenCleanup>();

            return(builder);
        }
        public static IIdentityServerBuilder AddOperationalStore(
            this IIdentityServerBuilder builder,
            IConfiguration mongoConfiguration,
            Action <OperationalStoreOptions> storeOptionsAction = null,
            Action <TokenCleanupOptions> tokenCleanUpOptions    = null)
        {
            builder.Services.AddScoped <IPersistedGrantRepository, PersistedGrantRepository>();

            builder.Services.AddTransient <IPersistedGrantStore, PersistedGrantStore>();
            builder.Services.Configure <MongoOptions>(mongoConfiguration);

            var storeOptions = new OperationalStoreOptions();

            storeOptionsAction?.Invoke(storeOptions);
            builder.Services.AddSingleton(storeOptions);

            var tokenCleanupOptions = new TokenCleanupOptions();

            tokenCleanUpOptions?.Invoke(tokenCleanupOptions);
            builder.Services.AddSingleton(tokenCleanupOptions);
            builder.Services.AddSingleton <TokenCleanup>();

            return(builder);
        }
        public TokenCleanup(IServiceProvider serviceProvider, ILogger <TokenCleanup> logger, TokenCleanupOptions options)
        {
            if (serviceProvider == null)
            {
                throw new ArgumentNullException(nameof(serviceProvider));
            }
            if (logger == null)
            {
                throw new ArgumentNullException(nameof(logger));
            }
            if (options == null)
            {
                throw new ArgumentNullException(nameof(options));
            }
            if (options.Interval < 1)
            {
                throw new ArgumentException("interval must be more than 1 second");
            }

            _logger          = logger;
            _serviceProvider = serviceProvider;
            _interval        = TimeSpan.FromSeconds(options.Interval);
        }
Example #13
0
 public TokenCleanupHost(TokenCleanup tokenCleanup, TokenCleanupOptions options)
 {
     _tokenCleanup = tokenCleanup;
     _options      = options;
 }
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.Configure <KestrelServerOptions>(options =>
            {
                options.AllowSynchronousIO = true;
            });


            // register the scope authorization handler
            services.AddSingleton <IAuthorizationHandler, HasPermissionHandler>();
            services.AddSingleton <IAuthorizationHandler, HasScopeHandler>();

            var authority = Configuration.GetValue <string>("AuthenticationSettings:Authority");

            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
            .AddJwtBearer(o =>
            {
                o.Authority                 = authority;
                o.Audience                  = Configuration.GetValue <string>("AuthenticationSettings:Audience");
                o.SaveToken                 = true;
                o.RequireHttpsMetadata      = true;
                o.TokenValidationParameters = new TokenValidationParameters
                {
                    // dont check issuer because of wildcard domain
                    ValidateIssuer           = false,
                    ValidateAudience         = true,
                    ValidateLifetime         = true,
                    ValidateIssuerSigningKey = true
                };
            });

            services.AddAuthorization(options =>
            {
                options.AddPolicy("permissions:read", policy => policy.Requirements.Add(new HasPermissionRequirement("permissions:read", authority)));
                options.AddPolicy("permissions:write", policy => policy.Requirements.Add(new HasPermissionRequirement("permissions:write", authority)));

                options.AddPolicy("authentications:read", policy => policy.Requirements.Add(new HasPermissionRequirement("authentications:read", authority)));
                options.AddPolicy("authentications:write", policy => policy.Requirements.Add(new HasPermissionRequirement("authentications:write", authority)));

                options.AddPolicy("tenants:read", policy => policy.Requirements.Add(new HasPermissionRequirement("tenants:read", authority)));
                options.AddPolicy("tenants:write", policy => policy.Requirements.Add(new HasPermissionRequirement("tenants:write", authority)));

                options.AddPolicy("users:read", policy => policy.Requirements.Add(new HasPermissionRequirement("users:read", authority)));
                options.AddPolicy("users:write", policy => policy.Requirements.Add(new HasPermissionRequirement("users:write", authority)));

                options.AddPolicy("users:read", policy => policy.Requirements.Add(new HasPermissionRequirement("users:read", authority)));
                options.AddPolicy("users:write", policy => policy.Requirements.Add(new HasPermissionRequirement("users:write", authority)));

                options.AddPolicy("roles:read", policy => policy.Requirements.Add(new HasPermissionRequirement("roles:read", authority)));
                options.AddPolicy("roles:write", policy => policy.Requirements.Add(new HasPermissionRequirement("roles:write", authority)));

                options.AddPolicy("roles:read:root", policy => policy.Requirements.Add(new HasPermissionRequirement("roles:read:root", authority)));
                options.AddPolicy("users:write:root", policy => policy.Requirements.Add(new HasPermissionRequirement("users:write:root", authority)));
                options.AddPolicy("users:read:root", policy => policy.Requirements.Add(new HasPermissionRequirement("users:read:root", authority)));

                options.AddPolicy("users:write:tenant", policy => policy.Requirements.Add(new HasPermissionRequirement("users:write:tenant", authority)));
                options.AddPolicy("users:read:tenant", policy => policy.Requirements.Add(new HasPermissionRequirement("users:read:tenant", authority)));

                options.AddPolicy("users:write:user", policy => policy.Requirements.Add(new HasPermissionRequirement("users:write:user", authority)));
                options.AddPolicy("users:read:user", policy => policy.Requirements.Add(new HasPermissionRequirement("users:read:user", authority)));

                options.AddPolicy("application(tenants:read)", policy => policy.Requirements.Add(new HasScopeRequirement("tenants:read", authority)));
                options.AddPolicy("application(tenants:write)", policy => policy.Requirements.Add(new HasScopeRequirement("tenants:write", authority)));

                options.AddPolicy("application(users:read)", policy => policy.Requirements.Add(new HasScopeRequirement("users:read", authority)));
                options.AddPolicy("application(users:write)", policy => policy.Requirements.Add(new HasScopeRequirement("users:write", authority)));
            });


            //Application - Db Context
            services.Configure <ApplicationDbSettings>(
                Configuration.GetSection(nameof(ApplicationDbSettings)));

            services.AddSingleton <IApplicationDbSettings>(sp =>
                                                           sp.GetRequiredService <IOptions <ApplicationDbSettings> >().Value);

            services.AddSingleton <ApplicationDbContext, ApplicationDbContext>();


            //Application - IdentityService to get current user from token
            services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>();
            services.AddScoped <IIdentityService, HttpRequestIdentityService>();

            // Application - Repositories
            services.AddScoped <IApiResourceRepository, ApiResourceRepository>();
            services.AddScoped <IClientRepository, ClientRepository>();
            services.AddScoped <IIdentityResourceRepository, IdentityResourceRepository>();
            services.AddScoped <IPersistedGrandRepository, PersistedGrantRepository>();
            services.AddScoped <ITenantRepository, TenantRepository>();
            services.AddScoped <IUserRepository, UserRepository>();
            services.AddScoped <IRoleRepository, RoleRepository>();
            services.AddScoped <IPermissionRepository, PermissionRepository>();

            // Application - Queries
            services.AddScoped <ApiQueries, ApiQueries>();
            services.AddScoped <ClientQueries, ClientQueries>();
            services.AddScoped <TenantQueries, TenantQueries>();
            services.AddScoped <UserQueries, UserQueries>();
            services.AddScoped <RoleQueries, RoleQueries>();
            services.AddScoped <PermissionQueries, PermissionQueries>();
            services.AddScoped <IdentityResourceQueries, IdentityResourceQueries>();

            // Application - Security
            services.AddScoped <SecurityService, SecurityService>();

            //Custom extension for mongo implementation
            services.AddIdentity <Domain.UserAggregate.IdentityUser, Domain.RoleAggregate.IdentityRole>(options =>
            {
                // For multi tenant
                options.User.RequireUniqueEmail         = false;
                options.Password.RequireNonAlphanumeric = false;
                options.Password.RequireUppercase       = false;
                options.SignIn.RequireConfirmedEmail    = true;
            })
            //.AddEntityFrameworkStores<ApplicationDbContext>()
            .AddUserStore <UserRepository>()
            .AddRoleStore <RoleRepository>()
            .AddSignInManager <CustomSignInManager>()
            .AddDefaultTokenProviders();


            // Application - Commands
            services.AddMediatR(typeof(ApiHandlers).GetTypeInfo().Assembly);

            // Add email and sms services.
            services.AddTransient <IEmailSender, AuthMessageSender>();
            services.AddTransient <ISmsSender, AuthMessageSender>();

            // Localization
            services.AddLocalization(options => options.ResourcesPath = "Resources");


            // Rebus - Integration event
            services.AddRebus(configure => configure
                              .Serialization(s => s.UseNewtonsoftJson(new JsonSerializerSettings {
                TypeNameHandling = TypeNameHandling.None
            }))
                              .Logging(l => l.Console())
                              .Transport(x => x.UseInMemoryTransport(new InMemNetwork(), "bus"))
                              .Subscriptions(x => x.StoreInMemory())
                              .Routing(r => r.TypeBased().MapAssemblyOf <IntegrationEvent>("bus"))
                              );

            // Identity sever configuration
            services.AddScoped <ICustomTokenRequestValidator, CustomClaimInjection>();

            //Identity server persistance
            services.AddTransient <IClientStore, ClientStore>();
            services.AddTransient <IResourceStore, ResourceStore>();
            services.AddTransient <ICorsPolicyService, CustomCorsPolicyService>();
            services.AddTransient <IPersistedGrantStore, PersistedGrantStore>();
            var tokenCleanupOptions = new TokenCleanupOptions();

            services.AddSingleton(tokenCleanupOptions);
            services.AddSingleton <TokenCleanup>();

            services.AddScoped <IProfileService, CustomProfileService>();
            //Identity server
            services.AddIdentityServer(options =>
            {
                options.Events.RaiseSuccessEvents = true;
                options.Events.RaiseFailureEvents = true;
                options.Events.RaiseErrorEvents   = true;
            })
            .AddDeveloperSigningCredential()
            .AddExtensionGrantValidator <AuthorizationServer.Infrastructure.IdentityServer.ExtensionGrantValidator>()
            .AddExtensionGrantValidator <NoSubjectExtensionGrantValidator>()
            .AddJwtBearerClientAuthentication()
            .AddAspNetIdentity <AuthorizationServer.Domain.UserAggregate.IdentityUser>()
            .AddRedirectUriValidator <CustomRedirectUriValidator>()
            .AddProfileService <CustomProfileService>()
            .AddResourceOwnerValidator <CustomResourceOwnerPasswordValidator>();

            services.AddControllersWithViews()
            .AddViewLocalization(
                LanguageViewLocationExpanderFormat.Suffix,
                opts => { opts.ResourcesPath = "Resources"; });

            // API versionning
            services.AddApiVersioning(o =>
            {
                o.AssumeDefaultVersionWhenUnspecified = true;
                o.DefaultApiVersion = new ApiVersion(1, 0);
            });


            // In production, the Angular files will be served from this directory
            services.AddSpaStaticFiles(configuration =>
            {
                configuration.RootPath = "ClientApp/dist";
            });
        }