Ejemplo n.º 1
0
        public void Configure(IAppHost appHost)
        {
            var AppSettings = appHost.AppSettings;

            appHost.Plugins.Add(new AuthFeature(() => new AuthUserSession(),
                                                new IAuthProvider[] {
                //new BasicAuthProvider(), //Sign-in with HTTP Basic Auth
                new JwtAuthProvider(AppSettings)
                {
                    AuthKey = AesUtils.CreateKey(),
                    RequireSecureConnection = false,
                },
                new CredentialsAuthProvider(),     //HTML Form post of UserName/Password credentials
                new FacebookAuthProvider(AppSettings),
                new TwitterAuthProvider(AppSettings),
            }));

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

            var userRep = new InMemoryAuthRepository();

            appHost.Register <IAuthRepository>(userRep);

            var authRepo = userRep;

            var newAdmin = new UserAuth {
                Email = "*****@*****.**", DisplayName = "Admin User"
            };
            var user = authRepo.CreateUserAuth(newAdmin, "p@55wOrd");

            authRepo.AssignRoles(user, new List <string> {
                "Admin"
            });
        }
Ejemplo n.º 2
0
        public void Configure(IAppHost appHost)
        {
            var AppSettings = appHost.AppSettings;

            appHost.Plugins.Add(new AuthFeature(() => new CustomUserSession(),
                                                new IAuthProvider[] {
                new CredentialsAuthProvider(AppSettings),     //Enable UserName/Password Credentials Auth
                new JwtAuthProvider(AppSettings)
                {
                    RequireSecureConnection = false,
                    AuthKey = AesUtils.CreateKey(),     //Transient Auth Key
                },
            }));

            appHost.Plugins.Add(new RegistrationFeature()); //Enable /register Service

            //override the default registration validation with your own custom implementation
            appHost.RegisterAs <CustomRegistrationValidator, IValidator <Register> >();

            appHost.Register <ICacheClient>(new MemoryCacheClient());         //Store User Sessions in Memory

            appHost.Register <IAuthRepository>(new InMemoryAuthRepository()); //Store Authenticated Users in Memory

            CreateUser(appHost, "*****@*****.**", "Admin User", "p@55wOrd", roles: new[] { RoleNames.Admin });
        }
Ejemplo n.º 3
0
        /// <summary>
        /// Application specific configuration
        /// This method should initialize any IoC resources utilized by your web service classes.
        /// </summary>
        public override void Configure(Container container)
        {
            Plugins.Add(new CorsFeature());

            this.GlobalRequestFilters.Add((httpReq, httpRes, requestDto) => {
                // Handles Request and closes Responses after emitting global HTTP Headers
                if (httpReq.GetHttpMethodOverride() == "OPTIONS")
                {
                    httpRes.EndRequest();
                }
            });

            container.Register(c => DatabaseProvider.PrepareDatabase());

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

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

            Plugins.Add(new AuthFeature(
                            () => new AuthUserSession(),
                            new IAuthProvider[] {
                new JwtAuthProvider(AppSettings)
                {
                    AuthKey = AesUtils.CreateKey()
                },
                new BasicAuthProvider(),
                new CredentialsAuthProvider(),
            }
                            ));
            Plugins.Add(new RegistrationFeature());
        }
Ejemplo n.º 4
0
 protected override JwtAuthProvider CreateJwtAuthProvider()
 {
     return(new JwtAuthProvider
     {
         AuthKey = AesUtils.CreateKey(),
         RequireSecureConnection = false,
     });
 }
Ejemplo n.º 5
0
        public void Test_Method1()
        {
            var kex = AesUtils.CreateKey().ToBase64UrlSafe();
            var service = appHost.Container.Resolve<MyServices>();

            var response = (HelloResponse)service.Any(new Hello { Name = "World" });

            Assert.That(response.Result, Is.EqualTo("Hello, World!"));
        }
        public void Does_throw_on_replayed_messages()
        {
            var client = CreateClient();

            var request = new HelloSecure {
                Name = "World"
            };

            byte[] cryptKey, iv;
            AesUtils.CreateKeyAndIv(out cryptKey, out iv);

            byte[] authKey = AesUtils.CreateKey();

            var cryptAuthKeys = cryptKey.Combine(authKey);

            var rsaEncCryptAuthKeys     = RsaUtils.Encrypt(cryptAuthKeys, SecureConfig.PublicKeyXml);
            var authRsaEncCryptAuthKeys = HmacUtils.Authenticate(rsaEncCryptAuthKeys, authKey, iv);

            var timestamp   = DateTime.UtcNow.ToUnixTime();
            var requestBody = timestamp + " POST " + typeof(HelloSecure).Name + " " + request.ToJson();

            var encryptedBytes     = AesUtils.Encrypt(requestBody.ToUtf8Bytes(), cryptKey, iv);
            var authEncryptedBytes = HmacUtils.Authenticate(encryptedBytes, authKey, iv);

            var encryptedMessage = new EncryptedMessage
            {
                EncryptedSymmetricKey = Convert.ToBase64String(authRsaEncCryptAuthKeys),
                EncryptedBody         = Convert.ToBase64String(authEncryptedBytes),
            };

            var encResponse = client.Post(encryptedMessage);

            try
            {
                client.Post(encryptedMessage);

                Assert.Fail("Should throw");
            }
            catch (WebServiceException ex)
            {
                ex.StatusDescription.Print();

                var errorResponse = (EncryptedMessageResponse)ex.ResponseDto;

                authEncryptedBytes = Convert.FromBase64String(errorResponse.EncryptedBody);
                if (!HmacUtils.Verify(authEncryptedBytes, authKey))
                {
                    throw new Exception("EncryptedBody is Invalid");
                }

                var responseBytes = HmacUtils.DecryptAuthenticated(authEncryptedBytes, cryptKey);
                var responseJson  = responseBytes.FromUtf8Bytes();
                var response      = responseJson.FromJson <ErrorResponse>();
                Assert.That(response.ResponseStatus.Message, Is.EqualTo("Nonce already seen"));
            }
        }
