コード例 #1
0
        public async Task <AdminConfigResponse> Insert(AdminConfigResponse entity)
        {
            string Id          = Guid.NewGuid().ToString();
            var    adminConfig = new AdminConfiguration
            {
                RowKey          = Id,
                PartitionKey    = PartitionKey.AdminConfiguration,
                ConfigId        = Id,
                FlagName        = entity.FlagName,
                FlagDescription = entity.FlagDescription,
                FlagValue       = entity.FlagValue.ToString(),
            };

            await _storage.Insert <AdminConfiguration>(TableStorageEntityType.AdminConfiguration, adminConfig);

            if (entity.FlagValue == Allow.AllOff && entity.UserId != null)
            {
                var chunkedList = this.ChunkBy(entity.UserId, 100).Select(e => string.Join(",", e)).ToList();

                foreach (var chunk in chunkedList)
                {
                    var user = new AllowExtenedUser
                    {
                        RowKey       = Guid.NewGuid().ToString(),
                        PartitionKey = Id,
                        UserId       = chunk
                    };
                    await _storage.Insert <AllowExtenedUser>(TableStorageEntityType.AllowExtenedUser, user);
                }
            }
            entity.ConfigId = new Guid(Id);
            return(entity);
        }
コード例 #2
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env, AdminConfiguration adminConfiguration)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseSwagger();
            app.UseSwaggerUI(c =>
            {
                c.SwaggerEndpoint($"{adminConfiguration.ApiBaseUrl}/swagger/v1/swagger.json", adminConfiguration.ApiName);

                c.OAuthClientId(adminConfiguration.OidcSwaggerUiClientId);
                c.OAuthAppName(adminConfiguration.ApiName);
            });

            app.UseRouting();
            UseAuthentication(app);
            app.UseCors();
            app.UseAuthorization();
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapDefaultControllerRoute();
                endpoints.MapHealthChecks("/health", new HealthCheckOptions
                {
                    ResponseWriter = UIResponseWriter.WriteHealthCheckUIResponse
                });
            });
        }
コード例 #3
0
        public ActionResult FreeTrialQuota()
        {
            using (var db = new EchoContext())
            {
                TrialQuota tq = new TrialQuota();

                var          today       = DateTime.Now.Date;
                AccountTrial today_acctt = db.AccountTrials.SingleOrDefault(x => x.Date.Equals(today));


                if (today_acctt == null)
                {
                    today_acctt = new AccountTrial();
                }

                AdminConfiguration ac = db.AdminConfigurations.SingleOrDefault();

                if (ac == null)
                {
                    ac = new AdminConfiguration();
                }

                tq.no_trial_used     = today_acctt.No_Trial_Used;
                tq.no_trial_acc      = today_acctt.No_Trial_Used_Acc;
                tq.trial_limit_total = ac.Trial_Limit_Total;
                tq.trial_dur_val     = ac.Trial_Dur_Val;
                tq.trial_enable_flag = ac.Trial_Enable_Flag;

                return(View(tq));
            }
        }
コード例 #4
0
        //private static EchoContext db = new EchoContext();

        public static bool is_service_disabled()
        {
            using (var val_db = new EchoContext())
            {
                bool result           = false;
                AdminConfiguration ac = val_db.AdminConfigurations.SingleOrDefault();
                if (ac == null)
                {
                    ac = new AdminConfiguration();
                }

                DateTime utc_now = DateTime.UtcNow;
                //TimeZoneInfo bkk = TimeZoneInfo.FindSystemTimeZoneById("S.E. Asia Standard Time");
                DateTime now            = utc_now.AddHours(7);
                TimeSpan disabled_start = (TimeSpan)ac.Regist_Disable_StartTime;
                TimeSpan disabled_end   = (TimeSpan)ac.Regist_Disable_EndTime;
                if (disabled_end < disabled_start)
                {
                    disabled_end = disabled_end.Add(new TimeSpan(24, 0, 0));
                }
                TimeSpan disabled_span = disabled_end - disabled_start;
                DateTime start_at      = new DateTime(now.Year, now.Month, now.Day, disabled_start.Hours, disabled_start.Minutes, disabled_start.Seconds);
                DateTime end_at        = start_at.Add(disabled_span);

                if (start_at <= now && now <= end_at)
                {
                    result = true;
                }

                return(result);
            }
        }
