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.jivesoftware.openfire.http.HttpBindServlet.java

private void handleSessionRequest(String sid, HttpServletRequest request, HttpServletResponse response,
        Element rootNode) throws IOException {
    if (JiveGlobals.getBooleanProperty("log.httpbind.enabled", false)) {
        System.out.println(new Date() + ": HTTP RECV(" + sid + "): " + rootNode.asXML());
    }//from   ww  w  .  j  ava 2 s  .  c  o  m
    long rid = getLongAttribue(rootNode.attributeValue("rid"), -1);
    if (rid <= 0) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Body missing RID (Request ID)");
        return;
    }

    HttpSession session = sessionManager.getSession(sid);
    if (session == null) {
        Log.warn("Client provided invalid session: " + sid + ". [" + request.getRemoteAddr() + "]");
        response.sendError(HttpServletResponse.SC_NOT_FOUND, "Invalid SID.");
        return;
    }
    synchronized (session) {
        HttpConnection connection;
        try {
            connection = sessionManager.forwardRequest(rid, session, request.isSecure(), rootNode);
        } catch (HttpBindException e) {
            sendError(request, response, e.getBindingError(), session);
            return;
        } catch (HttpConnectionClosedException nc) {
            Log.error("Error sending packet to client.", nc);
            return;
        }

        String type = rootNode.attributeValue("type");
        String restartStream = rootNode
                .attributeValue(new QName("restart", rootNode.getNamespaceForPrefix("xmpp")));
        int pauseDuration = getIntAttribue(rootNode.attributeValue("pause"), -1);

        if ("terminate".equals(type)) {
            session.close();
            respond(session, request, response, createEmptyBody(true), request.getMethod());
        } else if ("true".equals(restartStream) && rootNode.elements().size() == 0) {
            try {
                respond(session, request, response, createSessionRestartResponse(session), request.getMethod());
            } catch (DocumentException e) {
                Log.error("Error sending session restart response to client.", e);
            }
        } else if (pauseDuration > 0 && pauseDuration <= session.getMaxPause()) {
            session.pause(pauseDuration);
            respond(session, request, response, createEmptyBody(false), request.getMethod());
            session.setLastResponseEmpty(true);
        } else {
            session.resetInactivityTimeout();
            connection.setContinuation(ContinuationSupport.getContinuation(request));
            request.setAttribute("request-session", connection.getSession());
            request.setAttribute("request", connection.getRequestId());
            request.setAttribute("connection", connection);
            try {
                respond(session, request, response, session.consumeResponse(connection), request.getMethod());
            } catch (HttpBindException e) {
                sendError(request, response, e.getBindingError(), session);
            }
        }
    }
}

From source file:io.seldon.api.service.AuthorizationServer.java

/**
 * @return token/*from  w  w  w. ja v a 2 s  .c  o m*/
 * Create and return an access token for a specific consumer.
 * It generates a new token even if the consumer has already a valid token active
 */
public Token getToken(HttpServletRequest req, boolean makeTransient) throws APIException {

    //init
    String consumerKey = null;
    String consumerSecret = null;
    Token token = null;
    //if request is null
    if (req == null) {
        throw new APIException(APIException.NOT_VALID_CONNECTION);
    }
    //retrieve from the request the consumer key and the consumer secret
    consumerKey = req.getParameter(Constants.CONSUMER_KEY);
    consumerSecret = req.getParameter(Constants.CONSUMER_SECRET);
    //check if the consumerId is set
    if (consumerKey == null || consumerKey.trim().equals("")) {
        throw new APIException(APIException.NOT_SPECIFIED_CONS_KEY);
    }
    //check if the consumerSecret is set
    if (consumerSecret == null || consumerSecret.trim().equals("")) {
        throw new APIException(APIException.NOT_SPECIFIED_CONS_SECRET);
    }
    //check if the consumer credentials are valid
    Consumer consumer = isConsumerValid(consumerKey, consumerSecret);
    //check if the consumer is secure and request is TLS
    if (consumer.isSecure() && !req.isSecure()) {
        throw new APIException(APIException.NOT_SSL_CONN);
    }
    token = new Token(consumer);
    //make the token persistent
    tokenPeer.saveToken(token);
    if (makeTransient) {
        //RAS-34 (ensure token is transient so JDO doesn't try to refresh against the read-replica the fields
        //Maybe a better solution?
        jdoFactory.getPersistenceManager(Constants.API_DB).makeTransient(token);
    }
    return token;
}

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