Ejemplo n.º 7
0
 public override void Configure(Container container)
 {
     Plugins.Add(new AuthFeature(() => new AuthUserSession(),
                                 new IAuthProvider[] {
         new JwtAuthProvider(AppSettings)
         {
             AuthKey = AesUtils.CreateKey()
         },
     }));
 }
Ejemplo n.º 8
0
        public void Does_parse_byte_array_as_Base64()
        {
            var authKey = AesUtils.CreateKey();

            var appSettings = new DictionarySettings(new Dictionary <string, string>
            {
                { "AuthKey", Convert.ToBase64String(authKey) }
            });

            Assert.That(appSettings.Get <byte[]>("AuthKey"), Is.EquivalentTo(authKey));
        }
Ejemplo n.º 9
0
        // http://localhost:5000/auth/[email protected]&&password=!Abc1234
        // Configure your AppHost with the necessary configuration and dependencies your App needs
        public override void Configure(Container container)
        {
            Plugins.Add(new TemplatePagesFeature()); // enable server-side rendering, see: http://templates.servicestack.net

            if (Config.DebugMode)
            {
                Plugins.Add(new HotReloadFeature());
            }

            Plugins.Add(new RazorFormat()); // enable ServiceStack.Razor

            SetConfig(new HostConfig
            {
                AddRedirectParamsToQueryString = true,
                DebugMode = AppSettings.Get(nameof(HostConfig.DebugMode), false)
            });

            Plugins.Add(new AuthFeature(() => new AuthUserSession(),
                                        new IAuthProvider[] {
                //new BasicAuthProvider(), //Sign-in with HTTP Basic Auth
                new JwtAuthProvider(AppSettings)
                {
                    AuthKey = AesUtils.CreateKey(),
                    RequireSecureConnection = false,
                },
                new CredentialsAuthProvider(),     //HTML Form post of UserName/Password credentials
                new FacebookAuthProvider(AppSettings),
                new TwitterAuthProvider(AppSettings),
            }));

            Plugins.Add(new RegistrationFeature());

            Plugins.Add(new OpenApiFeature
            {
                UseBearerSecurity = true,
            });

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

            container.Register <IAuthRepository>(userRep);

            var authRepo = userRep;

            var newAdmin = new UserAuth {
                Email = "*****@*****.**"
            };
            var user = authRepo.CreateUserAuth(newAdmin, "test");

            authRepo.AssignRoles(user, new List <string> {
                "Admin"
            });
        }
Ejemplo n.º 10
0
        public override void Configure(Container container)
        {
            Plugins.Add(new AuthFeature(() => new AuthUserSession(),
                                        new IAuthProvider[] {
                new CredentialsAuthProvider(AppSettings),
                new JwtAuthProvider(AppSettings)
                {
                    AuthKey = AesUtils.CreateKey(),
                    RequireSecureConnection = false,
                },
            }));

            container.Register <IAuthRepository>(c => new InMemoryAuthRepository());
            var authRepo = container.Resolve <IAuthRepository>();

            try
            {
                ((IClearable)authRepo).Clear();
            }
            catch { /*ignore*/ }

            authRepo.CreateUserAuth(new UserAuth
            {
                Id          = 1,
                UserName    = "******",
                FirstName   = "First",
                LastName    = "Last",
                DisplayName = "Display",
            }, "p@55word");

            container.Register(c => createMqServerFn());

            var mqServer = container.Resolve <IMessageService>();

            mqServer.RegisterHandler <HelloIntro>(ExecuteMessage);
            mqServer.RegisterHandler <MqAuthOnlyToken>(ExecuteMessage);
            mqServer.RegisterHandler <MqAuthOnly>(m =>
            {
                var req = new BasicRequest
                {
                    Verb    = HttpMethods.Post,
                    Headers = { ["X-ss-id"] = m.GetBody().SessionId }
                };
                var response = ExecuteMessage(m, req);
                return(response);
            });
            mqServer.RegisterHandler <MqRestriction>(ExecuteMessage);
            mqServer.Start();
        }
