Beispiel #1
0
            public override void Configure(Container container)
            {
                AuthFeature.Init(this, () => new CustomUserSession(),
                                 new AuthProvider[] {
                    new CredentialsAuthProvider(),                       //HTML Form post of UserName/Password credentials
                    new BasicAuthProvider(),                             //Sign-in with Basic Auth
                });

                container.Register <ICacheClient>(new MemoryCacheClient());
                var userRep = new InMemoryAuthRepository();

                container.Register <IUserAuthRepository>(userRep);

                string hash;
                string salt;

                new SaltedHash().GetHashAndSaltString(Password, out hash, out salt);

                userRep.CreateUserAuth(new UserAuth {
                    Id           = 1,
                    DisplayName  = "DisplayName",
                    Email        = "*****@*****.**",
                    UserName     = UserName,
                    FirstName    = "FirstName",
                    LastName     = "LastName",
                    PasswordHash = hash,
                    Salt         = salt,
                }, Password);
            }
        protected void InitTest(IUserAuthRepository userAuthRepository)
        {
            new RedisClient().FlushAll();
            ((IClearable)userAuthRepository).Clear();

            var appsettingsMock = new Mock <IResourceManager>();
            var appSettings     = appsettingsMock.Object;

            AuthFeature.Init(null, null, new IAuthProvider[]
            {
                new CredentialsAuthProvider(),
                new BasicAuthProvider(),
                new FacebookAuthProvider(appSettings),
                new TwitterAuthProvider(appSettings)
            });

            mockService = new Mock <IServiceBase>();
            mockService.Expect(x => x.TryResolve <IUserAuthRepository>()).Returns(userAuthRepository);
            requestContext = new MockRequestContext();
            mockService.Expect(x => x.RequestContext).Returns(requestContext);
            service = mockService.Object;

            registrationDto = new Registration {
                UserName    = "******",
                Password    = "******",
                Email       = "*****@*****.**",
                DisplayName = "DisplayName",
                FirstName   = "FirstName",
                LastName    = "LastName",
            };
        }
        public override void Configure(Container container)
        {
            SetConfig(new HostConfig {
                DebugMode = true
            });

            var authFeature = new AuthFeature(
                () => new AuthUserSession(),
                new IAuthProvider[] { new JwtAuthProviderReader(AppSettings) });

            var openIdDiscoveryUrl = "https://server.example.com/open_id_discovery_doc";

            var stubClient = new JsonHttpClient();

            stubClient.ResultsFilter = (responseType, httpMethod, requestUri, request) => {
                if (requestUri == openIdDiscoveryUrl)
                {
                    return(File.ReadAllText("content/sample_openid_discovery_document.json").FromJson <OpenIdDiscoveryDocument>());
                }

                if (requestUri == "https://server.example.com/jwks.json")
                {
                    return(File.ReadAllText("content/expected_jwks_RS512.json").FromJson <JsonWebKeySetResponse>());
                }
                return(null);
            };

            authFeature.RegisterPlugins.Add(new JwksFeature()
            {
                OpenIdDiscoveryUrl = openIdDiscoveryUrl,
                JwksClient         = stubClient
            });

            Plugins.Add(authFeature);
        }
Beispiel #4
0
            //Configure ServiceStack Authentication and CustomUserSession
            private void ConfigureAuth(Funq.Container container)
            {
                Routes
                .Add <Auth>("/auth")
                .Add <Auth>("/auth/{provider}")
                .Add <Registration>("/register");

                var appSettings = new AppSettings();

                AuthFeature.Init(this, () => new CustomUserSession(),
                                 new IAuthProvider[] {
                    new CredentialsAuthProvider(appSettings),
                    new FacebookAuthProvider(appSettings),
                    new TwitterAuthProvider(appSettings),
                    new BasicAuthProvider(appSettings),
                });

                RegistrationFeature.Init(this);

                container.Register <IUserAuthRepository>(c =>
                                                         new OrmLiteAuthRepository(c.Resolve <IDbConnectionFactory>()));

                var authRepo = (OrmLiteAuthRepository)container.Resolve <IUserAuthRepository>();

                if (new AppSettings().Get("Recr	eateTables", true))
                {
                    authRepo.DropAndReCreateTables();
                }
                else
                {
                    authRepo.CreateMissingTables();
                }
            }