コード例 #5
0
        public ActionResult UpdateActivationLimit()
        {
            using (var db = new EchoContext())
            {
                ActivationLimit al = new ActivationLimit();

                var date = DateTime.Now.Date;

                AccountActivation aa = db.AccountActivations.Where(x => x.Date.Equals(date)).SingleOrDefault();

                if (aa == null)
                {
                    aa = new AccountActivation();
                }

                AdminConfiguration ac = db.AdminConfigurations.SingleOrDefault();

                if (ac == null)
                {
                    ac = new AdminConfiguration();
                }

                al.no_activation             = aa.No_Activation;
                al.no_activation_pending     = aa.No_Activation_Pending;
                al.no_activation_acc         = aa.No_Activation_Acc;
                al.no_activation_limit_total = ac.No_Activation_Limit_Total;
                al.no_activation_limit_daily = ac.No_Activation_Limit_Daily;


                return(View(al));
            }
        }
コード例 #6
0
ファイル: StartupHelpers.cs プロジェクト: fuji97/open-gate
        private static Task OnMessageReceived(MessageReceivedContext context, AdminConfiguration adminConfiguration)
        {
            context.Properties.IsPersistent = true;
            context.Properties.ExpiresUtc   = new DateTimeOffset(DateTime.Now.AddHours(adminConfiguration.IdentityAdminCookieExpiresUtcHours));

            return(Task.FromResult(0));
        }
コード例 #7
0
 public static IEnumerable <ApiResource> GetApis(AdminConfiguration adminConfiguration)
 {
     return(new List <ApiResource>
     {
         new ApiResource(IdentityServerConstants.LocalApi.ScopeName),
         new ApiResource(adminConfiguration.IdentityAdminApiScope, new List <string> {
             JwtClaimTypes.Role
         })
         {
             Scopes = new List <Scope>()
             {
                 new Scope(adminConfiguration.IdentityAdminApiScope)
             }
         },
         new ApiResource("api1", "My API", new List <string> {
             JwtClaimTypes.Role
         })
         {
             ApiSecrets = new List <Secret>
             {
                 new Secret("api1Secret1".Sha256(), "api1Secret1", DateTime.Now.AddMinutes(1)),
                 new Secret("api1Secret2".Sha256(), "api1Secret2")
             },
             Scopes = new List <Scope>
             {
                 new Scope("api1"),
                 new Scope("api2"),
                 new Scope("apiall")
             }
         }
     });
 }
コード例 #8
0
 public ConfirmationPerson(IPersonService personService,
                           IOptions <SendGridConnections> sendGridSettings,
                           IOptions <AdminConfiguration> adminSettings)
 {
     this.personService    = personService;
     this.sendGridSettings = sendGridSettings.Value;
     this.adminSettings    = adminSettings.Value;
 }
コード例 #9
0
 public ConfirmationCommunity(ICommunityService communityService,
                              IOptions <SendGridConnections> sendGridSettings,
                              IOptions <AdminConfiguration> adminSettings)
 {
     this.communityService = communityService;
     this.sendGridSettings = sendGridSettings.Value;
     this.adminSettings    = adminSettings.Value;
 }
コード例 #10
0
 public ConfirmationArticle(IArticleService articleService,
                            IOptions <SendGridConnections> sendGridSettings,
                            IOptions <AdminConfiguration> adminSettings)
 {
     this.articleService   = articleService;
     this.sendGridSettings = sendGridSettings.Value;
     this.adminSettings    = adminSettings.Value;
 }
コード例 #11
0
        private static Task OnRedirectToIdentityProvider(RedirectContext context, AdminConfiguration adminConfiguration)
        {
            if (!string.IsNullOrEmpty(adminConfiguration.IdentityAdminRedirectUri))
            {
                context.ProtocolMessage.RedirectUri = adminConfiguration.IdentityAdminRedirectUri;
            }

            return(Task.CompletedTask);
        }
コード例 #12
0
 public ReportEvents(IEventService eventService,
                     IOptions <SendGridConnections> sendGridSettings,
                     IOptions <AdminConfiguration> adminSettings,
                     IFlatFileService flatFileService,
                     IFileService fileService)
 {
     this.eventService     = eventService;
     this.flatFileService  = flatFileService;
     this.fileService      = fileService;
     this.sendGridSettings = sendGridSettings.Value;
     this.adminSettings    = adminSettings.Value;
 }
コード例 #13
0
 /// <summary>
 /// Initializes a new instance of the <see cref="DashboardService"/> class.
 /// </summary>
 /// <param name="noteDelegate">The note delegate to interact with the DB.</param>
 /// <param name="userProfileDelegate">The user profile delegate to interact with the DB.</param>
 /// <param name="betaRequestDelegate">The beta request delegate to interact with the DB.</param>
 /// <param name="config">The configuration provider.</param>
 public DashboardService(
     INoteDelegate noteDelegate,
     IUserProfileDelegate userProfileDelegate,
     IBetaRequestDelegate betaRequestDelegate,
     IConfiguration config)
 {
     this.noteDelegate        = noteDelegate;
     this.userProfileDelegate = userProfileDelegate;
     this.betaRequestDelegate = betaRequestDelegate;
     this.configuration       = config;
     this.adminConfiguration  = new AdminConfiguration();
     this.configuration.GetSection("Admin").Bind(this.adminConfiguration);
 }