Ejemplo n.º 11
0
    public override void Configure(Container container)
    {
        Plugins.Add(new EncryptedMessagesFeature
        {
            PrivateKey          = SecureConfig.PrivateKeyXml.ToPrivateRSAParameters(),
            FallbackPrivateKeys =
            {
                SecureConfig.FallbackPrivateKeyXml.ToPrivateRSAParameters()
            },
        });

        var apiKeyAuth = new ApiKeyAuthProvider(AppSettings);
        var jwtAuth    = new JwtAuthProvider(AppSettings)
        {
            AuthKey        = AesUtils.CreateKey(),
            UseTokenCookie = false, // only works with non HTTP Cookies
        };

        Plugins.Add(new AuthFeature(() => new AuthUserSession(),
                                    new IAuthProvider[] {
            new CredentialsAuthProvider(AppSettings),
            apiKeyAuth,
            jwtAuth,
        }));

        container.Register <IAuthRepository>(c => new InMemoryAuthRepository());
        var authRepo = container.Resolve <IAuthRepository>();

        var userAuth = authRepo.CreateUserAuth(
            new UserAuth {
            Email = "*****@*****.**"
        }, "p@55word");

        var apiKeys    = apiKeyAuth.GenerateNewApiKeys(userAuth.Id.ToString(), "live");
        var apiKeyRepo = (IManageApiKeys)authRepo;

        apiKeyRepo.StoreAll(apiKeys);
        LiveApiKey = apiKeys[0];

        JwtBearerToken = jwtAuth.CreateJwtBearerToken(new AuthUserSession {
            UserAuthId      = userAuth.Id.ToString(),
            Email           = userAuth.Email,
            IsAuthenticated = true,
        });
    }
Ejemplo n.º 12
0
        public void Configure(IAppHost appHost)
        {
            var AppSettings = appHost.AppSettings;

            appHost.Plugins.Add(new AuthFeature(() => new CustomUserSession(),
                                                new IAuthProvider[] {
                new JwtAuthProvider(AppSettings)
                {
                    AuthKey = AesUtils.CreateKey()
                },                                                // Use persistent key to enable JWT's beyond restarts
                new CredentialsAuthProvider(AppSettings),         /* Sign In with Username / Password credentials */
                new FacebookAuthProvider(AppSettings),            /* Create App https://developers.facebook.com/apps */
                new GoogleAuthProvider(AppSettings),              /* Create App https://console.developers.google.com/apis/credentials */
                new MicrosoftGraphAuthProvider(AppSettings),      /* Create App https://apps.dev.microsoft.com */
            }));

            appHost.Plugins.Add(new RegistrationFeature()); //Enable /register Service

            //override the default registration validation with your own custom implementation
            appHost.RegisterAs <CustomRegistrationValidator, IValidator <Register> >();
        }
Ejemplo n.º 13
0
        public void Configure(IAppHost appHost)
        {
            var appSettings = appHost.AppSettings;

            // Setup Authentication
            appHost.Plugins.Add(new AuthFeature(() => new AuthUserSession(),
                                                new IAuthProvider[] {
                new CredentialsAuthProvider(appSettings),        // Username/Password credentials
                new FacebookAuthProvider(appSettings),           /* Create App https://developers.facebook.com/apps */
                new JwtAuthProvider(appSettings)
                {
                    AuthKey = AesUtils.CreateKey()
                },
            })
            {
                IncludeOAuthTokensInAuthenticateResponse = true, // Include OAuth Keys in authenticated /auth page
            });

            appHost.Plugins.Add(new RegistrationFeature()); //Enable /register Service

            // Allow posting messages back to Studio when loaded in an iframe
            appHost.Plugins.Add(new CorsFeature(allowOriginWhitelist: new[] { "https://localhost:5002" }));
        }
