Example #1
0
        public void Register(IAppHost appHost)
        {
            hasRegistered = true;
            AuthenticateService.Init(sessionFactory, AuthProviders);

            var unitTest = appHost == null;

            if (unitTest)
            {
                return;
            }

            if (HostContext.StrictMode)
            {
                var sessionInstance = sessionFactory();
                if (TypeSerializer.HasCircularReferences(sessionInstance))
                {
                    throw new StrictModeException($"User Session {sessionInstance.GetType().Name} cannot have circular dependencies", "sessionFactory",
                                                  StrictModeCodes.CyclicalUserSession);
                }
            }

            foreach (var registerService in ServiceRoutes)
            {
                appHost.RegisterService(registerService.Key, registerService.Value);
            }

            var sessionFeature = RegisterPlugins.OfType <SessionFeature>().First();

            sessionFeature.SessionExpiry          = SessionExpiry;
            sessionFeature.PermanentSessionExpiry = PermanentSessionExpiry;

            appHost.LoadPlugin(RegisterPlugins.ToArray());

            if (IncludeAuthMetadataProvider && appHost.TryResolve <IAuthMetadataProvider>() == null)
            {
                appHost.Register <IAuthMetadataProvider>(new AuthMetadataProvider());
            }

            AuthProviders.OfType <IAuthPlugin>().Each(x => x.Register(appHost, this));

            AuthenticateService.HtmlRedirect               = HtmlRedirect;
            AuthenticateService.HtmlRedirectAccessDenied   = HtmlRedirectAccessDenied;
            AuthenticateService.HtmlRedirectReturnParam    = HtmlRedirectReturnParam;
            AuthenticateService.HtmlRedirectReturnPathOnly = HtmlRedirectReturnPathOnly;
            AuthenticateService.AuthResponseDecorator      = AuthResponseDecorator;
        }
        public void Register(IAppHost appHost)
        {
            SessionFeature.DefaultSessionFactory = sessionFactory;
            AuthenticateService.Init(authProviders);

            var unitTest = appHost == null;

            if (unitTest)
            {
                return;
            }

            if (appHost.Config.StrictMode.GetValueOrDefault())
            {
                var sessionInstance = sessionFactory();
                if (TypeSerializer.HasCircularReferences(sessionInstance))
                {
                    throw new StrictModeException($"User Session {sessionInstance.GetType().Name} cannot have circular dependencies", "sessionFactory",
                                                  StrictModeCodes.CyclicalUserSession);
                }
            }

            foreach (var registerService in ServiceRoutes)
            {
                appHost.RegisterService(registerService.Key, registerService.Value);
            }

            var sessionFeature = RegisterPlugins.OfType <SessionFeature>().First();

            sessionFeature.SessionExpiry          = SessionExpiry;
            sessionFeature.PermanentSessionExpiry = PermanentSessionExpiry;

            appHost.LoadPlugin(RegisterPlugins.ToArray());

            if (IncludeAuthMetadataProvider && appHost.TryResolve <IAuthMetadataProvider>() == null)
            {
                appHost.Register <IAuthMetadataProvider>(new AuthMetadataProvider());
            }

            authProviders.OfType <IAuthPlugin>().Each(x => x.Register(appHost, this));

            AuthenticateService.HtmlRedirect          = HtmlRedirect;
            AuthenticateService.AuthResponseDecorator = AuthResponseDecorator;

            appHost.GetPlugin <MetadataFeature>()
            ?.AddLink(MetadataFeature.AvailableFeatures, "http://docs.servicestack.net/authentication-and-authorization", nameof(AuthFeature));
        }
Example #3
0
        public void Register(IAppHost appHost, AuthFeature feature)
        {
            var authRepo = appHost.TryResolve <IAuthRepository>().AsUserAuthRepository(appHost);
            var apiRepo  = authRepo as IManageApiKeys;

            if (apiRepo == null)
            {
                throw new NotSupportedException(apiRepo.GetType().Name + " does not implement IManageApiKeys");
            }

            feature.AuthEvents.Add(new ApiKeyAuthEvents(this));

            if (InitSchema)
            {
                apiRepo.InitApiKeySchema();
            }
        }
Example #4
0
        public void AfterPluginsLoaded(IAppHost appHost)
        {
            var authEvents = appHost.TryResolve <IAuthEvents>();

            if (authEvents == null)
            {
                authEvents = AuthEvents.Count == 0
                    ? new AuthEvents() :
                             AuthEvents.Count == 1
                    ? AuthEvents.First()
                    : new MultiAuthEvents(AuthEvents);

                appHost.GetContainer().Register(authEvents);
            }
            else if (AuthEvents.Count > 0)
            {
                throw new Exception("Registering IAuthEvents via both AuthFeature.AuthEvents and IOC is not allowed");
            }
        }
