Example usage for javax.servlet.http HttpServletRequest isSecure

List of usage examples for javax.servlet.http HttpServletRequest isSecure

Introduction

In this page you can find the example usage for javax.servlet.http HttpServletRequest isSecure.

Prototype

public boolean isSecure();

Source Link

Document

Returns a boolean indicating whether this request was made using a secure channel, such as HTTPS.

Usage

From source file:org.nunux.poc.portal.ProxyServlet.java

/**
 * Executes the {@link HttpMethod} passed in and sends the proxy response
 * back to the client via the given {@link HttpServletResponse}
 *
 * @param httpMethodProxyRequest An object representing the proxy request to
 * be made//from   w w w  .j  a va2s.  c o  m
 * @param httpServletResponse An object by which we can send the proxied
 * response back to the client
 * @throws IOException Can be thrown by the {@link HttpClient}.executeMethod
 * @throws ServletException Can be thrown to indicate that another error has
 * occurred
 */
private void executeProxyRequest(HttpMethod httpMethodProxyRequest, HttpServletRequest httpServletRequest,
        HttpServletResponse httpServletResponse) throws IOException, ServletException {

    if (httpServletRequest.isSecure()) {
        Protocol.registerProtocol("https", new Protocol("https", new EasySSLProtocolSocketFactory(), 443));
    }

    // Create a default HttpClient
    HttpClient httpClient = new HttpClient();
    httpMethodProxyRequest.setFollowRedirects(false);
    // Execute the request
    int intProxyResponseCode = httpClient.executeMethod(httpMethodProxyRequest);
    InputStream response = httpMethodProxyRequest.getResponseBodyAsStream();

    // Check if the proxy response is a redirect
    // The following code is adapted from org.tigris.noodle.filters.CheckForRedirect
    // Hooray for open source software
    if (intProxyResponseCode >= HttpServletResponse.SC_MULTIPLE_CHOICES
            /*
            * 300
            */ && intProxyResponseCode < HttpServletResponse.SC_NOT_MODIFIED /*
                                                                              * 304
                                                                              */) {
        String stringStatusCode = Integer.toString(intProxyResponseCode);
        String stringLocation = httpMethodProxyRequest.getResponseHeader(STRING_LOCATION_HEADER).getValue();
        if (stringLocation == null) {
            throw new ServletException("Received status code: " + stringStatusCode + " but no "
                    + STRING_LOCATION_HEADER + " header was found in the response");
        }
        // Modify the redirect to go to this proxy servlet rather that the proxied host
        String stringMyHostName = httpServletRequest.getServerName();
        if (httpServletRequest.getServerPort() != 80) {
            stringMyHostName += ":" + httpServletRequest.getServerPort();
        }
        stringMyHostName += httpServletRequest.getContextPath();
        if (followRedirects) {
            if (stringLocation.contains("jsessionid")) {
                Cookie cookie = new Cookie("JSESSIONID",
                        stringLocation.substring(stringLocation.indexOf("jsessionid=") + 11));
                cookie.setPath("/");
                httpServletResponse.addCookie(cookie);
                //debug("redirecting: set jessionid (" + cookie.getValue() + ") cookie from URL");
            } else if (httpMethodProxyRequest.getResponseHeader("Set-Cookie") != null) {
                Header header = httpMethodProxyRequest.getResponseHeader("Set-Cookie");
                String[] cookieDetails = header.getValue().split(";");
                String[] nameValue = cookieDetails[0].split("=");

                if (nameValue[0].equalsIgnoreCase("jsessionid")) {
                    httpServletRequest.getSession().setAttribute("jsessionid" + this.getProxyHostAndPort(),
                            nameValue[1]);
                    debug("redirecting: store jsessionid: " + nameValue[1]);
                } else {
                    Cookie cookie = new Cookie(nameValue[0], nameValue[1]);
                    cookie.setPath("/");
                    //debug("redirecting: setting cookie: " + cookie.getName() + ":" + cookie.getValue() + " on " + cookie.getPath());
                    httpServletResponse.addCookie(cookie);
                }
            }
            httpServletResponse.sendRedirect(
                    stringLocation.replace(getProxyHostAndPort() + this.getProxyPath(), stringMyHostName));
            return;
        }
    } else if (intProxyResponseCode == HttpServletResponse.SC_NOT_MODIFIED) {
        // 304 needs special handling.  See:
        // http://www.ics.uci.edu/pub/ietf/http/rfc1945.html#Code304
        // We get a 304 whenever passed an 'If-Modified-Since'
        // header and the data on disk has not changed; server
        // responds w/ a 304 saying I'm not going to send the
        // body because the file has not changed.
        httpServletResponse.setIntHeader(STRING_CONTENT_LENGTH_HEADER_NAME, 0);
        httpServletResponse.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
        return;
    }

    // Pass the response code back to the client
    httpServletResponse.setStatus(intProxyResponseCode);

    // Pass response headers back to the client
    Header[] headerArrayResponse = httpMethodProxyRequest.getResponseHeaders();
    for (Header header : headerArrayResponse) {
        if (header.getName().equals("Transfer-Encoding") && header.getValue().equals("chunked")
                || header.getName().equals("Content-Encoding") && header.getValue().equals("gzip") || // don't copy gzip header
                header.getName().equals("WWW-Authenticate")) { // don't copy WWW-Authenticate header so browser doesn't prompt on failed basic auth
            // proxy servlet does not support chunked encoding
        } else if (header.getName().equals("Set-Cookie")) {
            String[] cookieDetails = header.getValue().split(";");
            String[] nameValue = cookieDetails[0].split("=");
            if (nameValue[0].equalsIgnoreCase("jsessionid")) {
                httpServletRequest.getSession().setAttribute("jsessionid" + this.getProxyHostAndPort(),
                        nameValue[1]);
                debug("redirecting: store jsessionid: " + nameValue[1]);
            } else {
                httpServletResponse.setHeader(header.getName(), header.getValue());
            }
        } else {
            httpServletResponse.setHeader(header.getName(), header.getValue());
        }
    }

    List<Header> responseHeaders = Arrays.asList(headerArrayResponse);

    if (isBodyParameterGzipped(responseHeaders)) {
        debug("GZipped: true");
        int length = 0;

        if (!followRedirects && intProxyResponseCode == HttpServletResponse.SC_MOVED_TEMPORARILY) {
            String gz = httpMethodProxyRequest.getResponseHeader(STRING_LOCATION_HEADER).getValue();
            httpServletResponse.setStatus(HttpServletResponse.SC_OK);
            intProxyResponseCode = HttpServletResponse.SC_OK;
            httpServletResponse.setHeader(STRING_LOCATION_HEADER, gz);
        } else {
            final byte[] bytes = ungzip(httpMethodProxyRequest.getResponseBody());
            length = bytes.length;
            response = new ByteArrayInputStream(bytes);
        }
        httpServletResponse.setContentLength(length);
    }

    // Send the content to the client
    debug("Received status code: " + intProxyResponseCode, "Response: " + response);

    //httpServletResponse.getWriter().write(response);
    copy(response, httpServletResponse.getOutputStream());
}