Beispiel #5
0
        public void Register(IAppHost appHost, AuthFeature feature)
        {
            var isHmac = HmacAlgorithms.ContainsKey(HashAlgorithm);
            var isRsa  = RsaSignAlgorithms.ContainsKey(HashAlgorithm);

            if (!isHmac && !isRsa)
            {
                throw new NotSupportedException("Invalid algoritm: " + HashAlgorithm);
            }

            if (isHmac && AuthKey == null)
            {
                throw new ArgumentNullException("AuthKey", "An AuthKey is Required to use JWT, e.g: new JwtAuthProvider { AuthKey = AesUtils.CreateKey() }");
            }
            else if (isRsa && PrivateKey == null && PublicKey == null)
            {
                throw new ArgumentNullException("PrivateKey", "PrivateKey is Required to use JWT with " + HashAlgorithm);
            }

            if (KeyId == null)
            {
                KeyId = GetKeyId();
            }

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

            feature.AuthResponseDecorator = AuthenticateResponseDecorator;
        }
        public void Register(IAppHost appHost, AuthFeature feature)
        {
            var authRepo = HostContext.AppHost.GetAuthRepository();

            if (authRepo == null)
            {
                throw new NotSupportedException("ApiKeyAuthProvider requires a registered IAuthRepository");
            }

            if (!(authRepo is IManageApiKeys apiRepo))
            {
                throw new NotSupportedException(authRepo.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)
            {
                using (apiRepo as IDisposable)
                {
                    apiRepo.InitApiKeySchema();
                }
            }
        }
Beispiel #7
0
            public override void Configure(Container container)
            {
                AuthFeature.Init(this, () => new CustomUserSession(),
                                 new AuthConfig[] {
                    new CredentialsAuthConfig(),                       //HTML Form post of UserName/Password credentials
                    new BasicAuthConfig(),                             //Sign-in with Basic Auth
                });

                container.Register <ICacheClient>(new MemoryCacheClient());
                container.Register <IUserAuthRepository>(new InMemoryAuthRepository());
            }
        public void Register(IAppHost appHost, AuthFeature authFeature)
        {
            if (!OverrideHtmlRedirect)
            {
                return;
            }

            // defaults: https://github.com/aspnet/Security/blob/master/src/Microsoft.AspNetCore.Authentication.Cookies/CookieAuthenticationDefaults.cs
            authFeature.HtmlRedirect               = "~/Account/Login";
            authFeature.HtmlRedirectReturnParam    = "ReturnUrl";
            authFeature.HtmlRedirectReturnPathOnly = true;
        }
Beispiel #9
0
        public override void Configure(Funq.Container container)
        {
            SetConfig(new EndpointHostConfig
            {
                DebugMode = false,

                GlobalResponseHeaders =
                {
                    { "Access-Control-Allow-Origin",  "*"                               },
                    { "Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS" }
                },

                EnableFeatures = ServiceStack.ServiceHost.Feature.All,

                ServiceStackHandlerFactoryPath = "api"
            });

            ServiceStack.Text.JsConfig.EmitCamelCaseNames = true;

            var appSettings = new AppSettings();

            AppConfig = new AppConfig(appSettings);

            container.Register(AppConfig);

            container.Register <ICacheClient>(new MemoryCacheClient());

            AdzCredenticalsProvider authProvider = new AdzCredenticalsProvider();

            Plugins.Add(new SessionFeature());

            AuthFeature authFeature = new AuthFeature(() => new AuthUserSession(), new IAuthProvider[] {
                authProvider, new BasicAuthProvider()
            });

            Plugins.Add(authFeature);

            //Plugins.Add(new RegistrationFeature());

            dbFactory = GetDbConnectionFromConfig();
            container.Register <IDbConnectionFactory>(dbFactory);
            DatabaseConnection = dbFactory.OpenDbConnection();
            container.Register(c => dbFactory.OpenDbConnection()).ReusedWithin(Funq.ReuseScope.Container);

            Helper.Common.ORMCreateTableOnInit(DatabaseConnection, "admin");

            var userRep = new ABORMLiteAuthRepository(dbFactory);

            container.Register <IAuthProvider>(authProvider);

            container.Register <IUserAuthRepository>(userRep);
        }
        private void ConfigureAuthentication()
        {
            var authProviders = new IAuthProvider[]
            {
                new ServiceStackCredentialsAuthAdapter(this.unityContainer)
            };
            var authFeature = new AuthFeature(() => new AuthUserSession(), authProviders)
            {
                IncludeAssignRoleServices = false
            };

            this.Plugins.Add(authFeature);
        }
Beispiel #11
0
            public override void Configure(Container container)
            {
                var db = new FakeDataStore();

                container.Register <IDataStore>(c => db).ReusedWithin(ReuseScope.Container);
                JsConfig.ExcludeTypeInfo = true;

                var auth = new AuthFeature(() => new AuthUserSession(), new IAuthProvider[] { new RestivalAuthProvider(db) })
                {
                    HtmlRedirect = null
                };

                Plugins.Add(auth);
            }
        public PMSApplication(TestCaseHeaderData headerData, string userName = "", string password = "")
        {
            executioner = TestExecutionerPool.GetTestExecutioner(headerData, userName, password, landingPage);

            if (!executioner.PoolState.WasAlreadyInPool)
            {
                executioner.NavigateTo(loginURL, "Navigate to Patitnet management system's login page");

                if (!(string.IsNullOrEmpty(userName) && string.IsNullOrEmpty(password)))
                {
                    this.IsAuthenticated = AuthFeature.LoginToPMS(userName, password);
                }
            }
        }
Beispiel #13
0
            public override void Configure(Container container)
            {
                //Plugins.Add(new AuthFeature(() => new AuthUserSession(), new IAuthProvider[] { container.Resolve<IRenewablesAuthProvider>() }));
                var authFeature = new AuthFeature(() => new AuthUserSession(), new IAuthProvider[]
                {
                    new CustomCredentialsAuthProvider(container.Resolve <IClientRepository>(), container.Resolve <IMembershipProvider>()),
                    new BasicAuthProvider()
                });

                authFeature.IncludeAssignRoleServices = false;
                Plugins.Add(authFeature);

                container.Register <ICacheClient>(new MemoryCacheClient());
            }
        public void Register(IAppHost appHost, AuthFeature authFeature)
        {
            if (AutoSignInSessions)
            {
                ((AppHostBase)appHost).BeforeNextMiddleware = SignInAuthenticatedSessions;
            }

            if (OverrideHtmlRedirect)
            {
                // defaults: https://github.com/aspnet/Security/blob/master/src/Microsoft.AspNetCore.Authentication.Cookies/CookieAuthenticationDefaults.cs
                authFeature.HtmlRedirect               = "~/Account/Login";
                authFeature.HtmlRedirectReturnParam    = "ReturnUrl";
                authFeature.HtmlRedirectReturnPathOnly = true;
            }
        }
        public override void Configure(Container container)
        {
            container.Register <IUserAuthRepository>(new InMemoryAuthRepository());

            var authFeature = new AuthFeature(() => new AuthUserSession(),
                                              new IAuthProvider[] {
                new JwtAuthProvider {
                    PrivateKeyXml      = AppSettings.Get <string>("jwt.RS512.PrivateKeyXml"),
                    FallbackPublicKeys = AppSettings.Get <List <string> >("jwt.RS512.FallbackKeys").Select(x => x.ToPublicRSAParameters()).ToList(),
                    HashAlgorithm      = "RS512"
                }
            });

            authFeature.RegisterPlugins.Add(new JwksFeature());
            Plugins.Add(authFeature);
        }
Beispiel #16
0
        public override void Configure(Container container)
        {
            container.Register <IUserAuthRepository>(new InMemoryAuthRepository());

            var authFeature = new AuthFeature(() => new AuthUserSession(),
                                              new IAuthProvider[] {
                new JwtAuthProvider {
                    PrivateKeyXml = AppSettings.Get <string>("jwt.RS256.PrivateKeyXml"),
                    HashAlgorithm = "RS256",
                    Issuer        = "https://server.example.com"
                }
            });

            authFeature.RegisterPlugins.Add(new JwksFeature());
            Plugins.Add(authFeature);
        }
Beispiel #17
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();
            }
        }