Example #5
0
        public void Register(IAppHost appHost)
        {
            if (appHost.TryResolve <IRedisClientsManager>() == null)
            {
                throw new Exception("Required IRedisClientsManager to be registered in IOC.");
            }
            appHost.RegisterService <RedisServiceDiscoveryServices>();
            appHost.AfterInitCallbacks.Add(StartBackgroundLoopTimer);
            appHost.OnDisposeCallbacks.Add(DisposeCallback);

            RedisNodeKey              = "{0}:node:{1}:{2}:{3}".Fmt(RedisPrefix, HostName, HostContext.ServiceName, NodeId);
            Config.NodeId             = NodeId;
            Config.HostName           = HostName;
            Config.ServiceName        = HostContext.ServiceName;
            Config.WebHostUrl         = appHost.Config.WebHostUrl;
            HostMasterInfo.WebHostUrl = Config.WebHostUrl;
            HostMasterInfo.NodeId     = Config.NodeId;
            appHost.GetContainer().Register <IServiceGatewayFactory>(c => new RedisServiceDiscoveryGateway()).ReusedWithin(Funq.ReuseScope.None);
        }
Example #6
0
        public void Register(IAppHost appHost, AuthFeature feature)
        {
            feature.AuthEvents.Add(new ApiKeyAuthEvents(this));

            if (InitSchema)
            {
                var dbFactory = appHost.TryResolve <IDbConnectionFactory>();

                if (dbFactory == null)
                {
                    throw new NotSupportedException("ApiKeyAuthProvider requires a registered OrmLite IDbConnectionFactory");
                }

                using (var db = dbFactory.OpenDbConnection())
                {
                    db.CreateTableIfNotExists <ApiKey>();
                }
            }
        }
Example #7
0
        public void Register(IAppHost appHost)
        {
            if (appHost.TryResolve <IRedisClientsManager>() == null)
            {
                throw new Exception("Required IRedisClientsManager to be registered in IOC.");
            }
            appHost.RegisterService <RedisServiceDiscoveryServices>();
            appHost.AfterInitCallbacks.Add(StartBackgroundLoopTimer);
            appHost.OnDisposeCallbacks.Add(DisposeCallback);

            RedisNodeKey              = NodeKeyFormatString.Fmt(RedisPrefix, HostName, HostContext.ServiceName, NodeId);
            RedisNodeRefreshKeySet    = NodeRefreshKeySetString.Fmt(RedisPrefix, HostName, HostContext.ServiceName, NodeId);
            Config.NodeId             = NodeId;
            Config.HostName           = HostName;
            Config.ServiceName        = HostContext.ServiceName;
            Config.WebHostUrl         = appHost.Config.WebHostUrl;
            HostMasterInfo.WebHostUrl = Config.WebHostUrl;
            HostMasterInfo.NodeId     = Config.NodeId;
            appHost.GetContainer().AddTransient <IServiceGatewayFactory>(c => new RedisServiceDiscoveryGateway());
        }
Example #8
0
        public void Register(IAppHost appHost)
        {
            AuthenticateService.Init(sessionFactory, authProviders);
            AuthenticateService.HtmlRedirect = HtmlRedirect;

            var unitTest = appHost == null;

            if (unitTest)
            {
                return;
            }

            foreach (var registerService in ServiceRoutes)
            {
                appHost.RegisterService(registerService.Key, registerService.Value);
            }

            appHost.LoadPlugin(RegisterPlugins.ToArray());

            if (IncludeAuthMetadataProvider && appHost.TryResolve <IAuthMetadataProvider>() == null)
            {
                appHost.Register <IAuthMetadataProvider>(new AuthMetadataProvider());
            }
        }
        public void AfterPluginsLoaded(IAppHost appHost)
        {
            var authEvents = appHost.TryResolve<IAuthEvents>();
            if (authEvents == null)
            {
                authEvents = AuthEvents.Count == 0
                    ? new AuthEvents() :
                      AuthEvents.Count == 1
                    ? AuthEvents.First()
                    : new MultiAuthEvents(AuthEvents);

                appHost.GetContainer().Register<IAuthEvents>(authEvents);
            }
            else if (AuthEvents.Count > 0)
            {
                throw new Exception("Registering IAuthEvents via both AuthFeature.AuthEvents and IOC is not allowed");
            }
        }
        public void Register(IAppHost appHost)
        {
            AuthenticateService.Init(sessionFactory, authProviders);
            AuthenticateService.HtmlRedirect = HtmlRedirect;

            var unitTest = appHost == null;
            if (unitTest) return;

            foreach (var registerService in ServiceRoutes)
            {
                appHost.RegisterService(registerService.Key, registerService.Value);
            }

            var sessionFeature = RegisterPlugins.OfType<SessionFeature>().First();
            sessionFeature.SessionExpiry = SessionExpiry;
            sessionFeature.PermanentSessionExpiry = PermanentSessionExpiry;

            appHost.LoadPlugin(RegisterPlugins.ToArray());

            if (IncludeAuthMetadataProvider && appHost.TryResolve<IAuthMetadataProvider>() == null)
                appHost.Register<IAuthMetadataProvider>(new AuthMetadataProvider());
        }
