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.apache.roller.weblogger.webservices.atomprotocol.RollerAtomHandler.java

private String authenticationOAUTH(HttpServletRequest request, HttpServletResponse response) {
    try {//from   w  w  w.j  a va  2s  .c o  m
        OAuthManager omgr = WebloggerFactory.getWeblogger().getOAuthManager();
        OAuthMessage requestMessage = OAuthServlet.getMessage(request, null);
        OAuthAccessor accessor = omgr.getAccessor(requestMessage);
        omgr.getValidator().validateMessage(requestMessage, accessor);
        return (String) accessor.consumer.getProperty("userId");

    } catch (Exception ex) {
        log.debug("ERROR authenticating user", ex);
        String realm = (request.isSecure()) ? "https://" : "http://";
        realm += request.getLocalName();
        try {
            OAuthServlet.handleException(response, ex, realm, true);
        } catch (Exception ioe) {
            log.debug("ERROR writing error response", ioe);
        }
    }
    return null;
}

From source file:ru.org.linux.comment.AddCommentController.java

/**
 *  ?./*from   w w  w . java  2  s.co  m*/
 *
 * @param add      WEB-, ?? 
 * @param errors      ? 
 * @param request   ?  web-
 * @return  web-
 * @throws Exception
 */
@RequestMapping(value = "/add_comment.jsp", method = RequestMethod.POST)
@CSRFNoAuto
public ModelAndView addComment(@ModelAttribute("add") @Valid CommentRequest add, Errors errors,
        HttpServletRequest request, @ModelAttribute("ipBlockInfo") IPBlockInfo ipBlockInfo) throws Exception {

    Map<String, Object> formParams = new HashMap<>();

    User user = commentService.getCommentUser(add, request, errors);

    commentService.checkPostData(add, user, ipBlockInfo, request, errors);
    commentService.prepareReplyto(add, formParams, request);

    String msg = commentService.getCommentBody(add, user, errors);
    Comment comment = commentService.getComment(add, user, request);

    if (add.getTopic() != null) {
        formParams.put("postscoreInfo", TopicPermissionService.getPostScoreInfo(add.getTopic().getPostScore()));

        topicPermissionService.checkCommentsAllowed(add.getTopic(), user, errors);
        formParams.put("comment",
                commentPrepareService.prepareCommentForEdit(comment, msg, request.isSecure()));
    }

    if (add.isPreviewMode() || errors.hasErrors() || comment == null) {
        ModelAndView modelAndView = new ModelAndView("add_comment", formParams);
        add.setMsg(StringUtil.escapeForceHtml(add.getMsg()));
        return modelAndView;
    }

    int msgid = commentService.create(comment, msg, request.getRemoteAddr(),
            request.getHeader("X-Forwarded-For"));
    searchQueueSender.updateComment(msgid);

    String returnUrl = "jump-message.jsp?msgid=" + add.getTopic().getId() + "&cid=" + msgid;
    return new ModelAndView(new RedirectView(returnUrl));
}

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

@Test
public void testLoginForceAuthnCookie() throws SecurityServiceException, WSSecurityException, IOException {
    String samlRequest = RestSecurity.deflateAndBase64Encode(authNRequestGetForce);
    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);
    idpEndpoint.setStrictSignature(false);

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

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

    assertThat(response.getEntity().toString(), containsString("<title>Login</title>"));
}

From source file:fr.xebia.servlet.filter.XForwardedFilterTest.java

/**
 * Test {@link XForwardedFilter} in Jetty
 *//*from   w  w  w.ja  va2 s. c  om*/
@Test
public void testWithJetty() throws Exception {

    // SETUP
    int port = 6666;
    Server server = new Server(port);
    Context context = new Context(server, "/", Context.SESSIONS);

    // mostly default configuration : enable "x-forwarded-proto"
    XForwardedFilter xforwardedFilter = new XForwardedFilter();
    MockFilterConfig filterConfig = new MockFilterConfig();
    filterConfig.addInitParameter(XForwardedFilter.PROTOCOL_HEADER_PARAMETER, "x-forwarded-proto");
    // Following is needed on ipv6 stacks..
    filterConfig.addInitParameter(XForwardedFilter.INTERNAL_PROXIES_PARAMETER,
            InetAddress.getByName("localhost").getHostAddress());
    xforwardedFilter.init(filterConfig);
    context.addFilter(new FilterHolder(xforwardedFilter), "/*", Handler.REQUEST);

    MockHttpServlet mockServlet = new MockHttpServlet();
    context.addServlet(new ServletHolder(mockServlet), "/test");

    server.start();
    try {
        // TEST
        HttpURLConnection httpURLConnection = (HttpURLConnection) new URL("http://localhost:" + port + "/test")
                .openConnection();
        String expectedRemoteAddr = "my-remote-addr";
        httpURLConnection.addRequestProperty("x-forwarded-for", expectedRemoteAddr);
        httpURLConnection.addRequestProperty("x-forwarded-proto", "https");

        // VALIDATE

        Assert.assertEquals(HttpURLConnection.HTTP_OK, httpURLConnection.getResponseCode());
        HttpServletRequest request = mockServlet.getRequest();
        Assert.assertNotNull(request);

        // VALIDATE X-FOWARDED-FOR
        Assert.assertEquals(expectedRemoteAddr, request.getRemoteAddr());
        Assert.assertEquals(expectedRemoteAddr, request.getRemoteHost());

        // VALIDATE X-FORWARDED-PROTO
        Assert.assertTrue(request.isSecure());
        Assert.assertEquals("https", request.getScheme());
        Assert.assertEquals(443, request.getServerPort());
    } finally {
        server.stop();
    }
}