@Test
public void testShowGetLoginWithCookieAssertionAfterTimeBounds() throws CertificateEncodingException,
        WSSecurityException, SAXException, IOException, ParserConfigurationException {
    String samlRequest = authNRequestGet;
    HttpServletRequest request = mock(HttpServletRequest.class);
    Cookie cookie = mock(Cookie.class);

    Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
    calendar.add(Calendar.SECOND, -1);
    Date beforeNow = calendar.getTime();
    DateFormat dateFormat = new SimpleDateFormat(samlConditionDateFormat);
    dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));

    Element assertionElement = readDocument("/saml.xml").getDocumentElement();

    //Change the NotOnOrAfter Date on the SAML Assertion to be before "now"
    assertionElement.getElementsByTagName("saml2:Conditions").item(0).getAttributes()
            .getNamedItem("NotOnOrAfter").setNodeValue(dateFormat.format(beforeNow));

    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");

    idpEndpoint.cookieCache.cacheSamlAssertion("2", assertionElement);
    assertNotNull(idpEndpoint.cookieCache.getSamlAssertion("2"));

    Response response = idpEndpoint.showGetLogin(samlRequest, relayState, signatureAlgorithm, signature,
            request);/* w  ww. jav  a2s.  co  m*/

    assertThat(response.getEntity().toString(), containsString("<title>Login</title>"));
    assertNull(idpEndpoint.cookieCache.getSamlAssertion("2"));
}

From source file:com.twelve.capital.external.feed.util.HttpImpl.java

@Override
public String getProtocol(HttpServletRequest request) {
    return getProtocol(request.isSecure());
}

From source file:com.twelve.capital.external.feed.util.HttpImpl.java

@Override
public String protocolize(String url, HttpServletRequest request) {
    return protocolize(url, request.isSecure());
}

From source file:org.openmhealth.reference.servlet.Version1.java

/**
 * Builds the base URL for the request that came in. This is everything up
 * to our web applications base, e.g. "http://localhost:8080/omh".
 * /*from   ww w  . j  ava  2s  .  c  o m*/
 * @param httpRequest
 *        The original HTTP request.
 * 
 * @return The base URL for the request.
 */
private String buildRootUrl(final HttpServletRequest httpRequest) {
    // It must be a HTTP request.
    StringBuilder builder = new StringBuilder("http");

    // If security was used add the "s" to make it "https".
    if (httpRequest.isSecure()) {
        builder.append('s');
    }

    // Add the protocol separator.
    builder.append("://");

    // Add the name of the server where the request was sent.
    builder.append(httpRequest.getServerName());

    // Add the port separator and the port.
    builder.append(':').append(httpRequest.getServerPort());

    // Add the context path, e.g. "/omh".
    builder.append(httpRequest.getContextPath());

    // Return the root URL.
    return builder.toString();
}

From source file:org.apache.nifi.web.api.DataTransferResource.java

private Peer constructPeer(final HttpServletRequest req, final InputStream inputStream,
        final OutputStream outputStream, final String portId, final String transactionId) {
    String clientHostName = req.getRemoteHost();
    try {/*from   ww  w . ja  v  a2  s.  c o m*/
        // req.getRemoteHost returns IP address, try to resolve hostname to be consistent with RAW protocol.
        final InetAddress clientAddress = InetAddress.getByName(clientHostName);
        clientHostName = clientAddress.getHostName();
    } catch (UnknownHostException e) {
        logger.info("Failed to resolve client hostname {}, due to {}", clientHostName, e.getMessage());
    }
    final int clientPort = req.getRemotePort();

    final PeerDescription peerDescription = new PeerDescription(clientHostName, clientPort, req.isSecure());

    final NiFiUser user = NiFiUserUtils.getNiFiUser();
    final String userDn = user == null ? null : user.getIdentity();
    final HttpServerCommunicationsSession commSession = new HttpServerCommunicationsSession(inputStream,
            outputStream, transactionId, userDn);

    boolean useCompression = false;
    final String useCompressionStr = req.getHeader(HANDSHAKE_PROPERTY_USE_COMPRESSION);
    if (!isEmpty(useCompressionStr) && Boolean.valueOf(useCompressionStr)) {
        useCompression = true;
    }

    final String requestExpiration = req.getHeader(HANDSHAKE_PROPERTY_REQUEST_EXPIRATION);
    final String batchCount = req.getHeader(HANDSHAKE_PROPERTY_BATCH_COUNT);
    final String batchSize = req.getHeader(HANDSHAKE_PROPERTY_BATCH_SIZE);
    final String batchDuration = req.getHeader(HANDSHAKE_PROPERTY_BATCH_DURATION);

    commSession.putHandshakeParam(HandshakeProperty.PORT_IDENTIFIER, portId);
    commSession.putHandshakeParam(HandshakeProperty.GZIP, String.valueOf(useCompression));

    if (!isEmpty(requestExpiration)) {
        commSession.putHandshakeParam(REQUEST_EXPIRATION_MILLIS, requestExpiration);
    }
    if (!isEmpty(batchCount)) {
        commSession.putHandshakeParam(BATCH_COUNT, batchCount);
    }
    if (!isEmpty(batchSize)) {
        commSession.putHandshakeParam(BATCH_SIZE, batchSize);
    }
    if (!isEmpty(batchDuration)) {
        commSession.putHandshakeParam(BATCH_DURATION, batchDuration);
    }

    if (peerDescription.isSecure()) {
        final NiFiUser nifiUser = NiFiUserUtils.getNiFiUser();
        logger.debug("initiating peer, nifiUser={}", nifiUser);
        commSession.setUserDn(nifiUser.getIdentity());
    }

    // TODO: Followed how SocketRemoteSiteListener define peerUrl and clusterUrl, but it can be more meaningful values, especially for clusterUrl.
    final String peerUrl = "nifi://" + clientHostName + ":" + clientPort;
    final String clusterUrl = "nifi://localhost:" + req.getLocalPort();

    return new Peer(peerDescription, commSession, peerUrl, clusterUrl);
}

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

