//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes: //ORIGINAL LINE: @Test public void retrieveCustomTransactionTimeout() public virtual void RetrieveCustomTransactionTimeout() { when(_request.getHeader(MAX_EXECUTION_TIME_HEADER)).thenReturn("100"); Log log = LogProvider.getLog(typeof(HttpServletRequest)); long transactionTimeout = getTransactionTimeout(_request, log); assertEquals("Transaction timeout should be retrieved.", 100, transactionTimeout); LogProvider.assertNoLoggingOccurred(); }
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes: //ORIGINAL LINE: @Test public void startTransactionWithCustomTimeout() public virtual void StartTransactionWithCustomTimeout() { when(_request.getHeader(HttpHeaderUtils.MAX_EXECUTION_TIME_HEADER)).thenReturn(CUSTOM_TRANSACTION_TIMEOUT.ToString()); CypherExecutor cypherExecutor = new CypherExecutor(_database, _logProvider); cypherExecutor.Start(); cypherExecutor.CreateTransactionContext(QUERY, VirtualValues.emptyMap(), _request); verify(_databaseQueryService).beginTransaction(KernelTransaction.Type.@implicit, AUTH_DISABLED, CUSTOM_TRANSACTION_TIMEOUT, TimeUnit.MILLISECONDS); _logProvider.assertNoLoggingOccurred(); }
private static ServletRequest Request(string userAgent) { HttpServletRequest request = mock(typeof(HttpServletRequest)); when(request.getHeader("User-Agent")).thenReturn(userAgent); return(request); }
private string BaseURL(HttpServletRequest request) { StringBuilder url = request.RequestURL; string baseURL = url.substring(0, url.Length - request.RequestURI.length()) + "/"; return(XForwardUtil.externalUri(baseURL, request.getHeader(X_FORWARD_HOST_HEADER_KEY), request.getHeader(X_FORWARD_PROTO_HEADER_KEY))); }
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#: //ORIGINAL LINE: public void doFilter(javax.servlet.ServletRequest servletRequest, javax.servlet.ServletResponse servletResponse, javax.servlet.FilterChain filterChain) throws java.io.IOException, javax.servlet.ServletException public override void DoFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) { ValidateRequestType(servletRequest); ValidateResponseType(servletResponse); //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': //ORIGINAL LINE: final javax.servlet.http.HttpServletRequest request = (javax.servlet.http.HttpServletRequest) servletRequest; HttpServletRequest request = ( HttpServletRequest )servletRequest; //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': //ORIGINAL LINE: final javax.servlet.http.HttpServletResponse response = (javax.servlet.http.HttpServletResponse) servletResponse; HttpServletResponse response = ( HttpServletResponse )servletResponse; try { LoginContext loginContext = AuthDisabledLoginContext; string userAgent = request.getHeader(HttpHeaders.USER_AGENT); JettyHttpConnection.updateUserForCurrentConnection(loginContext.Subject().username(), userAgent); filterChain.doFilter(new AuthorizedRequestWrapper(BASIC_AUTH, "neo4j", request, loginContext), servletResponse); } catch (AuthorizationViolationException e) { UnauthorizedAccess(e.Message).accept(response); } }
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes: //ORIGINAL LINE: @Test public void shouldSwallowAnyExceptionsThrownByTheRequest() throws java.io.IOException, javax.servlet.ServletException //JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#: public virtual void ShouldSwallowAnyExceptionsThrownByTheRequest() { HttpServletRequest request = mock(typeof(HttpServletRequest)); when(request.getHeader(anyString())).thenThrow(new Exception()); _filter.doFilter(request, null, _filterChain); }
public virtual AuthenticationResult extractAuthenticatedUser(HttpServletRequest request, ProcessEngine engine) { string authorizationHeader = request.getHeader(HttpHeaders.AUTHORIZATION); if (!string.ReferenceEquals(authorizationHeader, null) && authorizationHeader.StartsWith(BASIC_AUTH_HEADER_PREFIX, StringComparison.Ordinal)) { string encodedCredentials = authorizationHeader.Substring(BASIC_AUTH_HEADER_PREFIX.Length); string decodedCredentials = StringHelper.NewString(Base64.decodeBase64(encodedCredentials)); int firstColonIndex = decodedCredentials.IndexOf(":", StringComparison.Ordinal); if (firstColonIndex == -1) { return(AuthenticationResult.unsuccessful()); } else { string userName = decodedCredentials.Substring(0, firstColonIndex); string password = decodedCredentials.Substring(firstColonIndex + 1); if (isAuthenticated(engine, userName, password)) { return(AuthenticationResult.successful(userName)); } else { return(AuthenticationResult.unsuccessful(userName)); } } } else { return(AuthenticationResult.unsuccessful()); } }
private void echoHeader(HttpServletRequest req, HttpServletResponse resp) { string s = req.getHeader("Echo-Header"); if (!string.ReferenceEquals(s, null)) { resp.setHeader("Echo-Header", s); } }
public static string getIp(HttpServletRequest request) { if (null == request) { return null; } string ip = request.getHeader("x-forwarded-for"); if (!validateIp(ip)) { ip = request.getHeader("Proxy-Client-IP"); if (!validateIp(ip)) { ip = request.getHeader("WL-Proxy-Client-IP"); if (!validateIp(ip)) { ip = request.RemoteAddr; } } } return ip; }
/// <summary> /// Retrieve custom transaction timeout in milliseconds from numeric <seealso cref="MAX_EXECUTION_TIME_HEADER"/> request /// header. /// If header is not set returns -1. </summary> /// <param name="request"> http request </param> /// <param name="errorLog"> errors log for header parsing errors </param> /// <returns> custom timeout if header set, -1 otherwise or when value is not a valid number. </returns> public static long GetTransactionTimeout(HttpServletRequest request, Log errorLog) { string headerValue = request.getHeader(MAX_EXECUTION_TIME_HEADER); if (!string.ReferenceEquals(headerValue, null)) { try { return(long.Parse(headerValue)); } catch (System.FormatException e) { errorLog.Error(string.Format("Fail to parse `{0}` header with value: '{1}'. Should be a positive number.", MAX_EXECUTION_TIME_HEADER, headerValue), e); } } return(GraphDatabaseSettings.UNSPECIFIED_TIMEOUT); }
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#: //ORIGINAL LINE: public void handle(String target, org.eclipse.jetty.server.Request baseRequest, javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws java.io.IOException public override void Handle(string target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) { PrintWriter @out = response.Writer; response.ContentType = MimeTypes.Type.APPLICATION_JSON.asString(); string path = request.PathInfo; string expectedPath = string.format(KubernetesResolver.KubernetesClient.PATH, ExpectedNamespace); string labelSelector = request.getParameter("labelSelector"); string auth = request.getHeader(HttpHeader.AUTHORIZATION.name()); string expectedAuth = "Bearer " + ExpectedAuthToken; if (!expectedPath.Equals(path)) { response.Status = HttpServletResponse.SC_BAD_REQUEST; @out.println(Fail("Unexpected path: " + path)); } else if (!ExpectedLabelSelector.Equals(labelSelector)) { response.Status = HttpServletResponse.SC_BAD_REQUEST; @out.println(Fail("Unexpected labelSelector: " + labelSelector)); } else if (!expectedAuth.Equals(auth)) { response.Status = HttpServletResponse.SC_BAD_REQUEST; @out.println(Fail("Unexpected auth header value: " + auth)); } else if (!"GET".Equals(request.Method)) { response.Status = HttpServletResponse.SC_BAD_REQUEST; @out.println(Fail("Unexpected method: " + request.Method)); } else { response.Status = HttpServletResponse.SC_OK; if (!string.ReferenceEquals(Body, null)) { @out.println(Body); } } baseRequest.Handled = true; }
/// <summary> /// In order to avoid browsers popping up an auth box when using the Neo4j Browser, it sends us a special header. /// When we get that special header, we send a crippled authentication challenge back that the browser does not /// understand, which lets the Neo4j Browser handle auth on its own. /// /// Otherwise, we send a regular basic auth challenge. This method adds the appropriate header depending on the /// inbound request. /// </summary> private static ThrowingConsumer <HttpServletResponse, IOException> RequestAuthentication(HttpServletRequest req, ThrowingConsumer <HttpServletResponse, IOException> responseGen) { if ("true".Equals(req.getHeader("X-Ajax-Browser-Auth"))) { return(res => { responseGen.Accept(res); res.addHeader(HttpHeaders.WWW_AUTHENTICATE, "None"); }); } else { return(res => { responseGen.Accept(res); res.addHeader(HttpHeaders.WWW_AUTHENTICATE, "Basic realm=\"Neo4j\""); }); } }
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#: //ORIGINAL LINE: public void doFilter(javax.servlet.ServletRequest servletRequest, javax.servlet.ServletResponse servletResponse, javax.servlet.FilterChain filterChain) throws java.io.IOException, javax.servlet.ServletException public override void DoFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) { try { //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': //ORIGINAL LINE: final javax.servlet.http.HttpServletRequest request = (javax.servlet.http.HttpServletRequest) servletRequest; HttpServletRequest request = ( HttpServletRequest )servletRequest; string ua = request.getHeader("User-Agent"); if (!string.ReferenceEquals(ua, null) && ua.Length > 0) { _output.add(ua.Split(" ", true)[0]); } } catch (Exception) { // We're fine with that } filterChain.doFilter(servletRequest, servletResponse); }
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes: //ORIGINAL LINE: @Test public void shouldRequireValidAuthorizationHeader() throws Exception //JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#: public virtual void ShouldRequireValidAuthorizationHeader() { // Given //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': //ORIGINAL LINE: final AuthorizationEnabledFilter filter = new AuthorizationEnabledFilter(() -> authManager, logProvider); AuthorizationEnabledFilter filter = new AuthorizationEnabledFilter(() => _authManager, _logProvider); when(_servletRequest.Method).thenReturn("GET"); when(_servletRequest.ContextPath).thenReturn("/db/data"); when(_servletRequest.getHeader(HttpHeaders.AUTHORIZATION)).thenReturn("NOT A VALID VALUE"); // When filter.DoFilter(_servletRequest, _servletResponse, _filterChain); // Then verifyNoMoreInteractions(_filterChain); verify(_servletResponse).Status = 400; verify(_servletResponse).addHeader(HttpHeaders.CONTENT_TYPE, "application/json; charset=UTF-8"); assertThat(_outputStream.ToString(StandardCharsets.UTF_8.name()), containsString("\"code\" : \"Neo.ClientError.Request.InvalidFormat\"")); assertThat(_outputStream.ToString(StandardCharsets.UTF_8.name()), containsString("\"message\" : \"Invalid authentication header.\"")); }
protected override string getHeader(string name) { return(_HttpServletRequest.getHeader(name)); }
public override string getHeader(String name) { return(_request.getHeader(name)); }
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#: //ORIGINAL LINE: public void doFilter(javax.servlet.ServletRequest servletRequest, javax.servlet.ServletResponse servletResponse, javax.servlet.FilterChain filterChain) throws java.io.IOException, javax.servlet.ServletException public override void DoFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) { ValidateRequestType(servletRequest); ValidateResponseType(servletResponse); //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': //ORIGINAL LINE: final javax.servlet.http.HttpServletRequest request = (javax.servlet.http.HttpServletRequest) servletRequest; HttpServletRequest request = ( HttpServletRequest )servletRequest; //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': //ORIGINAL LINE: final javax.servlet.http.HttpServletResponse response = (javax.servlet.http.HttpServletResponse) servletResponse; HttpServletResponse response = ( HttpServletResponse )servletResponse; string userAgent = request.getHeader(HttpHeaders.USER_AGENT); // username is only known after authentication, make connection aware of the user-agent JettyHttpConnection.updateUserForCurrentConnection(null, userAgent); //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': //ORIGINAL LINE: final String path = request.getContextPath() + (request.getPathInfo() == null ? "" : request.getPathInfo()); string path = request.ContextPath + (request.PathInfo == null ? "" : request.PathInfo); if (request.Method.Equals("OPTIONS") || Whitelisted(path)) { // NOTE: If starting transactions with access mode on whitelisted uris should be possible we need to // wrap servletRequest in an AuthorizedRequestWrapper here filterChain.doFilter(servletRequest, servletResponse); return; } //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': //ORIGINAL LINE: final String header = request.getHeader(javax.ws.rs.core.HttpHeaders.AUTHORIZATION); string header = request.getHeader(HttpHeaders.AUTHORIZATION); if (string.ReferenceEquals(header, null)) { RequestAuthentication(request, _noHeader).accept(response); return; } //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': //ORIGINAL LINE: final String[] usernameAndPassword = extractCredential(header); string[] usernameAndPassword = ExtractCredential(header); if (usernameAndPassword == null) { _badHeader.accept(response); return; } //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': //ORIGINAL LINE: final String username = usernameAndPassword[0]; string username = usernameAndPassword[0]; //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': //ORIGINAL LINE: final String password = usernameAndPassword[1]; string password = usernameAndPassword[1]; try { LoginContext securityContext = Authenticate(username, password); // username is now known, make connection aware of both username and user-agent JettyHttpConnection.updateUserForCurrentConnection(username, userAgent); switch (securityContext.Subject().AuthenticationResult) { case PASSWORD_CHANGE_REQUIRED: if (!_passwordChangeWhitelist.matcher(path).matches()) { PasswordChangeRequired(username, BaseURL(request)).accept(response); return; } // fall through case SUCCESS: try { filterChain.doFilter(new AuthorizedRequestWrapper(BASIC_AUTH, username, request, securityContext), servletResponse); } catch (AuthorizationViolationException e) { UnauthorizedAccess(e.Message).accept(response); } return; case TOO_MANY_ATTEMPTS: _tooManyAttempts.accept(response); return; default: _log.warn("Failed authentication attempt for '%s' from %s", username, request.RemoteAddr); RequestAuthentication(request, _invalidCredential).accept(response); break; } } catch (InvalidAuthTokenException e) { RequestAuthentication(request, InvalidAuthToken(e.Message)).accept(response); } catch (AuthProviderTimeoutException) { _authProviderTimeout.accept(response); } catch (AuthProviderFailedException) { _authProviderFailed.accept(response); } }