コード例 #14
0
        private static Task OnRedirectToIdentityProvider(RedirectContext n, AdminConfiguration adminConfiguration)
        {
            n.ProtocolMessage.RedirectUri = adminConfiguration.IdentityAdminRedirectUri;

            // EZY-modification (EZYC-3029): custom feature to support redirecting when deployed inside d-c where ports are different.
            if (adminConfiguration.IdentityServerUseExternalBaseUrl)
            {
                n.ProtocolMessage.IssuerAddress = n.ProtocolMessage.IssuerAddress.Replace(
                    adminConfiguration.IdentityServerBaseUrl, adminConfiguration.IdentityServerExternalBaseUrl);
            }

            return(Task.FromResult(0));
        }
コード例 #15
0
 /// <summary>
 /// Initializes a new instance of the <see cref="DashboardService"/> class.
 /// </summary>
 /// <param name="noteDelegate">The note delegate to interact with the DB.</param>
 /// <param name="dependentDelegate">The dependent delegate to interact with the DB.</param>
 /// <param name="userProfileDelegate">The user profile delegate to interact with the DB.</param>
 /// <param name="config">The configuration provider.</param>
 public DashboardService(
     INoteDelegate noteDelegate,
     IResourceDelegateDelegate dependentDelegate,
     IUserProfileDelegate userProfileDelegate,
     IConfiguration config)
 {
     this.noteDelegate        = noteDelegate;
     this.dependentDelegate   = dependentDelegate;
     this.userProfileDelegate = userProfileDelegate;
     this.configuration       = config;
     this.adminConfiguration  = new AdminConfiguration();
     this.configuration.GetSection("Admin").Bind(this.adminConfiguration);
 }
コード例 #16
0
        public static void SetAdminClaimsViaHeaders(this HttpClient client, AdminConfiguration adminConfiguration)
        {
            var claims = new[]
            {
                new Claim(ClaimTypes.NameIdentifier, Guid.NewGuid().ToString()),
                new Claim(ClaimTypes.Name, Guid.NewGuid().ToString()),
                new Claim(ClaimTypes.Role, adminConfiguration.AdministrationRole)
            };

            var token = new JwtSecurityToken(claims: claims);
            var t     = new JwtSecurityTokenHandler().WriteToken(token);

            client.DefaultRequestHeaders.Add(AuthenticatedTestRequestMiddleware.TestAuthorizationHeader, t);
        }
コード例 #17
0
 public AccountController(UserResolver <TUser> userResolver, UserManager <TUser> userManager, SignInManager <TUser> signInManager, IClientStore clientStore, IEventService events, IEmailSender emailSender, IGenericControllerLocalizer <AccountController <TUserDto, TUserDtoKey, TRoleDto, TCreateUserDto, TRoleDtoKey, TUserKey, TRoleKey, TUser, TRole, TKey, TUserClaim, TUserRole, TUserLogin, TRoleClaim, TUserToken,
                                                                                                                                                                                                                                                             TUsersDto, TRolesDto, TUserRolesDto, TUserClaimsDto,
                                                                                                                                                                                                                                                             TUserProviderDto, TUserProvidersDto, TUserChangePasswordDto, TRoleClaimsDto> > localizer, AdminConfiguration adminConfiguration, IIdentityService <TUserDto, TUserDtoKey, TRoleDto, TRoleDtoKey, TUserKey, TRoleKey, TUser, TRole, TKey, TUserClaim, TUserRole, TUserLogin, TRoleClaim, TUserToken, TUsersDto, TRolesDto, TUserRolesDto, TUserClaimsDto, TUserProviderDto, TUserProvidersDto, TUserChangePasswordDto, TRoleClaimsDto> identityService, IIdentityServerHelper identityServerHelper, ILogger logger)
 {
     _userResolver         = userResolver;
     _userManager          = userManager;
     _signInManager        = signInManager;
     _clientStore          = clientStore;
     _events               = events;
     _emailSender          = emailSender;
     _localizer            = localizer;
     _adminConfiguration   = adminConfiguration;
     _identityService      = identityService;
     _identityServerHelper = identityServerHelper;
     _logger               = logger;
 }
コード例 #18
0
        public LoginModel(
            SignInManager <ApplicationUser> signInManager,
            UserManager <ApplicationUser> userManager,
            RoleManager <IdentityRole> roleManager,
            ILogger <LoginModel> logger,
            IConfiguration configuration)
        {
            _settings = configuration
                        .GetSection("Admin")
                        .Get <AdminConfiguration>();

            _signInManager = signInManager;
            _userManager   = userManager;
            _roleManager   = roleManager;
            _logger        = logger;
        }