From source file:org.codice.ddf.security.idp.server.IdpEndpointTest.java

@Test
public void testFailedLogin() throws SecurityServiceException {
    String samlRequest = authNRequestGet;
    HttpServletRequest request = mock(HttpServletRequest.class);

    SecurityManager securityManager = mock(SecurityManager.class);
    when(securityManager.getSubject(anyObject())).thenThrow(new SecurityServiceException("test"));
    idpEndpoint.setSecurityManager(securityManager);

    when(request.isSecure()).thenReturn(true);
    when(request.getRequestURL()).thenReturn(requestURL);
    when(request.getAttribute(ContextPolicy.ACTIVE_REALM)).thenReturn("*");

    Response response = idpEndpoint.processLogin(samlRequest, relayState, Idp.GUEST, signatureAlgorithm,
            signature, SamlProtocol.REDIRECT_BINDING, request);

    assertThat(response.getStatus(), is(401));
}

From source file:com.erudika.scoold.utils.ScooldUtils.java

public void setSecurityHeaders(HttpServletRequest request, HttpServletResponse response) {
    // CSP Header
    if (Config.getConfigBoolean("csp_header_enabled", true)) {
        response.addHeader("Content-Security-Policy",
                Config.getConfigParam("csp_header", getDefaultContentSecurityPolicy(request.isSecure())));
    }/*from   w ww .j a v  a2s.c  o  m*/
    // HSTS Header
    if (Config.getConfigBoolean("hsts_header_enabled", true)) {
        response.addHeader("Strict-Transport-Security", "max-age=31536000; includeSubDomains");
    }
    // Frame Options Header
    if (Config.getConfigBoolean("framing_header_enabled", true)) {
        response.addHeader("X-Frame-Options", "SAMEORIGIN");
    }
    // XSS Header
    if (Config.getConfigBoolean("xss_header_enabled", true)) {
        response.addHeader("X-XSS-Protection", "1; mode=block");
    }
    // Content Type Header
    if (Config.getConfigBoolean("contenttype_header_enabled", true)) {
        response.addHeader("X-Content-Type-Options", "nosniff");
    }
    // Referrer Header
    if (Config.getConfigBoolean("referrer_header_enabled", true)) {
        response.addHeader("Referrer-Policy", "strict-origin");
    }
}