Example #11
0
        public void Register(IAppHost appHost)
        {
            appHost.RegisterService(typeof(AdminUsersService));

            appHost.AddToAppMetadata(meta => {
                var host     = (ServiceStackHost)appHost;
                var authRepo = host.GetAuthRepository();
                if (authRepo == null)
                {
                    return;
                }

                using (authRepo as IDisposable)
                {
                    IUserAuth userAuth = new UserAuth();
                    IUserAuthDetails userAuthDetails = new UserAuthDetails();
                    if (authRepo is ICustomUserAuth customUserAuth)
                    {
                        userAuth        = customUserAuth.CreateUserAuth();
                        userAuthDetails = customUserAuth.CreateUserAuthDetails();
                    }

                    var nativeTypesMeta = appHost.TryResolve <INativeTypesMetadata>() as NativeTypesMetadata
                                          ?? new NativeTypesMetadata(HostContext.AppHost.Metadata, new MetadataTypesConfig());
                    var metaGen = nativeTypesMeta.GetGenerator();

                    var plugin = meta.Plugins.AdminUsers = new AdminUsersInfo {
                        AccessRole              = AdminRole,
                        Enabled                 = new List <string>(),
                        UserAuth                = metaGen.ToFlattenedType(userAuth.GetType()),
                        UserAuthDetails         = metaGen.ToFlattenedType(userAuthDetails.GetType()),
                        AllRoles                = HostContext.Metadata.GetAllRoles(),
                        AllPermissions          = HostContext.Metadata.GetAllPermissions(),
                        QueryUserAuthProperties = QueryUserAuthProperties,
                    };
                    if (authRepo is IQueryUserAuth)
                    {
                        plugin.Enabled.Add("query");
                    }
                    if (authRepo is ICustomUserAuth)
                    {
                        plugin.Enabled.Add("custom");
                    }
                    if (authRepo is IManageRoles)
                    {
                        plugin.Enabled.Add("manageRoles");
                    }

                    if (IncludeUserAuthProperties != null)
                    {
                        var map = plugin.UserAuth.Properties.ToDictionary(x => x.Name);
                        plugin.UserAuth.Properties = new List <MetadataPropertyType>();
                        foreach (var includeProp in IncludeUserAuthProperties)
                        {
                            if (map.TryGetValue(includeProp, out var prop))
                            {
                                plugin.UserAuth.Properties.Add(prop);
                            }
                        }
                    }
                    if (IncludeUserAuthDetailsProperties != null)
                    {
                        var map = plugin.UserAuthDetails.Properties.ToDictionary(x => x.Name);
                        plugin.UserAuthDetails.Properties = new List <MetadataPropertyType>();
                        foreach (var includeProp in IncludeUserAuthDetailsProperties)
                        {
                            if (map.TryGetValue(includeProp, out var prop))
                            {
                                plugin.UserAuthDetails.Properties.Add(prop);
                            }
                        }
                    }
                }
            });
        }
Example #12
0
        public void Register(IAppHost appHost)
        {
            AuthenticateService.Init(sessionFactory, authProviders);
            AuthenticateService.HtmlRedirect = HtmlRedirect;

            var unitTest = appHost == null;
            if (unitTest) return;

            foreach (var registerService in ServiceRoutes)
            {
                appHost.RegisterService(registerService.Key, registerService.Value);
            }

            RegisterPlugins.ForEach(x => appHost.LoadPlugin(x));

            if (IncludeAuthMetadataProvider && appHost.TryResolve<IAuthMetadataProvider>() == null)
                appHost.Register<IAuthMetadataProvider>(new AuthMetadataProvider());
        }