コード例 #19
0
        public ActionResult UpdateActivationLimit(ActivationLimit al)
        {
            using (var db = new EchoContext())
            {
                AdminConfiguration ac      = db.AdminConfigurations.SingleOrDefault();
                string             user_no = Session["User_No"].ToString();
                ac.No_Activation_Limit_Total = Convert.ToInt32(al.no_activation_limit_total);
                ac.No_Activation_Limit_Daily = Convert.ToInt32(al.no_activation_limit_daily);
                ac.Updated_By   = user_no;
                ac.Updated_Dttm = DateTime.Now;

                db.Entry(ac).State = EntityState.Modified;
                db.SaveChanges();
                FreebieEvent.UserUpdateEvent(Permission.activation_page_id, "A04");
                return(RedirectToAction("ActivationLimit"));
            }
        }
コード例 #20
0
        public ActionResult UpdateFreeTrialQuota(TrialQuota tq)
        {
            using (var db = new EchoContext())
            {
                AdminConfiguration ac      = db.AdminConfigurations.SingleOrDefault();
                string             user_no = Session["User_No"].ToString();
                ac.Trial_Limit_Total = Convert.ToInt32(tq.trial_limit_total);
                ac.Trial_Dur_Val     = Convert.ToInt32(tq.trial_dur_val);
                ac.Trial_Enable_Flag = Convert.ToBoolean(tq.trial_enable_flag);
                ac.Updated_By        = user_no;
                ac.Updated_Dttm      = DateTime.Now;

                db.Entry(ac).State = EntityState.Modified;
                db.SaveChanges();
                FreebieEvent.UserUpdateEvent(Permission.free_trial_page_id, "A04");
                return(RedirectToAction("FreeTrialQuota"));
            }
        }
コード例 #21
0
        public async Task <AdminConfigResponse> Upsert(AdminConfigResponse entity)
        {
            var adminConfig = new AdminConfiguration
            {
                RowKey          = entity.ConfigId.ToString(),
                PartitionKey    = PartitionKey.AdminConfiguration,
                ConfigId        = entity.ConfigId.ToString(),
                FlagName        = entity.FlagName,
                FlagDescription = entity.FlagDescription,
                FlagValue       = entity.FlagValue.ToString(),
            };

            await _storage.Upsert <AdminConfiguration>(TableStorageEntityType.AdminConfiguration, adminConfig);

            var existingData = await _storage.GetAll <AllowExtenedUser>(TableStorageEntityType.AllowExtenedUser, entity.ConfigId.ToString());

            foreach (var data in existingData)
            {
                await _storage.Delete <AllowExtenedUser>(TableStorageEntityType.AllowExtenedUser, data);
            }

            if (entity.FlagValue == Allow.AllOff && entity.UserId != null)
            {
                var chunkedList = this.ChunkBy(entity.UserId, 100).Select(e => string.Join(",", e)).ToList();

                foreach (var chunk in chunkedList)
                {
                    var user = new AllowExtenedUser
                    {
                        RowKey       = Guid.NewGuid().ToString(),
                        PartitionKey = entity.ConfigId.ToString(),
                        UserId       = chunk
                    };
                    await _storage.Upsert <AllowExtenedUser>(TableStorageEntityType.AllowExtenedUser, user);
                }
            }
            return(entity);
        }