Ejemplo n.º 14
0
        public static string CreateEncryptedJweToken(JsonObject jwtPayload, RSAParameters publicKey)
        {
            //From: http://self-issued.info/docs/draft-ietf-jose-json-web-encryption-09.html#RSACBCExample
            var jweHeader = new JsonObject
            {
                { "alg", "RSA-OAEP" },
                { "enc", "A128CBC-HS256" },
                { "kid", Convert.ToBase64String(publicKey.Modulus).Substring(0, 3) },
            };

            var jweHeaderBase64Url = jweHeader.ToJson().ToUtf8Bytes().ToBase64UrlSafe();

            var authKey          = new byte[128 / 8];
            var cryptKey         = new byte[128 / 8];
            var cryptAuthKeys256 = AesUtils.CreateKey();

            Buffer.BlockCopy(cryptAuthKeys256, 0, authKey, 0, authKey.Length);
            Buffer.BlockCopy(cryptAuthKeys256, authKey.Length, cryptKey, 0, cryptKey.Length);

            var aes = Aes.Create();

            aes.KeySize   = 128;
            aes.BlockSize = 128;
            aes.Mode      = CipherMode.CBC;
            aes.Padding   = PaddingMode.PKCS7;
            using (aes)
            {
                aes.GenerateIV();
                var iv = aes.IV;
                aes.Key = cryptKey;

                var jweEncKey          = RsaUtils.Encrypt(cryptAuthKeys256, publicKey, UseRsaKeyLength);
                var jweEncKeyBase64Url = jweEncKey.ToBase64UrlSafe();
                var ivBase64Url        = iv.ToBase64UrlSafe();

                var aad          = jweHeaderBase64Url + "." + jweEncKeyBase64Url;
                var aadBytes     = aad.ToUtf8Bytes();
                var payloadBytes = jwtPayload.ToJson().ToUtf8Bytes();

                using (var cipherStream = MemoryStreamFactory.GetStream())
                    using (var encrypter = aes.CreateEncryptor(cryptKey, iv))
                        using (var cryptoStream = new CryptoStream(cipherStream, encrypter, CryptoStreamMode.Write))
                            using (var writer = new BinaryWriter(cryptoStream))
                            {
                                writer.Write(payloadBytes);
                                cryptoStream.FlushFinalBlock();

                                using (var hmac = new HMACSHA256(authKey))
                                    using (var encryptedStream = MemoryStreamFactory.GetStream())
                                        using (var bw = new BinaryWriter(encryptedStream))
                                        {
                                            bw.Write(aadBytes);
                                            bw.Write(iv);
                                            bw.Write(cipherStream.GetBuffer(), 0, (int)cipherStream.Length);
                                            bw.Flush();

                                            var tag = hmac.ComputeHash(encryptedStream.GetBuffer(), 0, (int)encryptedStream.Length);

                                            var cipherTextBase64Url = cipherStream.ToBase64UrlSafe();
                                            var tagBase64Url        = tag.ToBase64UrlSafe();

                                            var jweToken = jweHeaderBase64Url + "."
                                                           + jweEncKeyBase64Url + "."
                                                           + ivBase64Url + "."
                                                           + cipherTextBase64Url + "."
                                                           + tagBase64Url;

                                            return(jweToken);
                                        }
                            }
            }
        }
Ejemplo n.º 15
0
        public override void Configure(Container container)
        {
            if (Use != null)
            {
                Use(container);
            }

            if (EnableRazor)
            {
                Plugins.Add(new RazorFormat());
            }

            Plugins.Add(new SwaggerFeature());
            Plugins.Add(new RequestInfoFeature());
            Plugins.Add(new RequestLogsFeature());
            Plugins.Add(new ServerEventsFeature());

            Plugins.Add(new ValidationFeature());
            container.RegisterValidators(typeof(AutoValidationValidator).Assembly);

            var dbFactory = new OrmLiteConnectionFactory(":memory:", SqliteDialect.Provider);

            container.Register <IDbConnectionFactory>(dbFactory);

            dbFactory.RegisterConnection("testdb", "~/App_Data/test.sqlite".MapAbsolutePath(), SqliteDialect.Provider);

            using (var db = dbFactory.OpenDbConnection())
            {
                db.DropAndCreateTable <Rockstar>(); //Create table if not exists
                db.Insert(Rockstar.SeedData);       //Populate with seed data
            }

            using (var db = dbFactory.OpenDbConnection("testdb"))
            {
                db.DropAndCreateTable <Rockstar>(); //Create table if not exists
                db.Insert(new Rockstar(1, "Test", "Database", 27));
            }

            SetConfig(new HostConfig
            {
                AdminAuthSecret = "secret",
                DebugMode       = true,
            });

            if (EnableAuth)
            {
                Plugins.Add(new AuthFeature(() => new AuthUserSession(),
                                            new IAuthProvider[] {
                    new BasicAuthProvider(AppSettings),
                    new CredentialsAuthProvider(AppSettings),
                    new ApiKeyAuthProvider(AppSettings)
                    {
                        RequireSecureConnection = false
                    },
                    new JwtAuthProvider(AppSettings)
                    {
                        AuthKey = JwtRsaPrivateKey != null || JwtRsaPublicKey != null ? null : AesUtils.CreateKey(),
                        RequireSecureConnection = false,
                        HashAlgorithm           = JwtRsaPrivateKey != null || JwtRsaPublicKey != null ? "RS256" : "HS256",
                        PublicKey      = JwtRsaPublicKey,
                        PrivateKey     = JwtRsaPrivateKey,
                        EncryptPayload = JwtEncryptPayload,
                    },
                })
                {
                    IncludeRegistrationService = true,
                });

                container.Resolve <IAuthRepository>().InitSchema();
            }
        }
