public void Export_PrivateKey_to_xml() { var privateKey = RsaUtils.CreatePrivateKeyParams(); "PRIVATE KEY".Print(); privateKey.ToPrivateKeyXml().Print(); "PUBLIC KEY".Print(); privateKey.ToPublicKeyXml().Print(); }
public virtual void Invalid_jwt_is_rejected() { var token = CreateJwt(RsaUtils.CreatePrivateKeyParams(), "RS512"); client.HttpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token); Assert.That( () => client.Send(new Hello()), Throws.TypeOf <WebServiceException>() .With.Matches <WebServiceException>(ex => ex.StatusCode == 401)); }
private string GetPrivateKeyXml() { // TODO: you can do better than this obviously :-) var privateKeyFile = "privateKey.xml".MapHostAbsolutePath(); if (!File.Exists(privateKeyFile)) { File.WriteAllText(privateKeyFile, RsaUtils.CreatePrivateKeyParams(RsaKeyLengths.Bit2048).ToPrivateKeyXml()); } return(File.ReadAllText(privateKeyFile)); }
public void Can_sign_data_with_RSA() { var privateKey = RsaUtils.CreatePrivateKeyParams(RsaKeyLengths.Bit2048); var publicKey = privateKey.ToPublicRsaParameters(); var message = "sign this"; var data = message.ToUtf8Bytes(); var signature = RsaUtils.Authenticate(data, privateKey, "SHA256", RsaKeyLengths.Bit2048); var verified = RsaUtils.Verify(data, signature, publicKey, "SHA256", RsaKeyLengths.Bit2048); Assert.That(verified, Is.True); }
protected override JwtAuthProvider CreateJwtAuthProvider() { var privateKey = RsaUtils.CreatePrivateKeyParams(RsaKeyLengths.Bit2048); var publicKey = privateKey.ToPublicRsaParameters(); var privateKeyXml = privateKey.ToPrivateKeyXml(); var publicKeyXml = privateKey.ToPublicKeyXml(); return(new JwtAuthProvider { HashAlgorithm = "RS256", PrivateKeyXml = privateKeyXml, RequireSecureConnection = false, }); }
public JwtAuthProviderRsa256ReaderTests() { privateKey = RsaUtils.CreatePrivateKeyParams(RsaKeyLengths.Bit2048); publicKey = privateKey.ToPublicRsaParameters(); privateKeyXml = privateKey.ToPrivateKeyXml(); publicKeyXml = privateKey.ToPublicKeyXml(); appHost = new AppHost { JwtAuthProviderReader = CreateJwtAuthProviderReader() } .Init() .Start(Config.ListeningOn); }
public override void Configure(Container container) { var dbFactory = new OrmLiteConnectionFactory(":memory:", SqliteDialect.Provider); container.Register <IDbConnectionFactory>(dbFactory); container.Register <IAuthRepository>(c => new OrmLiteAuthRepository(c.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(); var privateKey = RsaUtils.CreatePrivateKeyParams(RsaKeyLengths.Bit2048); var publicKey = privateKey.ToPublicRsaParameters(); var privateKeyXml = privateKey.ToPrivateKeyXml(); var publicKeyXml = privateKey.ToPublicKeyXml(); // just for testing, create a privateKeyXml on every instance Plugins.Add(new AuthFeature(() => new AuthUserSession(), new IAuthProvider[] { new JwtAuthProvider { HashAlgorithm = "RS256", PrivateKeyXml = privateKeyXml, RequireSecureConnection = false, }, new CredentialsAuthProvider() })); Plugins.Add(new RegistrationFeature()); var authRepo = GetAuthRepository(); authRepo.CreateUserAuth(new UserAuth { Id = 1, UserName = "******", FirstName = "First", LastName = "Last", DisplayName = "Display", }, "p@55word"); }
/// <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); } } }); }
public void Generate_new_Key() { RsaUtils.CreatePrivateKeyParams().ToPrivateKeyXml().Replace("\"", "\\\"").Print(); }
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); }
/// <summary> /// Application specific configuration /// This method should initialize any IoC resources utilized by your web service classes. /// </summary> // public override void Configure(Container container) // { // authKey = AesUtils.CreateKey(); // fallbackAuthKey = AesUtils.CreateKey(); // var privateKey = RsaUtils.CreatePrivateKeyParams(RsaKeyLengths.Bit2048); // var publicKey = privateKey.ToPublicRsaParameters(); // var privateKeyXml = privateKey.ToPrivateKeyXml(); // var publicKeyXml = privateKey.ToPublicKeyXml(); // AppSettings = new DictionarySettings(new Dictionary<string, string> { // { "jwt.AuthKeyBase64", Convert.ToBase64String(authKey) }, // { "jwt.AuthKeyBase64.1", Convert.ToBase64String(fallbackAuthKey) }, // {"PrivateKeyXml" ,"{PrivateKey2016Xml}"}, // { "jwt.RequireSecureConnection", "False" }, // {"oauth.GoogleOAuth.ConsumerKey","485362488543-e1eiujr63lmf88hd4v5roaq2hrtsfgul.apps.googleusercontent.com" }, // {"oauth.GoogleOAuth.ConsumerSecret","ryNIz_W-2KDmQ6E4RPXQcJEM" } // }); // SetConfig(new HostConfig // { // DebugMode = true, // UseCamelCase = true, // }); // SetConfig(new HostConfig // { // DefaultContentType = MimeTypes.Json // }); // // Plugins.Add(new CorsFeature()); // Plugins.Add(new PostmanFeature()); // Plugins.Add(new SwaggerFeature()); // Plugins.Add(new AdminFeature()); // Plugins.Add(new ValidationFeature()); // string[] allowOrgins = new string[] {"http://*****:*****@#qwe;MultipleActiveResultSets=True", SqlServerDialect.Provider); // container.Register<IDbConnectionFactory>(dbFactory); // container.Register<IAuthRepository>(c => // new OrmLiteAuthRepository(dbFactory) { 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(); // // Plugins.Add(new SessionFeature() { }); // //Add Support for // Plugins.Add(new AuthFeature(() => new AuthUserSession(), // new IAuthProvider[] { // new CredentialsAuthProvider(){ PersistSession = true}, // new BasicAuthProvider(), // new JwtAuthProvider(AppSettings) { // PersistSession = true, // //HashAlgorithm = "RS256", // //PrivateKeyXml = AppSettings.GetString("PrivateKeyXml") // 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, // // ExpireTokensIn = TimeSpan.FromDays(365), // ExpireRefreshTokensIn = TimeSpan.FromDays(365), // Refresh Token Expiry // Provider = "mp", // SaveExtendedUserInfo = true, // SetBearerTokenOnAuthenticateResponse = true, // SessionExpiry = TimeSpan.FromDays(365), // Issuer="MF", // ExpireTokensInDays = 20 // }, // //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 // })); // // Plugins.Add(new AuthFeature(() => new AuthUserSession(), // //new IAuthProvider[] { // // new JwtAuthProvider(AppSettings) { AuthKey = AesUtils.CreateKey() }, // // new CredentialsAuthProvider(AppSettings), // // //... // //})); // Plugins.Add(new RegistrationFeature()); // } public override void Configure(Container container) { //Store UserAuth in SQL Server var dbFactory = new OrmLiteConnectionFactory( "server=.;Database=IdentityDB;user=sa;pwd=123!@#qwe;MultipleActiveResultSets=True", SqlServerDialect.Provider); container.Register <IDbConnectionFactory>(dbFactory); container.Register <IAuthRepository>(c => new OrmLiteAuthRepository(dbFactory) { 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(); var privateKey = RsaUtils.CreatePrivateKeyParams(RsaKeyLengths.Bit2048); var publicKey = privateKey.ToPublicRsaParameters(); var privateKeyXml = privateKey.ToPrivateKeyXml(); var publicKeyXml = privateKey.ToPublicKeyXml(); // just for testing, create a privateKeyXml on every instance Plugins.Add(new AuthFeature(() => new AuthUserSession(), new IAuthProvider[] { new JwtAuthProvider { HashAlgorithm = "RS256", PrivateKeyXml = privateKeyXml, RequireSecureConnection = false, }, new CredentialsAuthProvider() })); this.GlobalRequestFilters.Add((httpReq, httpRes, requestDto) => { httpReq.SetSessionId("2MFD2Q706bNlpgG4MdMq"); //IRequest req = httpReq; //req.Items[Keywords.Session] = null; }); Plugins.Add(new RegistrationFeature()); // uncomment to create a first new user //var authRepo = GetAuthRepository(); //authRepo.CreateUserAuth(new UserAuth //{ // Id = 1, // UserName = "******", // FirstName = "First", // LastName = "Last", // DisplayName = "Display", //}, "p@55word"); }