private Response showLoginPage(String samlRequest, String relayState, String signatureAlgorithm,
        String signature, HttpServletRequest request, Binding binding, String template, String originalBinding)
        throws WSSecurityException {
    String responseStr;//from   ww  w . j  a va  2s.c  o m
    AuthnRequest authnRequest = null;
    try {
        Map<String, Object> responseMap = new HashMap<>();
        binding.validator().validateRelayState(relayState);
        authnRequest = binding.decoder().decodeRequest(samlRequest);
        authnRequest.getIssueInstant();
        binding.validator().validateAuthnRequest(authnRequest, samlRequest, relayState, signatureAlgorithm,
                signature, strictSignature);
        if (!request.isSecure()) {
            throw new IllegalArgumentException("Authn Request must use TLS.");
        }
        X509Certificate[] certs = (X509Certificate[]) request.getAttribute(CERTIFICATES_ATTR);
        boolean hasCerts = (certs != null && certs.length > 0);
        boolean hasCookie = hasValidCookie(request, authnRequest.isForceAuthn());
        if ((authnRequest.isPassive() && hasCerts) || hasCookie) {
            LOGGER.debug("Received Passive & PKI AuthnRequest.");
            org.opensaml.saml.saml2.core.Response samlpResponse;
            try {
                samlpResponse = handleLogin(authnRequest, Idp.PKI, request, authnRequest.isPassive(),
                        hasCookie);
                LOGGER.debug("Passive & PKI AuthnRequest logged in successfully.");
            } catch (SecurityServiceException e) {
                LOGGER.error(e.getMessage(), e);
                return getErrorResponse(relayState, authnRequest, StatusCode.AUTHN_FAILED, binding);
            } catch (WSSecurityException e) {
                LOGGER.error(e.getMessage(), e);
                return getErrorResponse(relayState, authnRequest, StatusCode.REQUEST_DENIED, binding);
            } catch (SimpleSign.SignatureException | ConstraintViolationException e) {
                LOGGER.error(e.getMessage(), e);
                return getErrorResponse(relayState, authnRequest, StatusCode.REQUEST_UNSUPPORTED, binding);
            }
            LOGGER.debug("Returning Passive & PKI SAML Response.");
            NewCookie cookie = null;
            if (hasCookie) {
                cookieCache.addActiveSp(getCookie(request).getValue(), authnRequest.getIssuer().getValue());
            } else {
                cookie = createCookie(request, samlpResponse);
                if (cookie != null) {
                    cookieCache.addActiveSp(cookie.getValue(), authnRequest.getIssuer().getValue());
                }
            }
            logAddedSp(authnRequest);

            return binding.creator().getSamlpResponse(relayState, authnRequest, samlpResponse, cookie,
                    template);
        } else {
            LOGGER.debug("Building the JSON map to embed in the index.html page for login.");
            Document doc = DOMUtils.createDocument();
            doc.appendChild(doc.createElement("root"));
            String authn = DOM2Writer.nodeToString(OpenSAMLUtil.toDom(authnRequest, doc, false));
            String encodedAuthn = RestSecurity.deflateAndBase64Encode(authn);
            responseMap.put(PKI, hasCerts);
            responseMap.put(SAML_REQ, encodedAuthn);
            responseMap.put(RELAY_STATE, relayState);
            String assertionConsumerServiceURL = ((ResponseCreatorImpl) binding.creator())
                    .getAssertionConsumerServiceURL(authnRequest);
            responseMap.put(ACS_URL, assertionConsumerServiceURL);
            responseMap.put(SSOConstants.SIG_ALG, signatureAlgorithm);
            responseMap.put(SSOConstants.SIGNATURE, signature);
            responseMap.put(ORIGINAL_BINDING, originalBinding);
        }

        String json = Boon.toJson(responseMap);

        LOGGER.debug("Returning index.html page.");
        responseStr = indexHtml.replace(IDP_STATE_OBJ, json);
        return Response.ok(responseStr).build();
    } catch (IllegalArgumentException e) {
        LOGGER.error(e.getMessage(), e);
        if (authnRequest != null) {
            try {
                return getErrorResponse(relayState, authnRequest, StatusCode.REQUEST_UNSUPPORTED, binding);
            } catch (IOException | SimpleSign.SignatureException e1) {
                LOGGER.error(e1.getMessage(), e1);
            }
        }
    } catch (UnsupportedOperationException e) {
        LOGGER.error(e.getMessage(), e);
        if (authnRequest != null) {
            try {
                return getErrorResponse(relayState, authnRequest, StatusCode.UNSUPPORTED_BINDING, binding);
            } catch (IOException | SimpleSign.SignatureException e1) {
                LOGGER.error(e1.getMessage(), e1);
            }
        }
    } catch (SimpleSign.SignatureException e) {
        LOGGER.error("Unable to validate AuthRequest Signature", e);
    } catch (IOException e) {
        LOGGER.error("Unable to decode AuthRequest", e);
    } catch (ValidationException e) {
        LOGGER.error("AuthnRequest schema validation failed.", e);
    }

    return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
}