Beispiel #18
0
        public static void Configure(ServiceStackHost appHost, Container container)
        {
            var appSettings = new AppSettings();

            var auth = new AuthFeature(() => new CustomUserSession(),
                                       new IAuthProvider[]
            {
                new CustomBasicAuthProvider(),
                new CredentialsAuthProvider(appSettings)
                {
                    SessionExpiry = TimeSpan.FromMinutes(30)
                }
            },
                                       "/login")
            {
                GenerateNewSessionCookiesOnAuthentication = false,
            };

            appHost.Plugins.Add(auth);

            IUserAuthRepository authRepository = new InMemoryAuthRepository();
            ICacheClient        cacheClient    = new MemoryCacheClient();

            var testUser = authRepository.CreateUserAuth(new UserAuth {
                Email = "*****@*****.**"
            }, "a");


            //IoC registrations
            container.Register(cacheClient);
            container.Register(authRepository);


            var hostConfig = new HostConfig
            {
#if DEBUG || STAGING || UAT
                DebugMode = true,
#endif
                AppendUtf8CharsetOnContentTypes = new HashSet <string> {
                    MimeTypes.Csv
                },
            };


            appHost.SetConfig(hostConfig);
        }
Beispiel #19
0
        public override void Register(IAppHost appHost, AuthFeature feature)
        {
            base.Register(appHost, feature);
            var manageApiKeys = HostContext.AppHost.AssertManageApiKeysAsync();

            using (manageApiKeys as IDisposable)
            {
                if (InitSchema)
                {
                    manageApiKeys.InitApiKeySchema();
                }
            }

            appHost.RegisterServices(ServiceRoutes);

            feature.AuthEvents.Add(new ApiKeyAuthEvents(this));
        }
Beispiel #20
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>();
                }
            }
        }
 public static void Initialize(Settings settings)
 {
     Settings    = settings;
     JWTProvider = new JwtAuthProvider()
     {
         AuthKeyBase64           = Settings.Auth.SigningKey,
         ExpireTokensIn          = TimeSpan.FromMinutes(Settings.Auth.TokenValidityMinutes),
         CreatePayloadFilter     = CreatePayload,
         PopulateSessionFilter   = PopulateSession,
         RequireSecureConnection = false
     };
     AuthFeature = new AuthFeature(
         () => new UserSession(),
         new[] {
         JWTProvider
     })
     {
         HtmlRedirect = null, IncludeAssignRoleServices = false
     };
 }
        public PMSApplication(string testNumber, string testName = "", string testDescription = "", string testFamily = "", string userName = "", string password = "")
        {
            TestCaseHeaderData tcHeader = new TestCaseHeaderData()
            {
                TestName        = string.Format("{0}_{1}", testNumber, testName.Replace(" ", "_")),
                TestNumber      = testNumber,
                TestDescription = testDescription
            };

            executioner = TestExecutionerPool.GetTestExecutioner(tcHeader, userName, password, landingPage);

            if (!executioner.PoolState.WasAlreadyInPool)
            {
                executioner.NavigateTo(loginURL, "Navigate to Patitnet management system's login page");

                if (!(string.IsNullOrEmpty(userName) && string.IsNullOrEmpty(password)))
                {
                    this.IsAuthenticated = AuthFeature.LoginToPMS(userName, password);
                }
            }
        }