From source file:com.osbitools.ws.shared.auth.SamlSecurityProvider.java

public String getDefServiceLocationUrl(HttpServletRequest req) {
    return "http:" + (req.isSecure() ? "s" : "") + "//" + req.getServerName() + ":" + req.getServerPort()
            + req.getContextPath();//from   w  ww. ja  v  a  2 s .co  m
}

From source file:ru.org.linux.topic.TopicListController.java

/**
 * @param request//from  ww w. j  a  va2s .  com
 * @param modelAndView
 * @param topicListForm
 * @param messages
 */
private void prepareTopicsForPlainOrRss(HttpServletRequest request, ModelAndView modelAndView,
        TopicListRequest topicListForm, List<Topic> messages) {
    boolean rss = topicListForm.getOutput() != null && "rss".equals(topicListForm.getOutput());
    if (rss) {
        modelAndView.addObject("messages", prepareService.prepareMessages(messages, request.isSecure()));
        modelAndView.setViewName("section-rss");
    } else {
        Template tmpl = Template.getTemplate(request);
        modelAndView.addObject("messages", prepareService.prepareMessagesForUser(messages, request.isSecure(),
                tmpl.getCurrentUser(), tmpl.getProf(), false));

        modelAndView.setViewName("view-news");
    }
}

From source file:org.apache.ranger.rest.AssetREST.java

@GET
@Path("/policyList/{repository}")
@Encoded//from   w ww. java  2s.  c om
public String getResourceJSON(@Context HttpServletRequest request, @PathParam("repository") String repository) {

    String epoch = request.getParameter("epoch");
    X509Certificate[] certchain = (X509Certificate[]) request
            .getAttribute("javax.servlet.request.X509Certificate");
    String ipAddress = request.getHeader("X-FORWARDED-FOR");
    boolean isSecure = request.isSecure();
    String policyCount = request.getParameter("policyCount");
    String agentId = request.getParameter("agentId");
    Long lastKnowPolicyVersion = Long.valueOf(-1);

    if (ipAddress == null) {
        ipAddress = request.getRemoteAddr();
    }

    boolean httpEnabled = PropertiesUtil.getBooleanProperty("ranger.service.http.enabled", true);

    ServicePolicies servicePolicies = null;

    try {
        servicePolicies = serviceREST.getServicePoliciesIfUpdated(repository, lastKnowPolicyVersion, 0L,
                agentId, request);
    } catch (Exception excp) {
        logger.error("failed to retrieve policies for repository " + repository, excp);
    }

    RangerService service = serviceUtil.getServiceByName(repository);
    List<RangerPolicy> policies = servicePolicies != null ? servicePolicies.getPolicies() : null;
    long policyUpdTime = (servicePolicies != null && servicePolicies.getPolicyUpdateTime() != null)
            ? servicePolicies.getPolicyUpdateTime().getTime()
            : 0l;
    VXAsset vAsset = serviceUtil.toVXAsset(service);
    List<VXResource> vResourceList = new ArrayList<VXResource>();

    if (policies != null) {
        for (RangerPolicy policy : policies) {
            vResourceList.add(serviceUtil.toVXResource(policy, service));
        }
    }

    String file = assetMgr.getLatestRepoPolicy(vAsset, vResourceList, policyUpdTime, certchain, httpEnabled,
            epoch, ipAddress, isSecure, policyCount, agentId);

    return file;
}

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

@Test
public void testPassiveLoginPkiFail()
        throws SecurityServiceException, WSSecurityException, CertificateEncodingException, IOException {
    String samlRequest = authNRequestPassivePkiGet;
    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);
    idpEndpoint.setStrictSignature(false);

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

    Response response = idpEndpoint.showGetLogin(samlRequest, relayState, signatureAlgorithm, signature,
            request);
    String responseStr = StringUtils.substringBetween(response.getEntity().toString(), "SAMLResponse=",
            "&RelayState");
    responseStr = URLDecoder.decode(responseStr, "UTF-8");
    responseStr = RestSecurity.inflateBase64(responseStr);

    //the only cookie that should exist is the "1" cookie so "2" should send us to the login webapp
    assertThat(responseStr, containsString("status:AuthnFailed"));
}