From source file:net.java.jaspicoil.MSPacSpnegoServerAuthModule.java

/**
 * This method can easily be overridden to provide extra groups
 * /*from  w w  w  .  j a va 2 s .  com*/
 * @param request
 *            the request
 * @param serverSubject
 *            the subject of the server containing the KerberosKey
 * @param options
 *            the options passed from the JASPIC context
 * @return the mutable set of extra roles to add or null if an error happens
 */
public Set<String> fetchExtraGroups(HttpServletRequest request, Subject serverSubject, Map<String, ?> options) {
    final Set<String> groups = new HashSet<String>();
    // Check for request context groups
    // Test channel security
    if (request.isSecure()) {
        groups.add(GROUP_SECURED_CHANNEL);
        debug("The request context is secured so the {0} group was added to the user", GROUP_SECURED_CHANNEL);
    } else {
        groups.add(GROUP_UNSECURED_CHANNEL);
        debug("The request context is not secured so the {0} group was added to the user",
                GROUP_UNSECURED_CHANNEL);
    }
    return groups;
}

From source file:org.sakaiproject.util.RequestFilter.java

/**
 * Compute the URL that would return to this server based on the current request.
 *
 * Note: this method is used by the one in /sakai-kernel-util/src/main/java/org/sakaiproject/util/Web.java
 *
 * @param req/*from  w w w.j  av  a  2 s .  c  o  m*/
 *        The request.
 * @return The URL back to this server based on the current request.
 */
public static String serverUrl(HttpServletRequest req) {
    String transport = null;
    int port = 0;
    boolean secure = false;

    // if force.url.secure is set (to a https port number), use https and this port
    String forceSecure = System.getProperty("sakai.force.url.secure");
    if (forceSecure != null && !"".equals(forceSecure)) {
        // allow the value to be forced to 0 or blank to disable this
        int portNum;
        try {
            portNum = Integer.parseInt(forceSecure);
        } catch (NumberFormatException e) {
            throw new IllegalArgumentException(
                    "force.url.secure must be set to the port number which should be a numeric value > 0 (or set it to 0 to disable secure urls)",
                    e);
        }
        if (portNum > 0) {
            transport = "https";
            port = portNum;
            secure = true;
        }
    } else {
        // otherwise use the request scheme and port
        transport = req.getScheme();
        port = req.getServerPort();
        secure = req.isSecure();
    }

    StringBuilder url = new StringBuilder();
    url.append(transport);
    url.append("://");
    url.append(req.getServerName());
    if (((port != 80) && (!secure)) || ((port != 443) && secure)) {
        url.append(":");
        url.append(port);
    }

    return url.toString();
}