Beispiel #23
0
            public override void Configure(Funq.Container container)
            {
                Routes
                .Add <Hello>("/hello")
                .Add <Hello>("/hello/{Name}");
                helloService = container.Resolve <HelloService>();

                AuthFeature authFeature = new AuthFeature(() => new AuthUserSession(), new IAuthProvider[] { new BasicAuthProvider(), new TwitterAuthProvider(new AppSettings()), });

                //authFeature.HtmlRedirect
                Plugins.Add(authFeature);
                MemoryCacheClient memoryCacheClient = new MemoryCacheClient();

                container.Register <ICacheClient>(memoryCacheClient);

                var userRepository = new InMemoryAuthRepository();

                container.Register <IUserAuthRepository>(userRepository);

                string hash;
                string salt;
                string password = "******";

                new SaltedHash().GetHashAndSaltString(password, out hash, out salt);
                userRepository.CreateUserAuth(
                    new UserAuth {
                    Id           = 1,
                    DisplayName  = "JoeUser",
                    Email        = "*****@*****.**",
                    UserName     = "******",
                    FirstName    = "Joe",
                    LastName     = "User",
                    PasswordHash = hash,
                    Salt         = salt,
                }, password);
                //IHttpResult authenticationRequired = helloService.AuthenticationRequired(); // ????
            }
Beispiel #24
0
        public override void Configure(Container container)
        {
            var authFeature = new AuthFeature(() => new AuthUserSession(),
                                              new IAuthProvider[]
            {
                new CredentialsAuthProvider(AppSettings),
                new AzureAuthenticationProvider(new TestAzureGraphService())
                {
                }
            });

            Plugins.Add(authFeature);

            container.Register <IDbConnectionFactory>(
                new OrmLiteConnectionFactory(":memory:", SqliteDialect.Provider));
            container.Register <IApplicationRegistryService>(
                c => new OrmLiteMultiTenantApplicationRegistryService(c.Resolve <IDbConnectionFactory>()));
            container.Register <IAuthRepository>(
                c => new OrmLiteAuthRepository(c.Resolve <IDbConnectionFactory>()));


            AfterInitCallbacks.Add(appHost =>
            {
                var authRepo = appHost.TryResolve <IAuthRepository>();
                authRepo.InitSchema();

                var regService = appHost.TryResolve <IApplicationRegistryService>();
                regService.InitSchema();
                regService.RegisterApplication(new ApplicationRegistration
                {
                    ClientId      = "clientid",
                    ClientSecret  = "clientsecret",
                    DirectoryName = "foodomain.com"
                });
            });
        }
Beispiel #25
0
 public virtual void Register(IAppHost appHost, AuthFeature feature)
 {
     RestoreSessionFromState ??= appHost.Config.UseSameSiteCookies == true;
 }