コード例 #22
0
ファイル: StartupHelpers.cs プロジェクト: fuji97/open-gate
        /// <summary>
        /// Register services for authentication, including Identity.
        /// For production mode is used OpenId Connect middleware which is connected to IdentityServer4 instance.
        /// For testing purpose is used cookie middleware with fake login url.
        /// </summary>
        /// <typeparam name="TContext"></typeparam>
        /// <typeparam name="TUserIdentity"></typeparam>
        /// <typeparam name="TUserIdentityRole"></typeparam>
        /// <param name="services"></param>
        /// <param name="adminConfiguration"></param>
        public static void AddAuthenticationServices <TContext, TUserIdentity, TUserIdentityRole>(this IServiceCollection services, AdminConfiguration adminConfiguration)
            where TContext : DbContext where TUserIdentity : class where TUserIdentityRole : class
        {
            services.AddIdentity <TUserIdentity, TUserIdentityRole>(options =>
            {
                options.User.RequireUniqueEmail = true;
            })
            .AddEntityFrameworkStores <TContext>()
            .AddDefaultTokenProviders();

            services.AddAuthentication(options =>
            {
                options.DefaultScheme          = CookieAuthenticationDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme = AuthenticationConsts.OidcAuthenticationScheme;

                options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
                options.DefaultForbidScheme       = CookieAuthenticationDefaults.AuthenticationScheme;
                options.DefaultSignInScheme       = CookieAuthenticationDefaults.AuthenticationScheme;
                options.DefaultSignOutScheme      = CookieAuthenticationDefaults.AuthenticationScheme;
            })
            .AddCookie(CookieAuthenticationDefaults.AuthenticationScheme,
                       options =>
            {
                options.Cookie.Name = adminConfiguration.IdentityAdminCookieName;

                // Issue: https://github.com/aspnet/Announcements/issues/318
                options.Cookie.SameSite = SameSiteMode.None;
            })
            .AddOpenIdConnect(AuthenticationConsts.OidcAuthenticationScheme, options =>
            {
                options.Authority            = adminConfiguration.IdentityServerBaseUrl;
                options.RequireHttpsMetadata = adminConfiguration.RequireHttpsMetadata;
                options.ClientId             = adminConfiguration.ClientId;
                options.ClientSecret         = adminConfiguration.ClientSecret;
                options.ResponseType         = adminConfiguration.OidcResponseType;

                options.Scope.Clear();
                foreach (var scope in adminConfiguration.Scopes)
                {
                    options.Scope.Add(scope);
                }

                options.ClaimActions.MapJsonKey(adminConfiguration.TokenValidationClaimRole, adminConfiguration.TokenValidationClaimRole, adminConfiguration.TokenValidationClaimRole);

                options.SaveTokens = true;

                options.GetClaimsFromUserInfoEndpoint = true;

                options.TokenValidationParameters = new TokenValidationParameters
                {
                    NameClaimType = adminConfiguration.TokenValidationClaimName,
                    RoleClaimType = adminConfiguration.TokenValidationClaimRole
                };

                options.Events = new OpenIdConnectEvents
                {
                    OnMessageReceived            = context => OnMessageReceived(context, adminConfiguration),
                    OnRedirectToIdentityProvider = context => OnRedirectToIdentityProvider(context, adminConfiguration)
                };
            });
        }
コード例 #23
0
 public UserCreatorService(AdminConfiguration adminConfiguration, IServiceProvider serviceProvider)
 {
     _serviceProvider    = serviceProvider;
     _adminConfiguration = adminConfiguration;
 }
コード例 #24
0
ファイル: Reference.cs プロジェクト: peterschen/SMAStudio
 public static AdminConfiguration CreateAdminConfiguration(string name, string value, global::System.DateTime lastModifiedTime)
 {
     AdminConfiguration adminConfiguration = new AdminConfiguration();
     adminConfiguration.Name = name;
     adminConfiguration.Value = value;
     adminConfiguration.LastModifiedTime = lastModifiedTime;
     return adminConfiguration;
 }
コード例 #25
0
ファイル: Reference.cs プロジェクト: peterschen/SMAStudio
 public void AddToAdminConfigurations(AdminConfiguration adminConfiguration)
 {
     base.AddObject("AdminConfigurations", adminConfiguration);
 }