Ejemplo n.º 16
0
        /// <summary>
        /// Application specific configuration
        /// This method should initialize any IoC resources utilized by your web service classes.
        /// </summary>
        public override void Configure(Container container)
        {
            //Console.WriteLine
            LogManager.LogFactory = new ConsoleLogFactory(debugEnabled: true);

            container.Register <IAuthRepository>(c =>
                                                 new OrmLiteAuthRepository(container.Resolve <IDbConnectionFactory>())
            {
                UseDistinctRoleTables = true
            });

            //Create UserAuth RDBMS Tables
            container.Resolve <IAuthRepository>().InitSchema();

            //Also store User Sessions in SQL Server
            container.RegisterAs <OrmLiteCacheClient, ICacheClient>();
            container.Resolve <ICacheClient>().InitSchema();
            container.RegisterAs <OrmLiteAuthRepository, IUserAuthRepository>();

            //Register Autofac IoC container adapter, so ServiceStack can use it
            container.Adapter = new AutofacIocAdapter(autoFacContainer);

            //This method scans the assembly for validators
            container.RegisterValidators(typeof(Api.General.RegistrationValidator).Assembly);

            SetConfig(new HostConfig {
                UseCamelCase = true
            });

            Plugins.Add(new SwaggerFeature {
                UseBootstrapTheme = true
            });
            Plugins.Add(new PostmanFeature());
            Plugins.Add(new CorsFeature());

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

            Plugins.Add(new AutoQueryFeature {
                MaxLimit = 100
            });
            Plugins.Add(new AdminFeature());
            Plugins.Add(new ValidationFeature());

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

            //Add Support for
            Plugins.Add(new AuthFeature(() => new AuthUserSession(),
                                        new IAuthProvider[] {
                new JwtAuthProvider(AppSettings)
                {
                    AuthKey = AesUtils.CreateKey(), RequireSecureConnection = false
                },
                new ApiKeyAuthProvider(AppSettings),            //Sign-in with API Key
                new CredentialsAuthProvider(),                  //Sign-in with UserName/Password credentials
                new BasicAuthProvider(),                        //Sign-in with HTTP Basic Auth
                new DigestAuthProvider(AppSettings),            //Sign-in with HTTP Digest Auth
                new TwitterAuthProvider(AppSettings),           //Sign-in with Twitter
                new FacebookAuthProvider(AppSettings),          //Sign-in with Facebook
                //new YahooOpenIdOAuthProvider(AppSettings),  //Sign-in with Yahoo OpenId
                //new OpenIdOAuthProvider(AppSettings),       //Sign-in with Custom OpenId
                //new GoogleOAuth2Provider(AppSettings),      //Sign-in with Google OAuth2 Provider
                //new LinkedInOAuth2Provider(AppSettings),    //Sign-in with LinkedIn OAuth2 Provider
                //new GithubAuthProvider(AppSettings),        //Sign-in with GitHub OAuth Provider
                //new YandexAuthProvider(AppSettings),        //Sign-in with Yandex OAuth Provider
                //new VkAuthProvider(AppSettings),            //Sign-in with VK.com OAuth Provider
            }));

            using (var db = container.Resolve <IDbConnectionFactory>().Open())
            {
                //Create the PortalTempUser POCO table if it doesn't already exist
                db.CreateTableIfNotExists <PortalTempUser>();
            }
        }
Ejemplo n.º 17
0
        public override void Configure(Container container)
        {
            Use?.Invoke(container);

            var dbFactory = new OrmLiteConnectionFactory(":memory:", SqliteDialect.Provider);

            container.Register <IDbConnectionFactory>(dbFactory);

            dbFactory.RegisterConnection("testdb", "~/App_Data/test.sqlite".MapServerPath(), SqliteDialect.Provider);

            using (var db = dbFactory.OpenDbConnection())
            {
                db.DropAndCreateTable <Rockstar>(); //Create table if not exists
                db.Insert(Rockstar.SeedData);       //Populate with seed data
            }

            using (var db = dbFactory.OpenDbConnection("testdb"))
            {
                db.DropAndCreateTable <Rockstar>(); //Create table if not exists
                db.Insert(new Rockstar(1, "Test", "Database", 27));
            }

#if !NETCORE
            Plugins.Add(new ServiceStack.Razor.RazorFormat());
#endif

            Plugins.Add(new AuthFeature(() => new AuthUserSession(),
                                        new IAuthProvider[] {
                new BasicAuthProvider(AppSettings),
                new CredentialsAuthProvider(AppSettings),
                new ApiKeyAuthProvider(AppSettings)
                {
                    RequireSecureConnection = false
                },
                new JwtAuthProvider(AppSettings)
                {
                    AuthKey = JwtRsaPrivateKey != null || JwtRsaPublicKey != null ? null : AesUtils.CreateKey(),
                    RequireSecureConnection = false,
                    HashAlgorithm           = JwtRsaPrivateKey != null || JwtRsaPublicKey != null ? "RS256" : "HS256",
                    PublicKey          = JwtRsaPublicKey,
                    PrivateKey         = JwtRsaPrivateKey,
                    EncryptPayload     = JwtEncryptPayload,
                    FallbackAuthKeys   = FallbackAuthKeys,
                    FallbackPublicKeys = FallbackPublicKeys,
                },
            })
            {
                IncludeRegistrationService = true,
            });

            container.Resolve <IAuthRepository>().InitSchema();
        }