From source file:org.jivesoftware.multiplexer.net.http.HttpBindServlet.java

private void handleSessionRequest(String sid, 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;/*ww w .  j a  va2 s. co m*/
    }

    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");
        if ("terminate".equals(type)) {
            session.close();
            respond(response, createEmptyBody(), request.getMethod());
        } else {
            connection.setContinuation(ContinuationSupport.getContinuation(request, connection));
            request.setAttribute("request-session", connection.getSession());
            request.setAttribute("request", connection.getRequestId());
            try {
                respond(response, session.getResponse(connection.getRequestId()), request.getMethod());
            } catch (HttpBindException e) {
                sendError(request, response, e.getBindingError(), session);
            }
        }
    }
}

From source file:org.nuxeo.ecm.platform.auth.saml.SAMLAuthenticationProvider.java

@Override
public UserIdentificationInfo handleRetrieveIdentity(HttpServletRequest request, HttpServletResponse response) {

    HttpServletRequestAdapter inTransport = new HttpServletRequestAdapter(request);
    SAMLBinding binding = getBinding(inTransport);

    // Check if we support this binding
    if (binding == null) {
        return null;
    }//from   w  w  w.j a v a2  s . c o  m

    HttpServletResponseAdapter outTransport = new HttpServletResponseAdapter(response, request.isSecure());

    // Create and populate the context
    SAMLMessageContext context = new BasicSAMLMessageContext();
    context.setInboundMessageTransport(inTransport);
    context.setOutboundMessageTransport(outTransport);
    populateLocalContext(context);

    // Decode the message
    try {
        binding.decode(context);
    } catch (org.opensaml.xml.security.SecurityException | MessageDecodingException e) {
        log.error("Error during SAML decoding", e);
        return null;
    }

    // Set Peer context info if needed
    try {
        if (context.getPeerEntityId() == null) {
            context.setPeerEntityId(getIdPDescriptor().getEntityID());
        }
        if (context.getPeerEntityMetadata() == null) {
            context.setPeerEntityMetadata(getIdPDescriptor());
        }
        if (context.getPeerEntityRole() == null) {
            context.setPeerEntityRole(IDPSSODescriptor.DEFAULT_ELEMENT_NAME);
        }
    } catch (MetadataProviderException e) {
        //
    }

    // Check for a response processor for this profile
    AbstractSAMLProfile processor = getProcessor(context);

    if (processor == null) {
        log.warn("Unsupported profile encountered in the context " + context.getCommunicationProfileId());
        return null;
    }

    // Set the communication profile
    context.setCommunicationProfileId(processor.getProfileIdentifier());

    // Delegate handling the message to the processor
    SAMLObject message = context.getInboundSAMLMessage();

    // Handle SLO
    // TODO - Try to handle IdP initiated SLO somewhere else
    if (processor instanceof SLOProfile) {
        SLOProfile slo = (SLOProfile) processor;
        try {
            // Handle SLO response
            if (message instanceof LogoutResponse) {
                slo.processLogoutResponse(context);
                // Handle SLO request
            } else if (message instanceof LogoutRequest) {
                SAMLCredential credential = getSamlCredential(request);
                slo.processLogoutRequest(context, credential);
            }
        } catch (SAMLException e) {
            log.debug("Error processing SAML message", e);
        }
        return null;
    }

    // Handle SSO
    SAMLCredential credential;

    try {
        credential = ((WebSSOProfile) processor).processAuthenticationResponse(context);
    } catch (SAMLException e) {
        log.error("Error processing SAML message", e);
        sendError(request, ERROR_AUTH);
        return null;
    }

    String userId = userResolver.findOrCreateNuxeoUser(credential);

    if (userId == null) {
        log.warn("Failed to resolve user with NameID \"" + credential.getNameID().getValue() + "\".");
        sendError(request, ERROR_USER);
        return null;
    }

    // Store session id in a cookie
    if (credential.getSessionIndexes() != null && !credential.getSessionIndexes().isEmpty()) {
        String nameValue = credential.getNameID().getValue();
        String nameFormat = credential.getNameID().getFormat();
        String sessionId = credential.getSessionIndexes().get(0);
        addCookie(response, SAML_SESSION_KEY, sessionId + "|" + nameValue + "|" + nameFormat);
    }

    // Redirect to URL in relay state if any
    HttpSession session = request.getSession(!response.isCommitted());
    if (session != null) {
        if (StringUtils.isNotEmpty(credential.getRelayState())) {
            session.setAttribute(NXAuthConstants.START_PAGE_SAVE_KEY, credential.getRelayState());
        }
    }

    return new UserIdentificationInfo(userId, userId);
}