Exemplo n.º 1
0
        //TODO: this can be used in document store/counter stores/time series store
        internal static void InitializeSecurity(ConventionBase conventions, HttpJsonRequestFactory requestFactory, string serverUrl, ICredentials primaryCredentials)
        {
            if (conventions.HandleUnauthorizedResponseAsync != null)
            {
                return; // already setup by the user
            }
            var securedAuthenticator = new SecuredAuthenticator();

            requestFactory.ConfigureRequest += securedAuthenticator.ConfigureRequest;

            conventions.HandleUnauthorizedResponseAsync = (unauthorizedResponse, credentials) =>
            {
                var oauthSource = unauthorizedResponse.Headers.GetFirstValue("OAuth-Source");

#if DEBUG && FIDDLER
                // Make sure to avoid a cross DNS security issue, when running with Fiddler
                if (string.IsNullOrEmpty(oauthSource) == false)
                {
                    oauthSource = oauthSource.Replace("localhost:", "localhost.fiddler:");
                }
#endif

                if (credentials.ApiKey == null)
                {
                    return(null);
                }

                if (string.IsNullOrEmpty(oauthSource))
                {
                    oauthSource = serverUrl + "/OAuth/API-Key";
                }

                return(securedAuthenticator.DoOAuthRequestAsync(oauthSource, credentials.ApiKey));
            };
        }
Exemplo n.º 2
0
        public void ConfigureRequest(RavenConnectionStringOptions options, WebRequest request)
        {
            if (RequestTimeoutInMs.HasValue)
            {
                request.Timeout = RequestTimeoutInMs.Value;
            }

            if (options.ApiKey == null)
            {
                request.Credentials = options.Credentials ?? CredentialCache.DefaultNetworkCredentials;
                return;
            }

            var webRequestEventArgs = new WebRequestEventArgs {
                Request = request
            };

            AbstractAuthenticator existingAuthenticator;

            if (authenticators.TryGetValue(GetCacheKey(options), out existingAuthenticator))
            {
                existingAuthenticator.ConfigureRequest(this, webRequestEventArgs);
            }
            else
            {
                var basicAuthenticator   = new BasicAuthenticator(options.ApiKey, enableBasicAuthenticationOverUnsecuredHttp: false);
                var securedAuthenticator = new SecuredAuthenticator(options.ApiKey);

                basicAuthenticator.ConfigureRequest(this, webRequestEventArgs);
                securedAuthenticator.ConfigureRequest(this, webRequestEventArgs);
            }
        }
Exemplo n.º 3
0
        internal static void InitializeSecurity(Convention conventions, HttpJsonRequestFactory requestFactory, string serverUrl)
        {
            if (conventions.HandleUnauthorizedResponseAsync != null)
            {
                return; // already setup by the user
            }
            var basicAuthenticator   = new BasicAuthenticator(requestFactory.EnableBasicAuthenticationOverUnsecuredHttpEvenThoughPasswordsWouldBeSentOverTheWireInClearTextToBeStolenByHackers);
            var securedAuthenticator = new SecuredAuthenticator(autoRefreshToken: true);

            requestFactory.OnDispose        += (sender, args) => securedAuthenticator.Dispose();
            requestFactory.ConfigureRequest += basicAuthenticator.ConfigureRequest;
            requestFactory.ConfigureRequest += securedAuthenticator.ConfigureRequest;

            conventions.HandleForbiddenResponseAsync = (forbiddenResponse, credentials) =>
            {
                if (credentials.ApiKey == null)
                {
                    AssertForbiddenCredentialSupportWindowsAuth(forbiddenResponse, credentials.Credentials);
                    return(null);
                }

                return(null);
            };

            conventions.HandleUnauthorizedResponseAsync = (unauthorizedResponse, credentials) =>
            {
                var oauthSource = unauthorizedResponse.Headers.GetFirstValue("OAuth-Source");

#if DEBUG && FIDDLER
                // Make sure to avoid a cross DNS security issue, when running with Fiddler
                if (string.IsNullOrEmpty(oauthSource) == false)
                {
                    oauthSource = oauthSource.Replace("localhost:", "localhost.fiddler:");
                }
#endif

                // Legacy support
                if (string.IsNullOrEmpty(oauthSource) == false &&
                    oauthSource.EndsWith("/OAuth/API-Key", StringComparison.CurrentCultureIgnoreCase) == false)
                {
                    return(basicAuthenticator.HandleOAuthResponseAsync(oauthSource, credentials.ApiKey));
                }

                if (credentials.ApiKey == null)
                {
                    AssertUnauthorizedCredentialSupportWindowsAuth(unauthorizedResponse, credentials.Credentials);
                    return(null);
                }

                if (string.IsNullOrEmpty(oauthSource))
                {
                    oauthSource = serverUrl + "/OAuth/API-Key";
                }

                return(securedAuthenticator.DoOAuthRequestAsync(serverUrl, oauthSource, credentials.ApiKey));
            };
        }