Ejemplo n.º 18
0
 public void Generate_AuthKey()
 {
     Convert.ToBase64String(AesUtils.CreateKey()).Print();
 }
Ejemplo n.º 19
0
        /// <summary>
        /// 个性化配置
        /// 用户初始化服务器需要的IOC资源
        /// </summary>
        public override void Configure(Container container)
        {
            //注册模板页面
            SetConfig(new HostConfig
            {
                //调试模式
                DebugMode = AppSettings.Get("DebugMode", false),
                ////隐藏metadata page页面
                //EnableFeatures = Feature.All.Remove(Feature.Metadata),
                //没有登录可以使用?authsecret=xxx方式,和登录效果一致
                AdminAuthSecret = AppSettings.Get("AdminAuthSecret", "secretz"),
                //注册网页根目录
                //WebHostPhysicalPath = MapProjectPath("~/my-project/dist"),
                //WebHostPhysicalPath = MapProjectPath("~/wwwroot"),
                AddRedirectParamsToQueryString = true,
                //UseCamelCase = true,
                //注册接口服务地址
                HandlerFactoryPath = "api",
                DefaultContentType = MimeTypes.Json,
            });
            //注册测试页
            Plugins.Add(new TemplatePagesFeature());

            Plugins.Add(new AdminFeature());

            Plugins.Add(new AutoQueryFeature {
                MaxLimit = 100
            });

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

            //添加一个request filter 确认用户的登录session
            //this.GlobalRequestFilters.Add((req, res, requestDto) =>
            //{
            //    if (!req.GetSession().IsAuthenticated)
            //    {
            //        res.ReturnAuthRequired();
            //    }
            //});

            //container.Register<IAuthProvider>(r => new myAuthProvider());


            //获取连接字符串
            var connectionString = ConfigurationManager.ConnectionStrings["DbContext"].ConnectionString;

            //注册数据库连接工厂
            container.Register <IDbConnectionFactory>(c =>
                                                      new OrmLiteConnectionFactory(connectionString, SqlServerDialect.Provider));
            //注册数据库连接
            container.Register <IAuthRepository>(c =>
                                                 new OrmLiteAuthRepository(c.Resolve <IDbConnectionFactory>())
            {
                UseDistinctRoleTables = true
            });
            //获取用户表的数据库连接,如果没有生成表则自动生成
            container.Resolve <IAuthRepository>().InitSchema();


            //Also store User Sessions in SQL Server
            container.RegisterAs <OrmLiteCacheClient, ICacheClient>();
            container.Resolve <ICacheClient>().InitSchema();


            //获取数据库的配置连接
            //container.Register<IAppSettings>(c => new OrmLiteAppSettings(c.Resolve<IDbConnectionFactory>()));

            //container.Register<IAppSettings>(c => new AppSettings());
            //获取配置
            //var appsetting = (AppSettings)container.Resolve<IAppSettings>();
            //初始化数据表
            //appsetting.InitSchema();

            //appsetting.Get("test", "test");

            var privateKey   = RsaUtils.CreatePrivateKeyParams(RsaKeyLengths.Bit2048);
            var publicKeyXml = privateKey.ToPublicKeyXml();


            //所有需要用账号访问的方法,都会调用认证界面CustomUserSession,myAuthProvider为自定义的方法
            //Add Support for
            Plugins.Add(new AuthFeature(() => new AuthUserSession(),
                                        new IAuthProvider[] {
                new JwtAuthProvider(AppSettings)
                {
                    AuthKey = AesUtils.CreateKey(),
                    RequireSecureConnection = false,
                    AllowInQueryString      = true,
                    SessionExpiry           = TimeSpan.FromDays(1),
                    //RedirectUrl = "www.baidu.com",
                    ExpireRefreshTokensIn = TimeSpan.FromDays(1),
                    ExpireTokensIn        = TimeSpan.FromDays(100),
                    CreatePayloadFilter   = (payload, session) =>
                    {
                        if (session.IsAuthenticated)
                        {
                            payload["CreatedAt"] = session.CreatedAt.ToUnixTime().ToString();
                            payload["exp"]       = DateTime.UtcNow.AddYears(1).ToUnixTime().ToString();
                        }
                    },

                    //AuthKeyBase64 = "Base64AuthKey",//AppSettings.GetString("AuthKeyBase64") //"Base64AuthKey",
                    //HashAlgorithm = "RS256",
                    //PrivateKeyXml ="PrivateKey2016Xml", //AppSettings.GetString("PrivateKeyXml")
                },
                new ApiKeyAuthProvider(AppSettings)
                {
                    RequireSecureConnection = false,
                    ExpireKeysAfter         = TimeSpan.FromDays(100),
                    SessionCacheDuration    = TimeSpan.FromMinutes(10),
                    InitSchema        = true,
                    AllowInHttpParams = true,
                    //KeyTypes = new[] { "secret", "publishable" },
                },                             //Sign-in with API Key
                new CredentialsAuthProvider(), //Sign-in with UserName/Password credentials
                new BasicAuthProvider(),       //Sign-in with HTTP Basic Auth
            })
            {
                IncludeRegistrationService   = true,
                IncludeAssignRoleServices    = true,
                IncludeAuthMetadataProvider  = true,
                ValidateUniqueEmails         = true,
                ValidateUniqueUserNames      = true,
                DeleteSessionCookiesOnLogout = true,
                SaveUserNamesInLowerCase     = true,
                GenerateNewSessionCookiesOnAuthentication = true,
            });

            //Default route: /register
            //Plugins.Add(new RegistrationFeature() { AllowUpdates = true });
            ////The IAuthRepository is used to store the user credentials etc.
            ////Implement this interface to adjust it to your app's data storage



            //CreateUser(10, "jinchaoqian1", "*****@*****.**", "j4012693", new List<string> { "TheRole" }, new List<string> { "ThePermission" });

            //记录日志
            LogManager.LogFactory = new MyLoggerFactory();
            //启用日志
            Plugins.Add(new RequestLogsFeature()
            {
                EnableRequestBodyTracking = true,
                EnableResponseTracking    = true,
                EnableSessionTracking     = true,
                EnableErrorTracking       = true,
            });
            //启用跨域访问
            this.Plugins.Add(new CorsFeature(allowedMethods: "GET, POST"));
            //注册Swagger插件进行API的Web调试
            Plugins.Add(new SwaggerFeature());
            //启用验证插件
            Plugins.Add(new ValidationFeature());
            //注册验证插件
            container.RegisterValidators(typeof(LoginValidator).Assembly);
            ////自动扫描验证插件
            //Plugins.Add(new ValidationFeature
            //{
            //    ScanAppHostAssemblies = true
            //});


            //JsConfig.EmitLowercaseUnderscoreNames = true;
            //JsConfig.ExcludeDefaultValues = true;
            //序列化时的日期格式
            JsConfig <DateTime> .SerializeFn = dateTime => dateTime.ToString("yyyy-MM-dd");
            JsConfig <TimeSpan> .SerializeFn = time =>
                                               (time.Ticks < 0 ? "-" : "") + time.ToString("hh':'mm':'ss'.'fffffff");

            //container.Register<ICacheClient>(c => new OrmLiteCacheClient(){DbFactory = c.Resolve<IDbConnectionFactory>()});

            //var cache = container.Resolve<OrmLiteCacheClient>();
            //cache.DbFactory = container.Resolve<IDbConnectionFactory>();

            //container.RegisterAs<OrmLiteCacheClient, ICacheClient>();

            ////Create 'CacheEntry' RDBMS table if it doesn't exist already
            //container.Resolve<ICacheClient>().InitSchema();

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



            //虚拟目录,使用插件方式或者是重载GetVirtualFileSources
            //Plugins.Add(new Disk1Plugin());

            //捕捉到被处理过的错误
            this.ServiceExceptionHandlers.Add((httpReq, request, exception) => {
                //记录错误信息
                //TODO:
                System.Diagnostics.Debug.WriteLine(exception.Message);
                return(null); //返回默认错误

                //或者自定义错误
                //return DtoUtils.CreateErrorResponse(request, exception);
            });

            //处理未被系统处理的错误
            //E.g. Exceptions during Request binding or in filters:
            this.UncaughtExceptionHandlers.Add((req, res, operationName, ex) =>
            {
                res.WriteAsync($"Error: {ex.GetType().Name}: {ex.Message}");
                res.EndRequest(skipHeaders: true);
            });

            AfterInitCallbacks.Add(host =>
            {
                var authProvider = (ApiKeyAuthProvider)
                                   AuthenticateService.GetAuthProvider(ApiKeyAuthProvider.Name);
                using (var db = host.TryResolve <IDbConnectionFactory>().Open())
                {
                    var userWithKeysIds = db.Column <string>(db.From <ApiKey>()
                                                             .SelectDistinct(x => x.UserAuthId)).Map(int.Parse);

                    var userIdsMissingKeys = db.Column <string>(db.From <UserAuth>()
                                                                .Where(x => userWithKeysIds.Count == 0 || !userWithKeysIds.Contains(x.Id))
                                                                .Select(x => x.Id));

                    var authRepo = (IManageApiKeys)host.TryResolve <IAuthRepository>();
                    foreach (var userId in userIdsMissingKeys)
                    {
                        var apiKeys = authProvider.GenerateNewApiKeys(userId.ToString());
                        authRepo.StoreAll(apiKeys);
                    }
                }
            });
        }