From source file:de.kp.ames.web.core.service.ServiceImpl.java

public void sendImageDownloadResponse(ImageUtil image, HttpServletRequest request, HttpServletResponse response)
        throws Exception {

    if (image == null)
        return;//from w  w  w  .  j  a  v  a 2  s.com

    String clientPath = request.getParameter("clientpath");
    if (clientPath == null)
        return;

    /*
     * Distinguish between secure and non-secure download requests
     */
    if (request.isSecure()) {

        response.addHeader("Cache-Control", "no-cache");
        response.addHeader("Pragma", "no-cache");

        response.addHeader("Expires", "-1");

    } else {

        response.addHeader("Cache-Control", "private");
        response.addHeader("Pragma", "public");

    }

    /*
     * Signal download ready with cookie
     */
    Cookie cookie = new Cookie("DOWNLOAD_READY", "END");
    cookie.setPath(clientPath);
    response.addCookie(cookie);

    /*
     * Determine user agent
     */
    String ua = request.getHeader("User-Agent").toLowerCase();
    boolean isIE = ((ua.indexOf("msie 6.0") != -1) || (ua.indexOf("msie 7.0") != -1)) ? true : false;

    /*
     * Encode file name
     */
    String encFileName = URLEncoder.encode(image.getFilename(), "UTF-8");

    if (isIE) {

        response.addHeader("Content-Disposition", "attachment;  filename=\"" + encFileName + "\"");
        response.addHeader("Connection", "close");

        response.setContentType("application/force-download;  name=\"" + encFileName + "\"");

    } else {

        response.addHeader("Content-Disposition", "attachment; filename=\"" + encFileName + "\"");

        response.setContentType("application/octet-stream; name=\"" + encFileName + "\"");
        response.setContentLength(image.getLength());

    }

    // finally set http status
    response.setStatus(HttpServletResponse.SC_OK);

    OutputStream os = response.getOutputStream();

    os.write(image.getBytes());
    os.close();
}

From source file:org.jivesoftware.openfire.http.HttpBindServlet.java