Exemplo n.º 4
0
        private static async Task <string> TryObtainAuthToken(TokenFetcherConfiguration config)
        {
            var securedAuthenticator = new SecuredAuthenticator(autoRefreshToken: false);
            var result = await securedAuthenticator.DoOAuthRequestAsync(null, config.ServerUrl + "/OAuth/API-Key", config.ApiKey);

            using (var httpClient = new HttpClient())
            {
                result(httpClient);
                var authenticationHeaderValue = httpClient.DefaultRequestHeaders.Authorization;
                return(authenticationHeaderValue.Parameter);
            }
        }
Exemplo n.º 5
0
        private void InitializeSecurity()
        {
            if (Conventions.HandleUnauthorizedResponse != null)
            {
                return;                 // already setup by the user
            }
            var basicAuthenticator   = new BasicAuthenticator(credentials, ApiKey, jsonRequestFactory);
            var securedAuthenticator = new SecuredAuthenticator(ApiKey, basicAuthenticator);

            jsonRequestFactory.ConfigureRequest += basicAuthenticator.ConfigureRequest;
            jsonRequestFactory.ConfigureRequest += securedAuthenticator.ConfigureRequest;

#if !SILVERLIGHT
            Conventions.HandleUnauthorizedResponse = response =>
            {
                var oauthSource = response.Headers["OAuth-Source"];
                response.Close();

                if (string.IsNullOrEmpty(oauthSource) == false)
                {
                    return(basicAuthenticator.HandleOAuthResponse(oauthSource));
                }

                if (ApiKey == null)
                {
                    return(null);
                }
                oauthSource = Url + "/OAuth/API-Key";

                return(securedAuthenticator.DoOAuthRequest(oauthSource));
            };
#endif

            Conventions.HandleUnauthorizedResponseAsync = unauthorizedResponse =>
            {
                var oauthSource = unauthorizedResponse.Headers["OAuth-Source"];
                unauthorizedResponse.Close();

                if (string.IsNullOrEmpty(oauthSource) == false)
                {
                    return(basicAuthenticator.HandleOAuthResponseAsync(oauthSource));
                }

                if (ApiKey == null)
                {
                    return(null);
                }
                oauthSource = Url + "/OAuth/API-Key";

                return(securedAuthenticator.DoOAuthRequestAsync(oauthSource));
            };
        }
Exemplo n.º 6
0
        public void ConfigureRequest(RavenConnectionStringOptions options, HttpWebRequest request)
        {
            if (RequestTimeoutInMs.HasValue)
            {
                request.Timeout = RequestTimeoutInMs.Value;
            }

            if (options.ApiKey == null)
            {
                ICredentials credentialsToUse = CredentialCache.DefaultNetworkCredentials;
                if (options.Credentials != null)
                {
                    var networkCredentials = options.Credentials as NetworkCredential;
                    if (networkCredentials != null && options.AuthenticationScheme != null)
                    {
                        var credentialCache = new CredentialCache();
                        var uri             = new Uri(options.Url);
                        credentialCache.Add(new Uri(string.Format("{0}://{1}:{2}/", uri.Scheme, uri.Host, uri.Port)), options.AuthenticationScheme, networkCredentials);

                        credentialsToUse = credentialCache;
                    }
                    else
                    {
                        credentialsToUse = options.Credentials;
                    }
                }

                request.Credentials = credentialsToUse;
                return;
            }

            var webRequestEventArgs = new WebRequestEventArgs {
                Request = request, Credentials = new OperationCredentials(options.ApiKey, options.Credentials)
            };

            AbstractAuthenticator existingAuthenticator;

            if (authenticators.TryGetValue(GetCacheKey(options), out existingAuthenticator))
            {
                existingAuthenticator.ConfigureRequest(this, webRequestEventArgs);
            }
            else
            {
                var basicAuthenticator   = new BasicAuthenticator(enableBasicAuthenticationOverUnsecuredHttp: false);
                var securedAuthenticator = new SecuredAuthenticator();

                basicAuthenticator.ConfigureRequest(this, webRequestEventArgs);
                securedAuthenticator.ConfigureRequest(this, webRequestEventArgs);
            }
        }
