HttpServletRequest request = (HttpServletRequest) req; HttpServletResponse response = (HttpServletResponse) res; String credentials = request.getHeader(HttpHeader.AUTHORIZATION.asString()); return Authentication.UNAUTHENTICATED; response.setHeader(HttpHeader.WWW_AUTHENTICATE.asString(), "basic realm=\"" + _loginService.getName() + '"'); response.sendError(HttpServletResponse.SC_UNAUTHORIZED); return Authentication.SEND_CONTINUE; } catch (IOException e) {
Response base_response = base_request.getResponse(); return new DeferredAuthentication(this); if (isLoginOrErrorPage(URIUtil.addPaths(request.getServletPath(),request.getPathInfo())) &&!DeferredAuthentication.isDeferred(response)) return new DeferredAuthentication(this); LOG.debug("jsecuritycheck {} {}",username,user); LOG.debug("authenticated {}->{}",form_auth,nuri); if (LOG.isDebugEnabled()) response.sendError(HttpServletResponse.SC_FORBIDDEN); response.setHeader(HttpHeader.CACHE_CONTROL.asString(),HttpHeaderValue.NO_CACHE.asString()); response.setDateHeader(HttpHeader.EXPIRES.asString(),1); dispatcher.forward(new FormRequest(request), new FormResponse(response)); base_response.sendRedirect(redirectCode, response.encodeRedirectURL(URIUtil.addPaths(request.getContextPath(),_formErrorPage))); response.setHeader(HttpHeader.CACHE_CONTROL.asString(),HttpHeaderValue.NO_CACHE.asString()); response.setDateHeader(HttpHeader.EXPIRES.asString(),1); dispatcher.forward(new FormRequest(request), new FormResponse(response)); base_response.sendRedirect(redirectCode, response.encodeRedirectURL(URIUtil.addPaths(request.getContextPath(),_formLoginPage)));
@Override public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException { String method = request.getMethod(); if (!HttpMethod.GET.is(method) && !HttpMethod.POST.is(method) && !HttpMethod.HEAD.is(method)) { baseRequest.setHandled(true); return; } baseRequest.setHandled(true); response.setContentType(MimeTypes.Type.TEXT_HTML_UTF_8.asString()); response.setHeader(HttpHeader.CACHE_CONTROL.asString(), "must-revalidate,no-cache,no-store"); ByteArrayOutputStream out = new ByteArrayOutputStream(4096); OutputStreamWriter writer = new OutputStreamWriter(out, Charsets.UTF_8); String reason=(response instanceof Response)?((Response)response).getReason():null; handleErrorPage(request, writer, response.getStatus(), reason); writer.flush(); response.setContentLength(out.size()); response.getOutputStream().write(out.toByteArray(), 0, out.size()); writer.close(); } }
public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { if (_newContextURL==null) return; String path=_newContextURL; if (!_discardPathInfo && request.getPathInfo()!=null) path=URIUtil.addPaths(path, request.getPathInfo()); StringBuilder location = URIUtil.hasScheme(path)?new StringBuilder():baseRequest.getRootURL(); location.append(path); if (!_discardQuery && request.getQueryString()!=null) { location.append('?'); String q=request.getQueryString(); q=q.replaceAll("\r\n?&=","!"); location.append(q); } response.setHeader(HttpHeader.LOCATION.asString(),location.toString()); if (_expires!=null) response.setHeader(HttpHeader.EXPIRES.asString(),_expires); response.setStatus(_permanent?HttpServletResponse.SC_MOVED_PERMANENTLY:HttpServletResponse.SC_FOUND); response.setContentLength(0); baseRequest.setHandled(true); }
String credentials = request.getHeader(HttpHeader.AUTHORIZATION.asString()); if (credentials != null) if (LOG.isDebugEnabled()) LOG.debug("Credentials: " + credentials); QuotedStringTokenizer tokenizer = new QuotedStringTokenizer(credentials, "=, ", true, false); final Digest digest = new Digest(request.getMethod()); String last = null; String name = null; String domain = request.getContextPath(); if (domain == null) domain = "/"; response.setHeader(HttpHeader.WWW_AUTHENTICATE.asString(), "Digest realm=\"" + _loginService.getName() + "\", domain=\"" + domain + "\", algorithm=MD5, qop=\"auth\"," + " stale=" + stale); response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
@Override protected void onProxyResponseFailure(final HttpServletRequest clientRequest, final HttpServletResponse proxyResponse, final Response serverResponse, final Throwable failure) { _log.warn(failure.toString()); if (proxyResponse.isCommitted()) { // Parent behavior super.onProxyResponseFailure(clientRequest, proxyResponse, serverResponse, failure); } else { proxyResponse.resetBuffer(); if (failure instanceof TimeoutException) { proxyResponse.setStatus(HttpServletResponse.SC_GATEWAY_TIMEOUT); } else { // Unavailable business server as JSON response proxyResponse.setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE); proxyResponse.setContentType("application/json"); try { proxyResponse.getOutputStream().write("{\"code\":\"business-down\"}".getBytes(StandardCharsets.UTF_8)); } catch (final IOException ioe) { _log.warn("Broken proxy stream", ioe); } } proxyResponse.setHeader(HttpHeader.CONNECTION.asString(), HttpHeaderValue.CLOSE.asString()); final AsyncContext asyncContext = clientRequest.getAsyncContext(); asyncContext.complete(); } }
private void sendConnectResponse(HttpServletRequest request, HttpServletResponse response, int statusCode) { try { response.setStatus(statusCode); response.setContentLength(0); if (statusCode != HttpServletResponse.SC_OK) response.setHeader(HttpHeader.CONNECTION.asString(), HttpHeaderValue.CLOSE.asString()); response.getOutputStream().close(); if (LOG.isDebugEnabled()) LOG.debug("CONNECT response sent {} {}", request.getProtocol(), response.getStatus()); } catch (IOException x) { if (LOG.isDebugEnabled()) LOG.debug("Could not send CONNECT response", x); } }
HttpServletResponse response = (HttpServletResponse)res; String header = request.getHeader(HttpHeader.AUTHORIZATION.asString()); String spnegoToken = getSpnegoToken(header); HttpSession httpSession = request.getSession(false); if (LOG.isDebugEnabled()) LOG.debug("Sending final token"); httpSession = request.getSession(true); httpSession.setAttribute(UserIdentityHolder.ATTRIBUTE, new UserIdentityHolder(identity)); if (LOG.isDebugEnabled()) LOG.debug("Sending intermediate challenge"); SpnegoUserPrincipal principal = (SpnegoUserPrincipal)identity.getUserPrincipal();
private void setHeaders(HttpServletResponse response, String resourcePath, String content) { response.setCharacterEncoding("UTF-8"); if (resourcePath.endsWith(".css")) { response.setContentType("text/css"); } else { response.setContentType("text/javascript"); } response.addDateHeader("EXPIRES", 0L); response.setDateHeader(HttpHeader.LAST_MODIFIED.asString(), new Date().getTime()); try { int contentLength = content.getBytes("UTF-8").length; response.setHeader(HttpHeader.CONTENT_LENGTH.asString(), Integer.toString(contentLength)); } catch (UnsupportedEncodingException e) { throw new RuntimeException("The JVM does not support javascript default encoding.", e); } }
protected void sendStatus(HttpServletResponse response, int status, Supplier<String> etag) throws IOException { response.setStatus(status); if (_etags && etag!=null) response.setHeader(HttpHeader.ETAG.asString(),etag.get()); response.flushBuffer(); }
protected void addXForwardedHeaders(HttpServletRequest clientRequest, Request proxyRequest) { proxyRequest.header(HttpHeader.X_FORWARDED_FOR, clientRequest.getRemoteAddr()); proxyRequest.header(HttpHeader.X_FORWARDED_PROTO, clientRequest.getScheme()); proxyRequest.header(HttpHeader.X_FORWARDED_HOST, clientRequest.getHeader(HttpHeader.HOST.asString())); proxyRequest.header(HttpHeader.X_FORWARDED_SERVER, clientRequest.getLocalName()); }
protected void sendProxyResponseError(HttpServletRequest clientRequest, HttpServletResponse proxyResponse, int status) { try { if (!proxyResponse.isCommitted()) { proxyResponse.resetBuffer(); proxyResponse.setHeader(HttpHeader.CONNECTION.asString(), HttpHeaderValue.CLOSE.asString()); } proxyResponse.sendError(status); } catch(Exception e) { _log.ignore(e); } finally { if (clientRequest.isAsyncStarted()) clientRequest.getAsyncContext().complete(); } }
protected boolean hasContent(HttpServletRequest clientRequest) { return clientRequest.getContentLength() > 0 || clientRequest.getContentType() != null || clientRequest.getHeader(HttpHeader.TRANSFER_ENCODING.asString()) != null; }
public static void setCaching(final HttpServletResponse response, final int expiresSeconds) { if (response instanceof org.eclipse.jetty.server.Response) { org.eclipse.jetty.server.Response r = (org.eclipse.jetty.server.Response) response; HttpFields fields = r.getHttpFields(); fields.remove(HttpHeader.LAST_MODIFIED); // if this field is present, the reload-time is a 10% fraction of ttl and other caching headers do not work fields.put(HttpHeader.CACHE_CONTROL, "public, no-store, max-age=" + Integer.toString(expiresSeconds)); // seconds fields.put(HttpHeader.CACHE_CONTROL, "public, max-age=" + Integer.toString(expiresSeconds)); // seconds response.setHeader(HttpHeader.LAST_MODIFIED.asString(), ""); // not really the best wqy to remove this header but there is no other option if(expiresSeconds == 0){ response.setHeader(HttpHeader.CACHE_CONTROL.asString(), "public, no-store, max-age=" + Integer.toString(expiresSeconds)); response.setHeader(HttpHeader.CACHE_CONTROL.asString(), "public, max-age=" + Integer.toString(expiresSeconds)); response.setDateHeader(HttpHeader.EXPIRES.asString(), System.currentTimeMillis() + expiresSeconds * 1000);
private static void respondFileContent( final Path filePath, final HttpServletRequest req, final HttpServletResponse resp) throws IOException, MultipleByteRangesException, NoLogFileException { if (Files.exists(filePath)) { final Enumeration<String> rangeHeaders = req.getHeaders(HttpHeader.RANGE.asString()); final List<InclusiveByteRange> byteRanges = satisfiableRanges(rangeHeaders, Files.size(filePath)); final long offset; final long size; if (byteRanges == null || 0 == byteRanges.size()) { offset = 0; size = LOG_PAGE_SIZE_LIMIT - 1; } else if (1 == byteRanges.size()) { final InclusiveByteRange byteRange = byteRanges.get(0); offset = byteRange.getFirst(); size = byteRange.getLast() + 1; } else { throw new MultipleByteRangesException("Unable to process more than 1 range header"); } writeFileRange(filePath, offset, size, resp.getOutputStream(), resp.getBufferSize()); } else { throw new NoLogFileException("The log file doesn't exist"); } }
void extractRequestTimestampAndApply( final HttpServletRequest req, final HttpServletResponse resp, final BiConsumer<Run, Long> runRespTimestampConsumer) throws IOException { final String reqTimestampRawValue = Collections.list(req.getHeaders(HttpHeader.IF_MATCH.toString())).stream() .findAny() .orElse(null); if (null == reqTimestampRawValue) { resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "Missing header: " + HttpHeader.IF_MATCH); } else { try { final long reqTimestamp = Long.parseLong(reqTimestampRawValue, 0x10); applyForActiveRunIfAny( resp, (run, resp_) -> runRespTimestampConsumer.accept(run, reqTimestamp)); } catch (final NumberFormatException e) { resp.sendError( HttpServletResponse.SC_BAD_REQUEST, "Invalid start time: " + reqTimestampRawValue); } } }
protected Set<String> findConnectionHeaders(HttpServletRequest clientRequest) { // Any header listed by the Connection header must be removed: // http://tools.ietf.org/html/rfc7230#section-6.1. Set<String> hopHeaders = null; Enumeration<String> connectionHeaders = clientRequest.getHeaders(HttpHeader.CONNECTION.asString()); while (connectionHeaders.hasMoreElements()) { String value = connectionHeaders.nextElement(); String[] values = value.split(","); for (String name : values) { name = name.trim().toLowerCase(Locale.ENGLISH); if (hopHeaders == null) hopHeaders = new HashSet<>(); hopHeaders.add(name); } } return hopHeaders; }