Beispiel #1
0
        public StatelessAuthTests()
        {
            //LogManager.LogFactory = new ConsoleLogFactory();
            appHost = CreateAppHost()
                      .Init()
                      .Start("http://*:2337/");

            var client   = GetClient();
            var response = client.Post(new Register
            {
                UserName    = "******",
                Password    = "******",
                Email       = "as@if{0}.com",
                DisplayName = "DisplayName",
                FirstName   = "FirstName",
                LastName    = "LastName",
            });

            userId  = response.UserId;
            apiRepo = (IManageApiKeys)appHost.Resolve <IAuthRepository>();
            var user1Client = GetClientWithUserPassword(alwaysSend: true);

            ApiKey = user1Client.Get(new GetApiKeys {
                Environment = "live"
            }).Results[0].Key;

            apiProvider = (ApiKeyAuthProvider)AuthenticateService.GetAuthProvider(ApiKeyAuthProvider.Name);

            response = client.Post(new Register
            {
                UserName    = "******",
                Password    = "******",
                Email       = "as2@if{0}.com",
                DisplayName = "DisplayName2",
                FirstName   = "FirstName2",
                LastName    = "LastName2",
            });
            userIdWithRoles = response.UserId;
            var user2Client = GetClientWithUserPassword(alwaysSend: true, userName: "******");

            ApiKeyWithRole = user2Client.Get(new GetApiKeys {
                Environment = "live"
            }).Results[0].Key;

            ListeningOn.CombineWith("/assignroles").AddQueryParam("authsecret", "secret")
            .PostJsonToUrl(new AssignRoles
            {
                UserName = "******",
                Roles    = new List <string> {
                    "TheRole"
                },
                Permissions = new List <string> {
                    "ThePermission"
                }
            }.ToJson());
        }
        public async void PostWithApiKey(string resourcePath, string payload)
        {
            var authProvider = new ApiKeyAuthProvider();
            var headers      = authProvider.GenerateAuthHeaders(_config[ConfigurationKeys.CLIENT_KEY], _config[ConfigurationKeys.CLIENT_SECRET], null, null);
            var client       = new HttpClient();

            foreach (var header in headers)
            {
                client.DefaultRequestHeaders.Add(header.Key, header.Value);
            }
            var result = await client.GetStringAsync(_config[ConfigurationKeys.BASE_URL] + resourcePath + payload);

            Assert.True(result.ToLower().Contains("atms"));
            //Console.WriteLine("Response: " + result);
        }
    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,
        });
    }
Beispiel #4
0
        public override IUserAuth CreateUserAuth(IUserAuth newUser, string password)
        {
            var user = base.CreateUserAuth(newUser, password);

            using (var db = dbFactory.OpenDbConnection())
            {
                var settings = new TextFileSettings("appsettings.txt");
                var provider = new ApiKeyAuthProvider();
                provider.KeySizeBytes = 32;
                var key = provider.GenerateApiKey(String.Empty, String.Empty, 32).Substring(0, 32);
                db.Save <APIKey>(new APIKey()
                {
                    UserId       = user.Id,
                    RequestLimit = 2500,
                    Key          = key
                });

                var mimeMessage = new MimeMessage();
                mimeMessage.From.Add(new MailboxAddress(settings.GetString("EmailFromName"), settings.GetString("EmailFrom")));
                mimeMessage.To.Add(new MailboxAddress(user.Email, user.Email));
                mimeMessage.Subject = "Your api key";
                var builder = new BodyBuilder();
                builder.TextBody =
                    "Your api key is: " + key +
                    "\n\n" +
                    "Support: " + settings.GetString("EmailFrom");
                builder.HtmlBody =
                    "Your api key is: " + key +
                    "<br /><br />" +
                    "Support: " + settings.GetString("EmailFrom");

                mimeMessage.Body = builder.ToMessageBody();
                using (var client = new SmtpClient())
                {
                    client.Connect(settings.GetString("SMTPHost"), 587, false);
                    // Note: only needed if the SMTP server requires authentication
                    // Error 5.5.1 Authentication
                    client.Authenticate(settings.GetString("SMTPUser"), settings.GetString("SMTPPass"));
                    client.Send(mimeMessage);
                    client.Disconnect(true);
                }
            }

            return(user);
        }
        static void Main(string[] args)
        {
            string response     = null;
            string payload      = "radius_unit=MI&radius=5&latitude=32.67&longitude=-96.79&limit=10&offset=1";
            var    authProvider = new ApiKeyAuthProvider();
            var    headers      = authProvider.GenerateAuthHeaders(apiKey, null, null, null);

            var task = Task.Factory.StartNew(() => {
                using (var client = new HttpClient())
                {
                    foreach (var header in headers)
                    {
                        client.DefaultRequestHeaders.Add(header.Key, header.Value);
                    }
                    response = client.GetStringAsync(url + payload).Result;
                }
            });

            task.Wait();
            Console.WriteLine("Response: " + response);
        }
Beispiel #6
0
        public void Can_Authenticate_with_ApiKeyAuth_SessionCacheDuration()
        {
            apiProvider.SessionCacheDuration = TimeSpan.FromSeconds(60);

            var client = GetClientWithBearerToken(ApiKey);

            var request = new Secured {
                Name = "test"
            };
            var response = client.Send(request);

            Assert.That(response.Result, Is.EqualTo(request.Name));

            //Does not preserve UserSession
            var newClient = GetClient();

            newClient.SetSessionId(client.GetSessionId());
            try
            {
                response = newClient.Send(request);
                Assert.Fail("Should throw");
            }
            catch (WebServiceException webEx)
            {
                Assert.That(webEx.StatusCode, Is.EqualTo((int)HttpStatusCode.Unauthorized));
            }

            var cachedSession = appHost.GetCacheClient(null).Get <IAuthSession>(ApiKeyAuthProvider.GetSessionKey(ApiKey));

            Assert.That(cachedSession.IsAuthenticated);

            //Can call multiple times using cached UserSession
            response = client.Send(request);
            Assert.That(response.Result, Is.EqualTo(request.Name));

            apiProvider.SessionCacheDuration = null;
        }
        public StatelessAuthTests()
        {
            //LogManager.LogFactory = new ConsoleLogFactory();
            appHost = CreateAppHost()
                      .Init()
                      .Start("http://*:2337/");

            var client   = GetClient();
            var response = client.Post(new Register
            {
                UserName    = "******",
                Password    = "******",
                Email       = "as@if{0}.com",
                DisplayName = "DisplayName",
                FirstName   = "FirstName",
                LastName    = "LastName",
            });

            userId  = response.UserId;
            apiRepo = (IManageApiKeys)appHost.Resolve <IAuthRepository>();
            ApiKey  = apiRepo.GetUserApiKeys(userId).First(x => x.Environment == "test");

            apiProvider = (ApiKeyAuthProvider)AuthenticateService.GetAuthProvider(ApiKeyAuthProvider.Name);
        }
Beispiel #8
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);
        }