Exemplo n.º 7
0
        public async Task CanGetTokenFromServer()
        {
            DoNotReuseServer();
            using (var store = GetDocumentStore())
            {
                StoreSampleDoc(store, "test/1");

                // Should get PreconditionFailed on Get without token
                Server.Configuration.Server.AnonymousUserAccessMode = AnonymousUserAccessModeValues.None;
                var client = new HttpClient();

                var result = await client.GetAsync(store.Url.ForDatabase(store.DefaultDatabase).Doc("test/1"));

                Assert.Equal(HttpStatusCode.PreconditionFailed, result.StatusCode);

                // Should throw on DoOAuthRequestAsync with unknown apiKey
                var securedAuthenticator = new SecuredAuthenticator();
                var exception            = await Assert.ThrowsAsync <InvalidOperationException>(async() =>
                                                                                                await securedAuthenticator.DoOAuthRequestAsync(store.Url + "/oauth/api-key", "super/secret"));

                Assert.Contains("Could not find api key: super", exception.Message);

                // Admin should be able to save apiKey
                Server.Configuration.Server.AnonymousUserAccessMode = AnonymousUserAccessModeValues.Admin;
                store.DatabaseCommands.GlobalAdmin.PutApiKey("super", apiKey);
                var doc = store.DatabaseCommands.GlobalAdmin.GetApiKey("super");
                Assert.NotNull(doc);

                // Should get token
                Server.Configuration.Server.AnonymousUserAccessMode = AnonymousUserAccessModeValues.None;
                var oauth = await securedAuthenticator.DoOAuthRequestAsync(store.Url + "/oauth/api-key", "super/secret");

                Assert.NotNull(securedAuthenticator.CurrentToken);
                Assert.NotEqual("", securedAuthenticator.CurrentToken);

                // Verify successfull get with valid token
                var authenticatedClient = new HttpClient();
                oauth(authenticatedClient);
                result = await authenticatedClient.GetAsync(store.Url.ForDatabase(store.DefaultDatabase).Doc("test/1"));

                Assert.Equal(HttpStatusCode.OK, result.StatusCode);
                Server.Configuration.Server.AnonymousUserAccessMode = AnonymousUserAccessModeValues.Admin;
            }
        }
Exemplo n.º 8
0
        public void ConfigureRequest(RavenConnectionStringOptions options, HttpWebRequest request)
        {
            if (RequestTimeoutInMs.HasValue)
            {
                request.Timeout = RequestTimeoutInMs.Value;
            }

            if (AllowWriteStreamBuffering.HasValue)
            {
                request.AllowWriteStreamBuffering = AllowWriteStreamBuffering.Value;
                if (AllowWriteStreamBuffering.Value == false)
                {
                    request.SendChunked = true;
                }
            }

            if (options.ApiKey == null)
            {
                request.Credentials = options.Credentials ?? CredentialCache.DefaultNetworkCredentials;
                return;
            }

            var webRequestEventArgs = new WebRequestEventArgs {
                Request = request, Credentials = new OperationCredentials(options.ApiKey, options.Credentials)
            };

            AbstractAuthenticator existingAuthenticator;

            if (authenticators.TryGetValue(GetCacheKey(options), out existingAuthenticator))
            {
                existingAuthenticator.ConfigureRequest(this, webRequestEventArgs);
            }
            else
            {
                var basicAuthenticator   = new BasicAuthenticator(enableBasicAuthenticationOverUnsecuredHttp: false);
                var securedAuthenticator = new SecuredAuthenticator();

                basicAuthenticator.ConfigureRequest(this, webRequestEventArgs);
                securedAuthenticator.ConfigureRequest(this, webRequestEventArgs);
            }
        }