private void createNewSession(HttpServletRequest request, HttpServletResponse response, Element rootNode)
        throws IOException {
    long rid = getLongAttribue(rootNode.attributeValue("rid"), -1);
    if (rid <= 0) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Body missing RID (Request ID)");
        return;//from  w w w  . j a  va  2  s  .c  om
    }

    try {
        X509Certificate[] certificates = (X509Certificate[]) request
                .getAttribute("javax.servlet.request.X509Certificate");
        HttpConnection connection = new HttpConnection(rid, request.isSecure(), certificates);
        InetAddress address = InetAddress.getByName(request.getRemoteAddr());
        connection.setSession(sessionManager.createSession(address, rootNode, connection));
        if (JiveGlobals.getBooleanProperty("log.httpbind.enabled", false)) {
            System.out.println(new Date() + ": HTTP RECV(" + connection.getSession().getStreamID().getID()
                    + "): " + rootNode.asXML());
        }
        respond(request, response, connection, request.getMethod());
    } catch (UnauthorizedException e) {
        // Server wasn't initialized yet.
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Server Not initialized");
    } catch (HttpBindException e) {
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }

}

From source file:de.kp.ames.web.core.service.ServiceImpl.java

/**
 * A specific method to enable file download even in a secure (SSL) environment
 * /*from  w  w  w.  j a v  a2  s  . co  m*/
 * @param file
 * @param request
 * @param response
 * @throws IOException
 */
public void sendFileDownloadResponse(FileUtil file, HttpServletRequest request, HttpServletResponse response)
        throws IOException {

    if (file == null)
        return;

    String clientPath = request.getParameter("clientpath");
    if (clientPath == null)
        return;

    /*
     * Distinguish between secure and non-secure download requests
     */
    if (request.isSecure()) {

        response.addHeader("Cache-Control", "no-cache");
        response.addHeader("Pragma", "no-cache");

        response.addHeader("Expires", "-1");

    } else {

        response.addHeader("Cache-Control", "private");
        response.addHeader("Pragma", "public");

    }

    /*
     * Determine user agent
     */
    String ua = request.getHeader("User-Agent").toLowerCase();
    boolean isIE = ((ua.indexOf("msie 6.0") != -1) || (ua.indexOf("msie 7.0") != -1)) ? true : false;

    /*
     * Encode file name
     */
    String encFileName = URLEncoder.encode(file.getFilename(), "UTF-8");

    if (isIE) {

        response.addHeader("Content-Disposition", "attachment;  filename=\"" + encFileName + "\"");
        response.addHeader("Connection", "close");

        response.setContentType("application/force-download;  name=\"" + encFileName + "\"");

    } else {

        response.addHeader("Content-Disposition", "attachment; filename=\"" + encFileName + "\"");

        response.setContentType("application/octet-stream; name=\"" + encFileName + "\"");
        response.setContentLength(file.getLength());

    }

    /*
     * Signal download ready with cookie
     */
    Cookie cookie = new Cookie("DOWNLOAD_READY", "END");
    cookie.setPath(clientPath);
    response.addCookie(cookie);

    // finally set http status
    response.setStatus(HttpServletResponse.SC_OK);

    OutputStream os = response.getOutputStream();

    os.write(file.getFile());
    os.close();

}

From source file:org.springframework.security.web.authentication.rememberme.AbstractRememberMeServices.java

/**
 * Sets the cookie on the response.//w  w w .  j  av a 2  s .  com
 *
 * By default a secure cookie will be used if the connection is secure. You can set
 * the {@code useSecureCookie} property to {@code false} to override this. If you set
 * it to {@code true}, the cookie will always be flagged as secure. By default the cookie
 * will be marked as HttpOnly.
 *
 * @param tokens the tokens which will be encoded to make the cookie value.
 * @param maxAge the value passed to {@link Cookie#setMaxAge(int)}
 * @param request the request
 * @param response the response to add the cookie to.
 */
protected void setCookie(String[] tokens, int maxAge, HttpServletRequest request,
        HttpServletResponse response) {
    String cookieValue = encodeCookie(tokens);
    Cookie cookie = new Cookie(cookieName, cookieValue);
    cookie.setMaxAge(maxAge);
    cookie.setPath(getCookiePath(request));
    if (cookieDomain != null) {
        cookie.setDomain(cookieDomain);
    }
    if (maxAge < 1) {
        cookie.setVersion(1);
    }

    if (useSecureCookie == null) {
        cookie.setSecure(request.isSecure());
    } else {
        cookie.setSecure(useSecureCookie);
    }

    cookie.setHttpOnly(true);

    response.addCookie(cookie);
}