コード例 #26
0
        /// <summary>
        /// Register services for authentication, including Identity.
        /// For production mode is used OpenId Connect middleware which is connected to Duende IdentityServer instance.
        /// For testing purpose is used cookie middleware with fake login url.
        /// </summary>
        /// <typeparam name="TContext"></typeparam>
        /// <typeparam name="TUserIdentity"></typeparam>
        /// <typeparam name="TUserIdentityRole"></typeparam>
        /// <param name="services"></param>
        /// <param name="adminConfiguration"></param>
        public static void AddAuthenticationServices <TContext, TUserIdentity, TUserIdentityRole>(this IServiceCollection services,
                                                                                                  AdminConfiguration adminConfiguration, Action <IdentityOptions> identityOptionsAction, Action <AuthenticationBuilder> authenticationBuilderAction)
            where TContext : DbContext where TUserIdentity : class where TUserIdentityRole : class
        {
            services.Configure <CookiePolicyOptions>(options =>
            {
                options.MinimumSameSitePolicy = SameSiteMode.Unspecified;
                options.Secure         = CookieSecurePolicy.SameAsRequest;
                options.OnAppendCookie = cookieContext =>
                                         AuthenticationHelpers.CheckSameSite(cookieContext.Context, cookieContext.CookieOptions);
                options.OnDeleteCookie = cookieContext =>
                                         AuthenticationHelpers.CheckSameSite(cookieContext.Context, cookieContext.CookieOptions);
            });

            services
            .AddIdentity <TUserIdentity, TUserIdentityRole>(identityOptionsAction)
            .AddEntityFrameworkStores <TContext>()
            .AddDefaultTokenProviders();

            var authenticationBuilder = services.AddAuthentication(options =>
            {
                options.DefaultScheme          = CookieAuthenticationDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme = AuthenticationConsts.OidcAuthenticationScheme;

                options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
                options.DefaultForbidScheme       = CookieAuthenticationDefaults.AuthenticationScheme;
                options.DefaultSignInScheme       = CookieAuthenticationDefaults.AuthenticationScheme;
                options.DefaultSignOutScheme      = CookieAuthenticationDefaults.AuthenticationScheme;
            })
                                        .AddCookie(CookieAuthenticationDefaults.AuthenticationScheme,
                                                   options =>
            {
                options.Cookie.Name = adminConfiguration.IdentityAdminCookieName;
            })
                                        .AddOpenIdConnect(AuthenticationConsts.OidcAuthenticationScheme, options =>
            {
                options.Authority            = adminConfiguration.IdentityServerBaseUrl;
                options.RequireHttpsMetadata = adminConfiguration.RequireHttpsMetadata;
                options.ClientId             = adminConfiguration.ClientId;
                options.ClientSecret         = adminConfiguration.ClientSecret;
                options.ResponseType         = adminConfiguration.OidcResponseType;

                options.Scope.Clear();
                foreach (var scope in adminConfiguration.Scopes)
                {
                    options.Scope.Add(scope);
                }

                options.ClaimActions.MapJsonKey(adminConfiguration.TokenValidationClaimRole, adminConfiguration.TokenValidationClaimRole, adminConfiguration.TokenValidationClaimRole);

                options.SaveTokens = true;

                options.GetClaimsFromUserInfoEndpoint = true;

                options.TokenValidationParameters = new TokenValidationParameters
                {
                    NameClaimType = adminConfiguration.TokenValidationClaimName,
                    RoleClaimType = adminConfiguration.TokenValidationClaimRole
                };

                options.Events = new OpenIdConnectEvents
                {
                    OnMessageReceived            = context => OnMessageReceived(context, adminConfiguration),
                    OnRedirectToIdentityProvider = context => OnRedirectToIdentityProvider(context, adminConfiguration)
                };
            });

            authenticationBuilderAction?.Invoke(authenticationBuilder);
        }
コード例 #27
0
        /// <summary>
        /// Add authorization policies
        /// </summary>
        /// <param name="services"></param>
        public static void AddAuthorizationPolicies(this IServiceCollection services, AdminConfiguration adminConfiguration,
                                                    Action <AuthorizationOptions> authorizationAction)
        {
            services.AddAuthorization(options =>
            {
                options.AddPolicy(AuthorizationConsts.AdministrationPolicy,
                                  policy => policy.RequireRole(adminConfiguration.AdministrationRole));

                authorizationAction?.Invoke(options);
            });
        }
コード例 #28
0
ファイル: StartupHelpers.cs プロジェクト: fuji97/open-gate
        private static Task OnRedirectToIdentityProvider(RedirectContext n, AdminConfiguration adminConfiguration)
        {
            n.ProtocolMessage.RedirectUri = adminConfiguration.IdentityAdminRedirectUri;

            return(Task.FromResult(0));
        }
コード例 #29
0
        private static void Seed(AppDbContext dbContext, UserManager <User> userManager,
                                 RoleManager <IdentityRole <int> > roleManager, ILogger <AppDbContext> logger, AdminConfiguration config)
        {
            try
            {
                var roles   = Enum.GetNames(typeof(UserRole));
                var dbRoles = dbContext.Roles.ToList();
                if (roles.Length > dbRoles.Count)
                {
                    var rolesToAdd = roles.Where(r => dbRoles.All(dbr => dbr.Name != r));
                    foreach (var role in rolesToAdd)
                    {
                        roleManager.CreateAsync(new IdentityRole <int>(role)).Wait();
                    }
                }

                var user = new User(DateTime.Now, config.AdminUserName);

                userManager.CreateAsync(user).GetAwaiter().GetResult();
                userManager.AddPasswordAsync(user, config.AdminPassword).GetAwaiter().GetResult();
                userManager.AddToRoleAsync(user, UserRole.Admin.ToString()).GetAwaiter().GetResult();

                dbContext.SaveChanges();
            }
            catch (Exception e)
            {
                logger.LogCritical(e.Message);

                throw;
            }
        }