Ejemplo n.º 20
0
        public override void Configure(Container container)
        {
            Use?.Invoke(container);

            SetConfig(new HostConfig
            {
                AdminAuthSecret = "secret",
                DebugMode       = true,
            });

            Plugins.Add(new AuthFeature(() => new AuthUserSession(),
                                        new IAuthProvider[] {
                new BasicAuthProvider(AppSettings),
                new CredentialsAuthProvider(AppSettings),
                new ApiKeyAuthProvider(AppSettings)
                {
                    RequireSecureConnection = false
                },
                new JwtAuthProvider(AppSettings)
                {
                    AuthKey = JwtRsaPrivateKey != null || JwtRsaPublicKey != null ? null : AesUtils.CreateKey(),
                    RequireSecureConnection = false,
                    HashAlgorithm           = JwtRsaPrivateKey != null || JwtRsaPublicKey != null ? "RS256" : "HS256",
                    PublicKey          = JwtRsaPublicKey,
                    PrivateKey         = JwtRsaPrivateKey,
                    EncryptPayload     = JwtEncryptPayload,
                    FallbackAuthKeys   = FallbackAuthKeys,
                    FallbackPublicKeys = FallbackPublicKeys,
                },
            })
            {
                IncludeRegistrationService = true,
            });

            container.Resolve <IAuthRepository>().InitSchema();
        }