Exemplo n.º 9
0
        private void InitializeSecurity()
        {
            if (Conventions.HandleUnauthorizedResponse != null)
            {
                return;                 // already setup by the user
            }
            if (String.IsNullOrEmpty(ApiKey) == false)
            {
                Credentials = null;
            }

            var basicAuthenticator   = new BasicAuthenticator(jsonRequestFactory.EnableBasicAuthenticationOverUnsecuredHttpEvenThoughPasswordsWouldBeSentOverTheWireInClearTextToBeStolenByHackers);
            var securedAuthenticator = new SecuredAuthenticator();

            jsonRequestFactory.ConfigureRequest += basicAuthenticator.ConfigureRequest;
            jsonRequestFactory.ConfigureRequest += securedAuthenticator.ConfigureRequest;

#if !SILVERLIGHT && !NETFX_CORE
            Conventions.HandleUnauthorizedResponse = (response, credentials) =>
            {
                var oauthSource = response.Headers["OAuth-Source"];

                if (string.IsNullOrEmpty(oauthSource) == false &&
                    oauthSource.EndsWith("/OAuth/API-Key", StringComparison.CurrentCultureIgnoreCase) == false)
                {
                    return(basicAuthenticator.DoOAuthRequest(oauthSource, credentials.ApiKey));
                }

                if (credentials.ApiKey == null)
                {
                    AssertUnauthorizedCredentialSupportWindowsAuth(response, credentials.Credentials);

                    return(null);
                }
                if (string.IsNullOrEmpty(oauthSource))
                {
                    oauthSource = Url + "/OAuth/API-Key";
                }

                return(securedAuthenticator.DoOAuthRequest(oauthSource, credentials.ApiKey));
            };
#endif

            Conventions.HandleForbiddenResponseAsync = (forbiddenResponse, credentials) =>
            {
                if (credentials.ApiKey == null)
                {
                    AssertForbiddenCredentialSupportWindowsAuth(forbiddenResponse);
                    return(null);
                }

                return(null);
            };

            Conventions.HandleUnauthorizedResponseAsync = (unauthorizedResponse, credentials) =>
            {
                var oauthSource = unauthorizedResponse.Headers["OAuth-Source"];

                if (string.IsNullOrEmpty(oauthSource) == false &&
                    oauthSource.EndsWith("/OAuth/API-Key", StringComparison.CurrentCultureIgnoreCase) == false)
                {
                    return(basicAuthenticator.HandleOAuthResponseAsync(oauthSource, credentials.ApiKey));
                }

                if (credentials.ApiKey == null)
                {
                    AssertUnauthorizedCredentialSupportWindowsAuth(unauthorizedResponse, credentials.Credentials);
                    return(null);
                }

                if (string.IsNullOrEmpty(oauthSource))
                {
                    oauthSource = this.Url + "/OAuth/API-Key";
                }

                return(securedAuthenticator.DoOAuthRequestAsync(Url, oauthSource, credentials.ApiKey));
            };
        }
Exemplo n.º 10
0
        private void InitializeSecurity()
        {
            if (Conventions.HandleUnauthorizedResponse != null)
            {
                return;                 // already setup by the user
            }
            if (String.IsNullOrEmpty(ApiKey) == false)
            {
                Credentials = null;
            }

            var basicAuthenticator   = new BasicAuthenticator(ApiKey, jsonRequestFactory);
            var securedAuthenticator = new SecuredAuthenticator(ApiKey);

            jsonRequestFactory.ConfigureRequest += basicAuthenticator.ConfigureRequest;
            jsonRequestFactory.ConfigureRequest += securedAuthenticator.ConfigureRequest;

#if !SILVERLIGHT
            Conventions.HandleUnauthorizedResponse = response =>
            {
                var oauthSource = response.Headers["OAuth-Source"];

                if (string.IsNullOrEmpty(oauthSource) == false &&
                    oauthSource.EndsWith("/OAuth/API-Key", StringComparison.CurrentCultureIgnoreCase) == false)
                {
                    return(basicAuthenticator.HandleOAuthResponse(oauthSource));
                }

                if (ApiKey == null)
                {
                    AssertUnuthorizedCredentialSupportWindowsAuth(response);

                    return(null);
                }
                oauthSource = Url + "/OAuth/API-Key";

                return(securedAuthenticator.DoOAuthRequest(oauthSource));
            };
#endif

            Conventions.HandleForbiddenResponseAsync = forbiddenResponse =>
            {
                if (ApiKey == null)
                {
                    AssertForbiddenCredentialSupportWindowsAuth(forbiddenResponse);
                    return(null);
                }

                return(null);
            };

            Conventions.HandleUnauthorizedResponseAsync = unauthorizedResponse =>
            {
                var oauthSource = unauthorizedResponse.Headers["OAuth-Source"];

                if (string.IsNullOrEmpty(oauthSource) == false &&
                    oauthSource.EndsWith("/OAuth/API-Key", StringComparison.CurrentCultureIgnoreCase) == false)
                {
                    return(basicAuthenticator.HandleOAuthResponseAsync(oauthSource));
                }

                if (ApiKey == null)
                {
                    AssertUnuthorizedCredentialSupportWindowsAuth(unauthorizedResponse);
                    return(null);
                }
                oauthSource = Url + "/OAuth/API-Key";

                return(securedAuthenticator.DoOAuthRequestAsync(oauthSource));
            };
        }