From source file:org.codice.ddf.security.idp.server.IdpEndpointTest.java

@Test
public void testExpiredLoginCookie() throws SecurityServiceException, WSSecurityException {
    String samlRequest = authNRequestGet;
    HttpServletRequest request = mock(HttpServletRequest.class);
    Cookie cookie = mock(Cookie.class);

    SecurityManager securityManager = mock(SecurityManager.class);
    when(securityManager.getSubject(anyObject())).thenThrow(new SecurityServiceException("test"));
    idpEndpoint.setSecurityManager(securityManager);

    when(request.isSecure()).thenReturn(true);
    when(request.getRequestURL()).thenReturn(requestURL);
    when(request.getAttribute(ContextPolicy.ACTIVE_REALM)).thenReturn("*");
    when(request.getCookies()).thenReturn(new Cookie[] { cookie });
    when(cookie.getName()).thenReturn(IdpEndpoint.COOKIE);
    when(cookie.getValue()).thenReturn("2");

    Response response = idpEndpoint.showGetLogin(samlRequest, relayState, signatureAlgorithm, signature,
            request);/*ww  w . java  2 s .c o  m*/

    //the only cookie that should exist is the "1" cookie so "2" should send us to the login webapp
    assertThat(response.getEntity().toString(), containsString("<title>Login</title>"));
}

From source file:org.codice.ddf.security.idp.server.IdpEndpointTest.java

@Test
public void testPassiveLoginPkiSignatureErrorPost()
        throws SecurityServiceException, WSSecurityException, CertificateEncodingException, IOException {
    String samlRequest = authNRequestPassivePkiPost;
    HttpServletRequest request = mock(HttpServletRequest.class);
    X509Certificate x509Certificate = mock(X509Certificate.class);

    SecurityManager securityManager = mock(SecurityManager.class);
    when(securityManager.getSubject(anyObject())).thenThrow(new SecurityServiceException("test"));
    idpEndpoint.setSecurityManager(securityManager);

    when(request.isSecure()).thenReturn(true);
    when(request.getRequestURL()).thenReturn(requestURL);
    when(request.getAttribute(ContextPolicy.ACTIVE_REALM)).thenReturn("*");
    //dummy cert// ww w  . j  av  a  2s.co  m
    when((X509Certificate[]) request.getAttribute(requestCertificateAttributeName))
            .thenReturn(new X509Certificate[] { x509Certificate });
    when(x509Certificate.getEncoded()).thenReturn(new byte[48]);

    Response response = idpEndpoint.showPostLogin(samlRequest, relayState, request);

    assertThat(response.getStatus(), is(500));
}

From source file:com.streamsets.lib.security.http.SSOUserAuthenticator.java

Cookie createAuthCookie(HttpServletRequest httpReq, String authToken, long expiresMillis) {
    Cookie authCookie = new Cookie(getAuthCookieName(httpReq), authToken);
    authCookie.setPath("/");
    // if positive it is a persistent session, else a transient one and we don't have to set the cookie age
    if (expiresMillis > 0) {
        int secondsToLive = (int) ((expiresMillis - System.currentTimeMillis()) / 1000);
        authCookie.setMaxAge(secondsToLive);
    } else if (expiresMillis == 0) {
        // to delete the cookie
        authCookie.setMaxAge(0);//  w  w  w  .  j a  v  a  2 s  . c om
    }

    if (isDataCollector) {
        // When an SDC is accessing SCH, set the cookie based on the SDC's scheme
        authCookie.setSecure(httpReq.isSecure());
    } else {
        // When a browser accesses SCH, set the cookie based on the SCH endpoint
        authCookie.setSecure(dpmBaseUrl.startsWith("https"));
    }

    return authCookie;
}