コード例 #30
0
        public static IEnumerable <Client> GetClients(AdminConfiguration adminConfiguration)
        {
            return(new List <Client>
            {
                new Client
                {
                    ClientId = "client",

                    // no interactive user, use the clientid/secret for authentication
                    AllowedGrantTypes = GrantTypes.ClientCredentials,

                    // secret for authentication
                    ClientSecrets =
                    {
                        new Secret("secret".Sha256(),  "secret1", DateTime.Now.AddMinutes(1)),
                        new Secret("secret2".Sha256(), "secret2")
                    },

                    // scopes that client has access to
                    AllowedScopes =
                    {
                        "api1",
                        "api2",
                        "apiall",
                        JwtClaimTypes.Role,
                        IdentityServerConstants.LocalApi.ScopeName,
                        adminConfiguration.IdentityAdminApiScope
                    },
                    ClientClaimsPrefix = string.Empty,
                    Claims = new List <Claim>
                    {
                        new Claim(JwtClaimTypes.Role, "zero.Admin")
                    }
                },
                // resource owner password grant client
                new Client
                {
                    ClientId = "ro.client",
                    AllowedGrantTypes = GrantTypes.ResourceOwnerPassword,
                    ClientSecrets = { new Secret("secret".Sha256()) },
                    AllowedScopes = { "api1", adminConfiguration.IdentityAdminApiScope }
                },
                // OpenID Connect hybrid flow client (MVC)
                new Client
                {
                    ClientId = "mvc",
                    ClientName = "MVC Client",
                    AllowedGrantTypes = GrantTypes.Hybrid,
                    ClientSecrets = { new Secret("secret".Sha256()) },
                    RedirectUris = { "http://localhost:5002/signin-oidc" },
                    PostLogoutRedirectUris = { "http://localhost:5002/signout-callback-oidc" },
                    AllowedScopes =
                    {
                        IdentityServerConstants.StandardScopes.OpenId,
                        IdentityServerConstants.StandardScopes.Profile,
                        JwtClaimTypes.Role,
                        "api1",
                        "api2",
                        adminConfiguration.IdentityAdminApiScope
                    },
                    AllowOfflineAccess = true
                },
                new Client
                {
                    ClientId = "mvc2",
                    ClientName = "MVC Client2",
                    AllowedGrantTypes = GrantTypes.Hybrid,
                    ClientSecrets = { new Secret("secret".Sha256()) },
                    RedirectUris = { "http://localhost:5003/signin-oidc" },
                    PostLogoutRedirectUris = { "http://localhost:5003/signout-callback-oidc" },
                    AllowedScopes =
                    {
                        IdentityServerConstants.StandardScopes.OpenId,
                        IdentityServerConstants.StandardScopes.Profile,
                        JwtClaimTypes.Role,
                        "api1",
                        "api2",
                        adminConfiguration.IdentityAdminApiScope
                    },
                    AllowOfflineAccess = true
                },
                // JavaScript Client
                new Client
                {
                    ClientId = "js",
                    ClientName = "JavaScript Client",
                    AllowedGrantTypes = GrantTypes.Code,
                    RequirePkce = true,
                    RequireClientSecret = false,
                    RedirectUris = { "http://localhost:5003/callback.html" },
                    PostLogoutRedirectUris = { "http://localhost:5003/index.html" },
                    AllowedCorsOrigins = { "http://localhost:5003" },
                    AllowedScopes =
                    {
                        IdentityServerConstants.StandardScopes.OpenId,
                        IdentityServerConstants.StandardScopes.Profile,
                        "api1",
                        adminConfiguration.IdentityAdminApiScope
                    }
                },
                new Client
                {
                    ClientId = adminConfiguration.IdentityAdminApiSwaggerUIClientId,
                    ClientName = adminConfiguration.IdentityAdminApiSwaggerUIClientId,

                    AllowedGrantTypes = GrantTypes.Implicit,

                    RedirectUris = new List <string>
                    {
                        adminConfiguration.IdentityAdminApiSwaggerUIRedirectUrl
                    },
                    AllowedScopes =
                    {
                        JwtClaimTypes.Role,
                        adminConfiguration.IdentityAdminApiScope
                    },
                    AllowAccessTokensViaBrowser = true
                }
            });
        }