Beispiel #26
0
        public override void Configure(Funq.Container container)
        {
            var host = ConfigurationManager.AppSettings.Get("PaypalWebsiteURL");

            SetConfig(new EndpointHostConfig
            {
                DebugMode = false, // Debugmode for stacktrace

                GlobalResponseHeaders =
                {
                    { "Access-Control-Allow-Origin",  "*"                               },
                    { "Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS" }
                },
                //EnableFeatures = Feature.All.Remove(GetDisabledFeatures()),
                EnableFeatures = ServiceStack.ServiceHost.Feature.All,
                //RestrictAllCookiesToDomain = "www.photobookmart.com"
                //ServiceStackHandlerFactoryPath = "api",
                //AppendUtf8CharsetOnContentTypes = new HashSet<string> { ContentType.Html },
            });

            //Set JSON web services to return idiomatic JSON camelCase properties
            ServiceStack.Text.JsConfig.EmitCamelCaseNames = false;

            //Register a external dependency-free
            //container.Register<ICacheClient>(new MemoryCacheClient());

            /* TODO:...
             * var redis_host = ConfigurationManager.AppSettings.Get("RedisHost");
             * var redis_db = long.Parse(ConfigurationManager.AppSettings.Get("RedisDBVersion"));
             * var pooled_redis = new PooledRedisClientManager(redis_db, redis_host);
             * pooled_redis.NamespacePrefix = System.Reflection.Assembly.GetExecutingAssembly().FullName;
             * container.Register<IRedisClientsManager>(c => pooled_redis);
             * container.Register<ICacheClient>(c =>
             *  (ICacheClient)c.Resolve<IRedisClientsManager>()
             *  .GetCacheClient())
             *  .ReusedWithin(Funq.ReuseScope.None);*/


            //Enable Authentication an Registration
            VMCCredenticalsProvider authProvider = new VMCCredenticalsProvider();

            Plugins.Add(new SessionFeature());
            AuthFeature authFeature = new AuthFeature(() => new AuthUserSession(), new IAuthProvider[] {
                authProvider, new BasicAuthProvider()
            });

            //authFeature.ServiceRoutes.Clear(); // we clear all routes
            Plugins.Add(authFeature);
            Plugins.Add(new RegistrationFeature());


            //Create a DB Factory configured to access the UserAuth SQL Server DB
            dbFactory = GetDbConnectionFromConfig();
            //container.Register(c => GetDbConnectionFromConfig()).ReusedWithin(Funq.ReuseScope.Container);
            //var dbConnection = container.Resolve<OrmLiteConnectionFactory>();
            container.Register <IDbConnectionFactory>(dbFactory);
            //container.Register(c => GetDbConnectionFromConfig()).ReusedWithin(Funq.ReuseScope.Request);

            // register db connection
            //container.Register(c => dbFactory.OpenDbConnection()).ReusedWithin(Funq.ReuseScope.Container);
            DatabaseConnection = dbFactory.OpenDbConnection();
            container.Register(c => dbFactory.OpenDbConnection()).ReusedWithin(Funq.ReuseScope.Container);
            //container.Register<IDbConnection>(DatabaseConnection);
            // caching  - TODO: later must change to ORMLiteCache
            //container.RegisterAs<OrmLiteCacheClient, ICacheClient>();
            //Create 'CacheEntry' RDBMS table if it doesn't exist already
            //container.Resolve<ICacheClient>().InitSchema();
            // end of caching register

            // create tables
            ModelBase.InitDbTable(ConfigurationManager.AppSettings.Get("AdminUserNames"), true, true);

            //container.RegisterAutoWired<IDbConnection>();
            //container.Register<IDbConnectionFactory>(dbConnection);
            // Register ORM Lite Authentication Repository with our Authentication
            var userRep = new ABORMLiteAuthRepository(dbFactory);

            container.Register <IAuthProvider>(authProvider);
            container.Register <IUserAuthRepository>(userRep);

            //Configure Custom User Defined REST Paths for your services
            ConfigureServiceRoutes();

            //Set MVC to use the same Funq IOC as ServiceStack
            ControllerBuilder.Current.SetControllerFactory(new FunqControllerFactory(container));
            //ServiceStackController.CatchAllController = reqCtx => container.TryResolve<HomeController>();
        }
Beispiel #27
0
        public override void Configure(Container container)
        {
            this.ServiceExceptionHandlers.Add((httpReq, request, exception) =>
            {
                httpReq.Items["__exception"] = exception;
                return(new HttpError {
                    Status = exception.ToStatusCode()
                });
            });

            //Handle Unhandled Exceptions occurring outside of Services
            //E.g. Exceptions during Request binding or in filters:
            this.UncaughtExceptionHandlers.Add((httpReq, res, operationName, exception) =>
            {
                if (res.StatusCode == 200)
                {
                    res.StatusCode = exception.ToStatusCode();
                }
                res.EndRequest();
            });

            Plugins.Add(new ValidationFeature());

            var hostConfig = new HostConfig
            {
                IgnoreFormatsInMetadata = new HashSet <string> {
                    "xml", "csv", "jsv"
                },
                DefaultContentType = MimeTypes.Json,
            };

            hostConfig.MapExceptionToStatusCode.Add(typeof(CryptographicException), 401);
            SetConfig(hostConfig);

            this.Plugins.Add(new PostmanFeature()
            {
                DefaultLabelFmt = new List <string> {
                    "route", " - ", "type:english"
                },
            });
            this.Plugins.Add(new CorsFeature(allowedHeaders: "Content-Type,Authorization,x-client-version"));

            var privateKey = _settings.GetString("Security:PrivateKeyXml");//Получение закрытого ассиметричного ключа из конфига

            //Для генерации ключей
            //var keys = RsaUtils.CreatePublicAndPrivateKeyPair(RsaKeyLengths.Bit4096);

            var requireSecureConnectionStr = _settings.GetString("Security:RequireSecureConnection");

            bool.TryParse(requireSecureConnectionStr, out var requireSecureConnection);

            var jwtprovider = new JwtAuthProvider(_settings)
            {
                RequireSecureConnection = requireSecureConnection,//требуется защищённое соединение
                HashAlgorithm           = "RS512",
                PrivateKeyXml           = privateKey,
                EncryptPayload          = true, //шифрование токена
                ExpireTokensInDays      = 1,    //срок жизни токена
                ExpireRefreshTokensIn   = TimeSpan.FromDays(30),
                AllowInQueryString      = true, //токен можно передавать в параметрах как ?ss-tok
                AllowInFormData         = true, //токен можно передавать в теле как ss-tok
                PopulateSessionFilter   = (session, o, arg3) =>
                {
                    if (o.TryGetValue("session", out var sessionid))
                    {
                        if (session is AuthUserSession ses)
                        {
                            ses.Id = sessionid;
                        }
                    }
                }
            };

            if (_env.IsDevelopment())                        //при отладке
            {
                jwtprovider.RequireSecureConnection = false; //выключить требование защищённого соединения
            }

            jwtprovider.ServiceRoutes?.Clear();//Отключаю стандартные методы
            var authFeature = new AuthFeature(() => new AuthUserSession(),
                                              new IAuthProvider[]
            {
                jwtprovider,
            })
            {
                IncludeAssignRoleServices   = false,
                IncludeAuthMetadataProvider = false,
                IncludeRegistrationService  = false,
            };

            authFeature.ServiceRoutes.Clear();//Отключаю стандартные методы
            Plugins.Add(authFeature);

            Plugins.Add(new OpenApiFeature {
                UseBearerSecurity = true
            });
            Plugins.Add(new SwaggerFeature {
                UseCamelCaseModelPropertyNames = true, UseBootstrapTheme = true
            });
        }
    }