Example #13
0
        public void Register(IAppHost appHost)
        {
            hasRegistered = true;
            AuthenticateService.Init(sessionFactory, AuthProviders);

            var unitTest = appHost == null;

            if (unitTest)
            {
                return;
            }

            if (HostContext.StrictMode)
            {
                var sessionInstance = sessionFactory();
                if (TypeSerializer.HasCircularReferences(sessionInstance))
                {
                    throw new StrictModeException($"User Session {sessionInstance.GetType().Name} cannot have circular dependencies", "sessionFactory",
                                                  StrictModeCodes.CyclicalUserSession);
                }
            }

            appHost.RegisterServices(ServiceRoutes);

            var sessionFeature = RegisterPlugins.OfType <SessionFeature>().First();

            sessionFeature.SessionExpiry          = SessionExpiry;
            sessionFeature.PermanentSessionExpiry = PermanentSessionExpiry;

            appHost.LoadPlugin(RegisterPlugins.ToArray());

            if (IncludeAuthMetadataProvider && appHost.TryResolve <IAuthMetadataProvider>() == null)
            {
                appHost.Register <IAuthMetadataProvider>(new AuthMetadataProvider());
            }

            AuthProviders.OfType <IAuthPlugin>().Each(x => x.Register(appHost, this));

            AuthenticateService.HtmlRedirect               = HtmlRedirect;
            AuthenticateService.HtmlRedirectAccessDenied   = HtmlRedirectAccessDenied;
            AuthenticateService.HtmlRedirectReturnParam    = HtmlRedirectReturnParam;
            AuthenticateService.HtmlRedirectReturnPathOnly = HtmlRedirectReturnPathOnly;
            AuthenticateService.AuthResponseDecorator      = AuthResponseDecorator;
            if (ValidateFn != null)
            {
                AuthenticateService.ValidateFn = ValidateFn;
            }

            var authNavItems = AuthProviders.Select(x => (x as AuthProvider)?.NavItem).Where(x => x != null);

            if (!ViewUtils.NavItemsMap.TryGetValue("auth", out var navItems))
            {
                ViewUtils.NavItemsMap["auth"] = navItems = new List <NavItem>();
            }

            var isDefaultHtmlRedirect = HtmlRedirect == "~/" + LocalizedStrings.Login.Localize();

            if (IncludeDefaultLogin && isDefaultHtmlRedirect && !appHost.VirtualFileSources.FileExists("/login.html"))
            {
                appHost.VirtualFileSources.GetMemoryVirtualFiles().WriteFile("/login.html",
                                                                             Templates.HtmlTemplates.GetLoginTemplate());
            }

            navItems.AddRange(authNavItems);

            appHost.AddToAppMetadata(meta => {
                meta.Plugins.Auth = new AuthInfo {
                    HasAuthSecret       = (appHost.Config.AdminAuthSecret != null).NullIfFalse(),
                    HasAuthRepository   = appHost.GetContainer().Exists <IAuthRepository>().NullIfFalse(),
                    IncludesRoles       = IncludeRolesInAuthenticateResponse.NullIfFalse(),
                    IncludesOAuthTokens = IncludeOAuthTokensInAuthenticateResponse.NullIfFalse(),
                    HtmlRedirect        = HtmlRedirect?.TrimStart('~'),
                    AuthProviders       = AuthenticateService.GetAuthProviders().Map(x => new MetaAuthProvider {
                        Type    = x.Type,
                        Name    = x.Provider,
                        NavItem = (x as AuthProvider)?.NavItem,
                        Meta    = x.Meta,
                    })
                };
            });
        }
Example #14
0
 public static ICacheClient GetCacheClient(this IAppHost appHost)
 {
     return(appHost.TryResolve <ICacheClient>()
            ?? (ICacheClient)appHost.TryResolve <IRedisClientsManager>()
            ?? DefaultCache);
 }
        public void Register(IAppHost appHost, AuthFeature feature)
        {
            var authRepo = appHost.TryResolve<IAuthRepository>().AsUserAuthRepository(appHost);
            var apiRepo = authRepo as IManageApiKeys;
            if (apiRepo == null)
                throw new NotSupportedException(apiRepo.GetType().Name + " does not implement IManageApiKeys");

            foreach (var registerService in ServiceRoutes)
            {
                appHost.RegisterService(registerService.Key, registerService.Value);
            }

            feature.AuthEvents.Add(new ApiKeyAuthEvents(this));

            if (InitSchema)
            {
                apiRepo.InitApiKeySchema();
            }
        }