Ejemplo n.º 21
0
        static void Main(string[] args)
        {
            var skey   = AesUtils.CreateKey();
            var keyXml = skey.ToXml();
            var kUrl   = skey.ToBase64UrlSafe();

            JarsCore.Container = MEFBusinessLoader.Init();
            Logger.Info("MEF Loaded!");

            //add license
            string licPath = "~/ServiceStackLicense.txt".MapAbsolutePath();

            Logger.Info($"Registering ServiceStack Licence looking for:{licPath}");
            try
            {
                Licensing.RegisterLicenseFromFileIfExists(licPath);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                Console.WriteLine("Press any key to close");
                Console.ReadLine();
                return;
            }
            //setup service
            var listeningOn = args.Length == 0 ? GetHostUrl() : args;
            //start setting up the service stack host
            JarsServiceAppHost appHost = new JarsServiceAppHost(AssemblyLoaderUtil.ServicesAssemblies.ToArray());

            appHost.OnConnect   = (evtSub, dictVal) => { Console.WriteLine($"OnConnect - Connection UserId:{evtSub.UserId} UserName: {evtSub.UserName} dictVals:{dictVal.Values}"); };
            appHost.OnSubscribe = (evtSub) => { Console.WriteLine($"OnSubscribe - sub:{evtSub.UserId}"); };
            appHost.OnPublish   = (sub, res, msg) => { if (!msg.Contains("cmd.onHeartbeat"))
                                                       {
                                                           Console.WriteLine($"Publish - DisplayName:{sub.DisplayName} Res.Status:{res.StatusCode} MsgLen:{msg.Length}");
                                                       }
            };
            appHost.OnUnsubscribe            = (evtSub) => { Console.WriteLine($"OnUnsubscribe - sub:{evtSub.UserId}"); };
            appHost.LimitToAuthenticatedUser = true;
            try
            {   //start the service
                appHost.Init().Start(listeningOn);
            }
            catch (Exception ex)
            {
                Logger.Info($"Error:{ex.Message}");
                Console.WriteLine("\r\n Press key to close app");
                Console.ReadLine();
                return;
            }

            string listeningOnVals = "";

            listeningOn.ToList().ForEach(s => listeningOnVals += $"ip: {s.ToString()}{Environment.NewLine}");

            Console.WriteLine($"AppHost Created at {DateTime.Now}, listening on: {Environment.NewLine}{listeningOnVals}");

            Console.WriteLine("write 'exit' to close, 'notify' to send notification to all subscribers, test to notify 'test' channel or sub-[chanel name] to notify that channel");

            //resolve the events plugin loaded in the configuration.
            IServerEvents se = appHost.TryResolve <IServerEvents>();

            int    i   = 0;
            string key = "start";

            while (key != "exit")
            {
                Console.Write("Subs: {0}", se.GetAllSubscriptionInfos().Count);
                key = Console.ReadLine();

                if (key == "notify")
                {
                    se.NotifyAll($"Notify All count({i})");
                }

                if (key == "test")
                {
                    se.NotifyChannel("test", $"Notify all in test channel : count({i})");
                }

                if (key.Contains("sub"))
                {
                    se.NotifyChannel(key.Substring(key.IndexOf("-")), $"Notify channel {key.Substring(key.IndexOf("-"))} : count({i})");
                }

                if (key.Contains("infos"))
                {
                    List <SubscriptionInfo> infs = se.GetAllSubscriptionInfos();

                    foreach (var si in infs)
                    {
                        Console.Write($"DisplayName:{si.DisplayName}, Auth:{si.IsAuthenticated}, SubId:{si.SubscriptionId}, UserId:{si.UserId}, UserName:{si.UserName}");
                        Console.WriteLine();
                    }
                }
                if (key.Contains("login"))
                {
                    ServerEventsClient   client = new ServerEventsClient("http://localhost:3337/", "test");
                    AuthenticateResponse aResp  = client.Authenticate(new Authenticate()
                    {
                        UserName = "******", Password = "******", RememberMe = true
                    });
                    Console.Write($"Auth DisplayName:{aResp.DisplayName}, BT:{aResp.BearerToken}, Un:{aResp.UserName}, UserId:{aResp.UserId}");
                }
                if (key.Contains("req"))
                {
                }
                i++;
            }
        }