Beispiel #28
0
        public void Register(IAppHost appHost, AuthFeature feature)
        {
            var authRepo = HostContext.AppHost.GetAuthRepository();
            if (authRepo == null)
                throw new NotSupportedException("ApiKeyAuthProvider requires a registered IAuthRepository");

            var apiRepo = authRepo as IManageApiKeys;
            if (apiRepo == null)
                throw new NotSupportedException(authRepo.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)
            {
                using (apiRepo as IDisposable)
                {
                    apiRepo.InitApiKeySchema();
                }
            }
        }
        // Configure your AppHost with the necessary configuration and dependencies your App needs
        public override void Configure(Container container)
        {
            SetConfig(new HostConfig
            {
                DefaultRedirectPath = "/index.html",
                DebugMode           = AppSettings.Get(nameof(HostConfig.DebugMode), false)
            });
            JsConfig.IncludeNullValues = false;
            JsConfig.ExcludeTypeInfo   = true;
            JsConfig.DateHandler       = DateHandler.ISO8601;
            JsConfig.TextCase          = TextCase.PascalCase;
            JsConfig.TimeSpanHandler   = TimeSpanHandler.StandardFormat;
            #region Database
            var connString = AppSettings.Get("dbConnectionString", "");
            if (connString == "%%CONN_STR%%")
            {
                connString = AppSettings.Get("dbConnectionStringDev", "");
            }
            var dbFactory = new OrmLiteConnectionFactory(connString, SqlServer2008Dialect.Provider);
            container.Register <IDbConnectionFactory>(dbFactory);
            OrmLiteConfig.StringFilter = s => s.Trim();
            #endregion
            #region Plugins
            Plugins.Add(new CorsFeature(
                            allowedHeaders: "Content-Type, Allow, Authorization"));
            Plugins.Add(new OpenApiFeature()
            {
                ApiDeclarationFilter = declaration =>
                {
                    declaration.Info.Title = "Badges Molex Net Core";
                    //declaration.Info.Contact = new ServiceStack.Api.OpenApi.Specification.OpenApiContact()
                    //{
                    //    Email = "*****@*****.**",
                    //    Name = "Alfredo Pacheco"
                    //};
                    declaration.Info.Description = "";
                },
                OperationFilter = (verb, op) =>
                {
                    switch (verb)
                    {
                    case "POST":
                        op.Parameters.RemoveAll(p => p.Name == "Id");
                        op.Parameters.RemoveAll(p => p.Name == "RowVersion");
                        break;

                    default:
                        break;
                    }
                    op.Parameters.RemoveAll(p => p.Name == "EntityName");
                    op.Parameters.RemoveAll(p => p.Name == "EF_State");
                }
            });
            Plugins.Add(new AutoQueryFeature
            {
                //MaxLimit = 100
            });
            Plugins.Add(new RequestLogsFeature());
            Plugins.Add(new AdminFeature());
            // var rollbarSettings = AppSettings.Get<RollbarSettings>("RollbarPluginSettings");
            // Plugins.Add(new RollbarLoggerPlugin
            // {
            //     ApiKey = rollbarSettings.ApiKey,
            //     Enabled = rollbarSettings.Enabled,
            //     EnableErrorTracking = rollbarSettings.EnableErrorTracking,
            //     EnableRequestBodyTracking = rollbarSettings.EnableRequestBodyTracking,
            //     EnableResponseTracking = rollbarSettings.EnableResponseTracking,
            //     EnableSessionTracking = rollbarSettings.EnableSessionTracking,
            //     Environment = rollbarSettings.Environment,
            //     // HideRequestBodyForRequestDtoTypes = new List<Type>(),
            //     // ExcludeRequestDtoTypes = new List<Type>
            //     // {
            //     //         // Might have to exclude the Swagger requests to get the two to play nicely
            //     //     typeof(RollbarLogConfigRequest),
            //     //     typeof(SwaggerResource),
            //     //     typeof(SwaggerApiDeclaration)
            //     // },
            //     RequiredRoles = rollbarSettings.RequiredRoles,
            //     SkipLogging = IsRequestSkippedDuringRequestLogging
            // });
            #endregion
            #region Auth
            var authProviders = new List <IAuthProvider>
            {
                new JwtAuthProvider(AppSettings)
                {
                    RequireSecureConnection = false,
                    AllowInQueryString      = true
                },
                new CredentialsAuthProvider()
            };
            var authFeature = new AuthFeature(SessionFactory, authProviders.ToArray());
            Plugins.Add(authFeature);
            //var authRepo = new OrmLiteAuthRepository(dbFactory);
            //container.Register<IUserAuthRepository>(authRepo);
            //authRepo.InitSchema();
            //Plugins.Add(new RegistrationFeature());
            //var admin = authRepo.GetUserAuthByUserName("admin");
            //if (admin == null)
            //    authRepo.CreateUserAuth(new UserAuth
            //    {
            //        UserName = "******",
            //        Roles = new List<string> { RoleNames.Admin }
            //    }, "admin");
            #endregion
            //TODO:
            //Cache.
            //Logging.
            //Batched requests.
            //Profiler.
            //Versioning.
            //stripe.com
            #region Cache
            //container.Register<ICacheClient>(new MemoryCacheClient());
            #endregion
            #region App
            //container.Register(c => dbFactory.Open());
            //container.Register(c => c.Resolve<IDbConnectionFactory>().OpenDbConnection()).ReusedWithin(ReuseScope.Request);
            container.RegisterAutoWired <RevisionLogic>().ReusedWithin(ReuseScope.Request);
            MailgunService.AppSettings = AppSettings;
            container.Register <IEmailService>(i => new MailgunService()).ReusedWithin(ReuseScope.Request);
            container.RegisterAutoWired <CatalogLogic>().ReusedWithin(ReuseScope.Request);
            container.RegisterAutoWired <CatalogDefinitionLogic>().ReusedWithin(ReuseScope.Request);
            container.RegisterAutoWired <FieldLogic>().ReusedWithin(ReuseScope.Request);
            container.RegisterAutoWired <CatalogFieldValueLogic>().ReusedWithin(ReuseScope.Request);
            //This App:
            ///start:generated:di<<<
            container.RegisterAutoWired <ActivityLogic>().ReusedWithin(ReuseScope.Request);
            container.RegisterAutoWired <ApprovalLogic>().ReusedWithin(ReuseScope.Request);
            container.RegisterAutoWired <BadgeLogic>().ReusedWithin(ReuseScope.Request);
            container.RegisterAutoWired <EmailLogic>().ReusedWithin(ReuseScope.Request);
            container.RegisterAutoWired <AdvancedSortLogic>().ReusedWithin(ReuseScope.Request);
            container.RegisterAutoWired <ApplicationTaskLogic>().ReusedWithin(ReuseScope.Request);
            container.RegisterAutoWired <FilterDataLogic>().ReusedWithin(ReuseScope.Request);
            container.RegisterAutoWired <SortDataLogic>().ReusedWithin(ReuseScope.Request);
            container.RegisterAutoWired <TokenLogic>().ReusedWithin(ReuseScope.Request);
            ///end:generated:di<<<
            #endregion

            #region Seed Data
            Sower.Seed(dbFactory);
            #endregion
        }