コード例 #31
0
ファイル: StartupHelpers.cs プロジェクト: fuji97/open-gate
        public static void AddIdSHealthChecks <TConfigurationDbContext, TPersistedGrantDbContext, TIdentityDbContext, TLogDbContext, TAuditLoggingDbContext>(this IServiceCollection services, IConfiguration configuration, AdminConfiguration adminConfiguration)
            where TConfigurationDbContext : DbContext, IAdminConfigurationDbContext
            where TPersistedGrantDbContext : DbContext, IAdminPersistedGrantDbContext
            where TIdentityDbContext : DbContext
            where TLogDbContext : DbContext, IAdminLogDbContext
            where TAuditLoggingDbContext : DbContext, IAuditLoggingDbContext <AuditLog>
        {
            var configurationDbConnectionString   = configuration.GetConnectionString(ConfigurationConsts.ConfigurationDbConnectionStringKey);
            var persistedGrantsDbConnectionString = configuration.GetConnectionString(ConfigurationConsts.PersistedGrantDbConnectionStringKey);
            var identityDbConnectionString        = configuration.GetConnectionString(ConfigurationConsts.IdentityDbConnectionStringKey);
            var logDbConnectionString             = configuration.GetConnectionString(ConfigurationConsts.AdminLogDbConnectionStringKey);
            var auditLogDbConnectionString        = configuration.GetConnectionString(ConfigurationConsts.AdminAuditLogDbConnectionStringKey);

            var identityServerUri   = adminConfiguration.IdentityServerBaseUrl;
            var healthChecksBuilder = services.AddHealthChecks()
                                      .AddDbContextCheck <TConfigurationDbContext>("ConfigurationDbContext")
                                      .AddDbContextCheck <TPersistedGrantDbContext>("PersistedGrantsDbContext")
                                      .AddDbContextCheck <TIdentityDbContext>("IdentityDbContext")
                                      .AddDbContextCheck <TLogDbContext>("LogDbContext")
                                      .AddDbContextCheck <TAuditLoggingDbContext>("AuditLogDbContext")

                                      .AddIdentityServer(new Uri(identityServerUri), "Identity Server");

            var serviceProvider = services.BuildServiceProvider();
            var scopeFactory    = serviceProvider.GetRequiredService <IServiceScopeFactory>();

            using (var scope = scopeFactory.CreateScope())
            {
                var configurationTableName  = DbContextHelpers.GetEntityTable <TConfigurationDbContext>(scope.ServiceProvider);
                var persistedGrantTableName = DbContextHelpers.GetEntityTable <TPersistedGrantDbContext>(scope.ServiceProvider);
                var identityTableName       = DbContextHelpers.GetEntityTable <TIdentityDbContext>(scope.ServiceProvider);
                var logTableName            = DbContextHelpers.GetEntityTable <TLogDbContext>(scope.ServiceProvider);
                var auditLogTableName       = DbContextHelpers.GetEntityTable <TAuditLoggingDbContext>(scope.ServiceProvider);

                var databaseProvider = configuration.GetSection(nameof(DatabaseProviderConfiguration)).Get <DatabaseProviderConfiguration>();
                switch (databaseProvider.ProviderType)
                {
                case DatabaseProviderType.SqlServer:
                    healthChecksBuilder
                    .AddSqlServer(configurationDbConnectionString, name: "ConfigurationDb",
                                  healthQuery: $"SELECT TOP 1 * FROM dbo.[{configurationTableName}]")
                    .AddSqlServer(persistedGrantsDbConnectionString, name: "PersistentGrantsDb",
                                  healthQuery: $"SELECT TOP 1 * FROM dbo.[{persistedGrantTableName}]")
                    .AddSqlServer(identityDbConnectionString, name: "IdentityDb",
                                  healthQuery: $"SELECT TOP 1 * FROM dbo.[{identityTableName}]")
                    .AddSqlServer(logDbConnectionString, name: "LogDb",
                                  healthQuery: $"SELECT TOP 1 * FROM dbo.[{logTableName}]")
                    .AddSqlServer(auditLogDbConnectionString, name: "AuditLogDb",
                                  healthQuery: $"SELECT TOP 1 * FROM dbo.[{auditLogTableName}]");
                    break;

                case DatabaseProviderType.PostgreSQL:
                    healthChecksBuilder
                    .AddNpgSql(configurationDbConnectionString, name: "ConfigurationDb",
                               healthQuery: $"SELECT * FROM {configurationTableName} LIMIT 1")
                    .AddNpgSql(persistedGrantsDbConnectionString, name: "PersistentGrantsDb",
                               healthQuery: $"SELECT * FROM {persistedGrantTableName} LIMIT 1")
                    .AddNpgSql(identityDbConnectionString, name: "IdentityDb",
                               healthQuery: $"SELECT * FROM {identityTableName} LIMIT 1")
                    .AddNpgSql(logDbConnectionString, name: "LogDb",
                               healthQuery: $"SELECT * FROM {logTableName} LIMIT 1")
                    .AddNpgSql(auditLogDbConnectionString, name: "AuditLogDb",
                               healthQuery: $"SELECT * FROM {auditLogTableName}  LIMIT 1");
                    break;

                case DatabaseProviderType.MySql:
                    healthChecksBuilder
                    .AddMySql(configurationDbConnectionString, name: "ConfigurationDb")
                    .AddMySql(persistedGrantsDbConnectionString, name: "PersistentGrantsDb")
                    .AddMySql(identityDbConnectionString, name: "IdentityDb")
                    .AddMySql(logDbConnectionString, name: "LogDb")
                    .AddMySql(auditLogDbConnectionString, name: "AuditLogDb");
                    break;

                default:
                    throw new NotImplementedException($"Health checks not defined for database provider {databaseProvider.ProviderType}");
                }
            }
        }
 public CheckUserExistence(IOptions <AdminConfiguration> adminSettings)
 {
     this.adminSettings = adminSettings.Value;
 }