Beispiel #30
0
        public override void Configure(Container container)
        {
            JsConfig.DateHandler = DateHandler.ISO8601;

            var appSettings = new AppSettings();

            ServiceExceptionHandlers.Add((httpReq, request, exception) =>
            {
                var logger = LogManager.GetLogger(GetType());
                logger.Error(exception);
                return(null);
            });


            container.Register <ICacheClient>(new MemoryCacheClient {
                FlushOnDispose = false
            });


            JsConfig.AssumeUtc = true;

            container.RegisterAs <FordereAuthEventHandler, IAuthEvents>();

            container.Register <IDbConnectionFactory>(
                new OrmLiteConnectionFactory(
                    "Server = {0}; Database = {1}; Uid = {2}; Pwd = {3}".Fmt(
                        appSettings.Get("DB.Host"),
                        appSettings.Get("DB.Name"),
                        appSettings.Get("DB.User"),
                        appSettings.Get("DB.Pass")),
                    MySqlDialect.Provider));

            container.Register <IUserAuthRepository>(c => new OrmLiteAuthRepository(c.Resolve <IDbConnectionFactory>()));

            var authProvider = new IAuthProvider[]
            {
                new CredentialsAuthProvider(),
                new JwtAuthProvider(appSettings),
            }.ToList();

            if (appSettings.Get("Debug", false))
            {
                authProvider.Add(new BasicAuthProvider());
            }

            var authFeature = new AuthFeature(() => new FordereAuthUserService(), authProvider.ToArray());

            this.Plugins.Add(new RegistrationFeature());
            this.Plugins.Add(authFeature);


            this.Plugins.Add(new RequestLogsFeature
            {
                // do not log request bodies of requests containing passwords
                HideRequestBodyForRequestDtoTypes = new[] { typeof(Authenticate), typeof(Register), typeof(UpdateUserProfileRequest) },
            });

            if (appSettings.Get("CORS.Enabled", false))
            {
                this.Plugins.Add(
                    new CorsFeature(
                        allowedOrigins: appSettings.GetString("CORS.AllowedOrigins"),
                        allowedMethods: "OPTIONS,GET,POST,PUT,DELETE,PATCH",
                        allowedHeaders: "Content-Type,Authorization,division_id",
                        allowCredentials: true));
            }

            if (appSettings.Get("Debug", false))
            {
                this.Plugins.Add(new PostmanFeature());
                this.Plugins.Add(new OpenApiFeature());
            }

            if (appSettings.Get("Debug", false) == false)
            {
                this.Plugins.RemoveAll(x => x is MetadataFeature);
            }

            this.SetConfig(new HostConfig
            {
                // TODO SSH This sets ss-pid/ss-opt to NOT HttpOnly.. is this a security issue?
                AllowNonHttpOnlyCookies = true,
                DebugMode = appSettings.Get("Debug", false)
            });

            this.RegisterTypedRequestFilter <ICaptchaRequest>(Filter.Captcha);
            this.RegisterTypedRequestFilter <EnterMatchAppointmentRequest>(Filter.EnterMatchAppointment);
            this.RegisterTypedRequestFilter <EnterMatchResultRequest>(Filter.EnterMatchResult);

            this.RegisterTypedResponseFilter <TeamDto>(Filter.TeamPlayerDetails);

            PreRequestFilters.Add((httpReq, httpRes) =>
            {
                if (httpReq.Verb.ToUpper() == "PATCH")
                {
                    httpReq.UseBufferedStream = true;
                }
            });
        }
        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();
            }
        }
Beispiel #32
0
        public void PreRegister(AppHostBase appHost, Container container)
        {
            var dbFactory   = container.TryResolve <IDbConnectionFactory>();
            var appSettings = container.TryResolve <IAppSettings>();

            if (dbFactory == null || appSettings == null)
            {
                return; // missing required dependencies
            }
            var authProviders = new List <IAuthProvider>();

            authProviders.Add(new CredentialsAuthProvider(appSettings));
            authProviders.Add(new BasicAuthProvider(appSettings));

            var apiKeyProvider = new ApiKeyAuthProvider(appSettings)
            {
                RequireSecureConnection = false,
                ServiceRoutes           = new Dictionary <Type, string[]>
                {
                    { typeof(GetApiKeysService), new[] { "/auth/apikeys", "/auth/apikeys/{Environment}" } },
                    { typeof(RegenerateApiKeysService), new [] { "/auth/apikeys/regenerate", "/auth/apikeys/regenerate/{Environment}" } },
                }
            };

            authProviders.Add(apiKeyProvider);

            var privateKeyXml = (appSettings as OrmLiteAppSettings)?.GetOrCreate("PrivateKeyXml", () => {
                return(RsaUtils.CreatePrivateKeyParams().ToPrivateKeyXml());
            });

            if (!string.IsNullOrWhiteSpace(privateKeyXml))
            {
                authProviders.Add(new JwtAuthProvider(appSettings)
                {
                    PrivateKeyXml           = privateKeyXml,
                    HashAlgorithm           = "RS256",
                    RequireSecureConnection = false,
                    SetBearerTokenOnAuthenticateResponse      = true,
                    IncludeJwtInConvertSessionToTokenResponse = true,
                    ServiceRoutes = new Dictionary <Type, string[]>
                    {
                        { typeof(ConvertSessionToTokenService), new[] { "/auth/session-to-token" } },
                        { typeof(GetAccessTokenService), new[] { "/auth/access-token" } },
                    }
                });
            }

            var authRepository = new AppAuthRepository(dbFactory);

            authRepository.InitSchema();
            authRepository.InitApiKeySchema();
            appHost.Register <IUserAuthRepository>(authRepository);
            appHost.Register <IAuthRepository>(authRepository);

            var authFeature = new AuthFeature(() => new AppUserSession(), authProviders.ToArray())
            {
                IncludeRegistrationService   = false,
                IncludeAssignRoleServices    = false,
                DeleteSessionCookiesOnLogout = true,
                GenerateNewSessionCookiesOnAuthentication = true,
                SaveUserNamesInLowerCase = true,
                ValidateUniqueEmails     = true,
                ValidateUniqueUserNames  = true
            };

            authFeature.ServiceRoutes[typeof(AuthenticateService)] =
                authFeature.ServiceRoutes[typeof(AuthenticateService)].Where(r =>
                                                                             !r.Contains("authenticate")).ToArray();

            appHost.Plugins.Add(authFeature);

            var regFeature = new RegistrationFeature
            {
                AllowUpdates = false,
                AtRestPath   = "/auth/register"
            };

            appHost.Plugins.Add(regFeature);
        }
        public void Register(IAppHost appHost, AuthFeature feature)
        {
            var isHmac = HmacAlgorithms.ContainsKey(HashAlgorithm);
            var isRsa = RsaSignAlgorithms.ContainsKey(HashAlgorithm);
            if (!isHmac && !isRsa)
                throw new NotSupportedException("Invalid algoritm: " + HashAlgorithm);

            if (isHmac && AuthKey == null)
                throw new ArgumentNullException("AuthKey", "An AuthKey is Required to use JWT, e.g: new JwtAuthProvider { AuthKey = AesUtils.CreateKey() }");
            else if (isRsa && PrivateKey == null && PublicKey == null)
                throw new ArgumentNullException("PrivateKey", "PrivateKey is Required to use JWT with " + HashAlgorithm);

            if (KeyId == null)
                KeyId = GetKeyId();

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

            feature.AuthResponseDecorator = AuthenticateResponseDecorator;
        }