Example usage for javax.servlet.http HttpServletRequest isRequestedSessionIdFromCookie

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

Introduction

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

Prototype

public boolean isRequestedSessionIdFromCookie();

Source Link

Document

<p>Checks whether the requested session ID was conveyed to the server as an HTTP cookie.</p>

Usage

From source file:org.owasp.webgoat.service.SessionService.java

/**
 * Returns hints for current lesson/*from  ww  w.  j a  v a2 s  .c o  m*/
 *
 * @param session a {@link javax.servlet.http.HttpSession} object.
 * @param request a {@link javax.servlet.http.HttpServletRequest} object.
 * @return a {@link java.lang.String} object.
 */
@RequestMapping(value = "/session.mvc", produces = "application/json")
public @ResponseBody String showSession(HttpServletRequest request, HttpSession session) {
    StringBuilder sb = new StringBuilder();
    sb.append("id").append(" = ").append(session.getId()).append("\n");
    sb.append("created").append(" = ").append(new Date(session.getCreationTime())).append("\n");
    sb.append("last access").append(" = ").append(new Date(session.getLastAccessedTime())).append("\n");
    sb.append("timeout (secs)").append(" = ").append(session.getMaxInactiveInterval()).append("\n");
    sb.append("session from cookie?").append(" = ").append(request.isRequestedSessionIdFromCookie())
            .append("\n");
    sb.append("session from url?").append(" = ").append(request.isRequestedSessionIdFromURL()).append("\n");
    sb.append("=====================================\n");
    // get attributes
    List<String> attributes = new ArrayList<String>();
    Enumeration keys = session.getAttributeNames();
    while (keys.hasMoreElements()) {
        String name = (String) keys.nextElement();
        attributes.add(name);
    }
    Collections.sort(attributes);
    for (String attribute : attributes) {
        String value = session.getAttribute(attribute) + "";
        sb.append(attribute).append(" = ").append(value).append("\n");
    }
    return sb.toString();
}

From source file:edu.hawaii.its.hudson.security.Cas1SecurityRealm.java

@Override
public Filter createFilter(FilterConfig filterConfig) {
    AuthenticationFilter authenticationFilter = new AuthenticationFilter();
    authenticationFilter.setIgnoreInitConfiguration(true); // configuring here, not in web.xml
    authenticationFilter.setRenew(forceRenewal);
    authenticationFilter.setGateway(false);
    authenticationFilter.setCasServerLoginUrl(casServerUrl + "/login");
    authenticationFilter.setServerName(hudsonHostName);

    Cas10TicketValidationFilter validationFilter = new Cas10TicketValidationFilter();
    validationFilter.setIgnoreInitConfiguration(true); // configuring here, not in web.xml
    validationFilter.setRedirectAfterValidation(true);
    validationFilter.setServerName(hudsonHostName);
    validationFilter.setTicketValidator(new AbstractCasProtocolUrlBasedTicketValidator(casServerUrl) {

        protected String getUrlSuffix() {
            return "validate"; // version 1 protocol
        }/*w  w  w .  j a  va  2s .c o m*/

        protected Assertion parseResponseFromServer(final String response) throws TicketValidationException {
            if (!response.startsWith("yes")) {
                throw new TicketValidationException("CAS could not validate ticket.");
            }

            try {
                final BufferedReader reader = new BufferedReader(new StringReader(response));
                String mustBeYes = reader.readLine();
                assert mustBeYes.equals("yes") : mustBeYes;
                String username = reader.readLine();

                // parse optional extra validation attributes
                Collection roles = parseRolesFromValidationResponse(getParsedScript(), response);

                Map<String, Object> attributes = new HashMap<String, Object>();
                attributes.put(AUTH_KEY, new Cas1Authentication(username, roles)); // Acegi Authentication
                // CAS saves this Assertion in the session; we'll use the Authentication it's carrying.
                return new AssertionImpl(new AttributePrincipalImpl(username), attributes);
            } catch (final IOException e) {
                throw new TicketValidationException("Unable to parse CAS response.", e);
            }
        }
    });

    Filter casToAcegiContext = new OnlyDoFilter() {
        /**
         * Gets the authentication out of the session and puts it in Acegi's ThreadLocal on every request.
         * If we've made it this far down this FilterChain without a redirect,
         * then there must be a session with an authentication in it.
         * Using an Acegi filter to do this would require implementing more of the Acegi framework.
         */
        public void doFilter(final ServletRequest servletRequest, final ServletResponse servletResponse,
                final FilterChain filterChain) throws IOException, ServletException {
            final HttpServletRequest request = (HttpServletRequest) servletRequest;
            final HttpSession session = request.getSession(false);
            final Assertion assertion = (Assertion) session.getAttribute(AbstractCasFilter.CONST_CAS_ASSERTION);

            try {
                Cas1Authentication auth = (Cas1Authentication) assertion.getAttributes().get(AUTH_KEY);
                SecurityContextHolder.getContext().setAuthentication(auth);
                filterChain.doFilter(servletRequest, servletResponse);
            } finally {
                SecurityContextHolder.getContext().setAuthentication(null);
            }
        }
    };

    Filter jettyJsessionidRedirect = new OnlyDoFilter() {
        private final UrlPathHelper URL_PATH_HELPER = new UrlPathHelper();

        /**
         * Redirects to remove a jsessionid that a servlet container leaves in the URI if it's also in a cookie.
         * Jetty's getRequestURI() fails to remove the jsessionid (whether or not it's also in a cookie),
         * and this messes up Hudson's Stapler (as of version 1.323, at least).  CAS tickles this bug because
         * Jetty's encodeRedirectURL() is adding jsessionid on redirect after validation,
         * if it wasn't in a cookie on the request.  However, apparently Jetty also puts it in a cookie
         * on the redirect response, and Firefox accepts it.  This is a work-around to redirect that jsessionid
         * off the URL, since the cookie is enough, and the whole point of CAS redirect after validation is
         * to get a clean URL anyway (for bookmarks or restored browser tabs).
         * Other servlet containers and browser combinations may behave differently.
         * <p/>
         * This work-around does not attempt to make Hudson work in Jetty without cookies.
         * A potential approach for that would be for this filter to install an HttpServletRequestWrapper
         * that cleans jsessionid out of getRequestURI().  However, Hudson would also need to rewrite
         * all its URLs with the jsessionid, and I have no idea whether it does that.  That is an issue
         * between Hudson and Jetty, and we can just use cookies anyway.
         */
        public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)
                throws IOException, ServletException {
            if (request instanceof HttpServletRequest) {
                HttpServletRequest httpRequest = (HttpServletRequest) request;
                if (httpRequest.getRequestURI().contains(";jsessionid=")
                        && httpRequest.isRequestedSessionIdFromCookie()) {
                    // without (i.e., with relative) protocol, host, and port
                    String decodedCleanedUrl = URL_PATH_HELPER.getRequestUri(httpRequest);
                    if (StringUtils.isNotBlank(httpRequest.getQueryString())) {
                        decodedCleanedUrl += "?" + URL_PATH_HELPER.decodeRequestString(httpRequest,
                                httpRequest.getQueryString());
                    }
                    HttpServletResponse httpResponse = (HttpServletResponse) response;
                    httpResponse.sendRedirect(httpResponse.encodeRedirectURL(decodedCleanedUrl));
                    return;
                }
            }
            filterChain.doFilter(request, response);
        }
    };

    // todo: Exclude paths in Hudson#getTarget() from CAS filtering/Authorization?
    // todo: Add SecurityFilters.commonProviders?
    // todo: Or, is all that just to support on-demand authentication (upgrade)?

    return new ChainedServletFilter(authenticationFilter, validationFilter, casToAcegiContext,
            jettyJsessionidRedirect);
}

From source file:eu.eidas.node.AbstractNodeServlet.java

/**
 * Sets HTTPOnly Header on the session to prevent cookies from being accessed through
 * client-side script.//  ww w . ja  v a  2 s. com
 *
 * @param renewSession indicates that the session cookie will be renewed
 */
protected final void setHTTPOnlyHeaderToSession(final boolean renewSession, HttpServletRequest request,
        HttpServletResponse response) {
    if (request != null && request.getSession(false) != null) {
        // Renewing the session if necessary
        String currentSession = null;
        String messageLog = null;
        if (renewSession) {
            currentSession = sessionIdRegenerationInWebApp(request);
            messageLog = "http session Renewed : {}";
        } else {
            currentSession = request.getSession().getId();
            messageLog = "http session obtained from request : {}";
        }
        MDC.put(LoggingMarkerMDC.MDC_SESSIONID, currentSession);
        getLogger().info(LoggingMarkerMDC.SECURITY_SUCCESS, messageLog, currentSession);
        // changing session cookie to http only cookie
        if (request.getCookies() != null && request.isRequestedSessionIdFromCookie()) {
            //Session Id requested by the client, obtained from the cookie
            final String requestedSessionId = request.getRequestedSessionId();
            for (Cookie cookie : request.getCookies()) {
                getLogger().debug("Treating cookie [domain][path][name][value] : [{}][{}][{}][{}]",
                        cookie.getName(), cookie.getPath(), cookie.getName(), cookie.getValue());
                if (currentSession.equals(requestedSessionId)) {
                    // Removes old version
                    boolean isSecure = request.isSecure();
                    getLogger().debug("Cookie==session : Remove and replacing with HttpOnly {}",
                            cookie.toString());
                    getLogger().debug("Is using SSL?", isSecure);

                    //TODO: when migrating to servlet 3, use the cookie interface calls below instead of writing the http header
                    //
                    //NOSONAR                        cookie.setMaxAge(0);
                    //NOSONAR                        cookie.setPath(getServletContext().getContextPath());
                    //NOSONAR                 cookie.setDomain(request.getServerName());
                    //NOSONAR                 cookie.setSecure(isSecure);
                    //NOSONAR                 cookie.setHttpOnly(true);
                    //NOSONAR                 response.addCookie(cookie);

                    // Create new one httpOnly
                    StringBuilder httpOnlyCookie = new StringBuilder(cookie.getName())
                            .append(EIDASValues.EQUAL.toString()).append(cookie.getValue())
                            .append(EIDASValues.SEMICOLON.toString()).append(" ")
                            .append(EIDASValues.DOMAIN.toString()).append(EIDASValues.EQUAL.toString())
                            .append(request.getServerName()).append(EIDASValues.SEMICOLON.toString())
                            .append(" ").append(EIDASValues.PATH.toString())
                            .append(EIDASValues.EQUAL.toString()).append(getServletContext().getContextPath())
                            .append(EIDASValues.SEMICOLON.toString()).append(" ")
                            .append(EIDASValues.HTTP_ONLY.toString()).append(EIDASValues.SEMICOLON.toString())
                            .append(isSecure ? EIDASValues.SECURE.toString() : "");
                    response.setHeader(EIDASValues.SETCOOKIE.toString(), httpOnlyCookie.toString());
                }
            }
        }
        //cookie _csrf
        //            request.setAttribute("_csrf_header", "X-CSRF-TOKEN");
        //            UUID idOne = UUID.randomUUID();
        //            LOG.info("generate csrf id="+idOne);
        //            request.setAttribute("_csrf", idOne);
        response.setHeader("_csrf_header", "X-CSRF-TOKEN");
        UUID idOne = UUID.randomUUID();
        UUID idTwo = UUID.randomUUID();
        getLogger().info("generate csrf id1=" + idOne + " id2=" + idTwo);
        Cookie gato = new Cookie("_csrf", idOne.toString());
        response.addCookie(gato);
        response.setHeader("X-CSRF-TOKEN", idTwo.toString());

    } else {
        getLogger().warn(LoggingMarkerMDC.SECURITY_FAILURE, "Request or Session is null !");
    }
}

From source file:SessionSnoop.java

public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    res.setContentType("text/html");
    PrintWriter out = res.getWriter();

    HttpSession session = req.getSession();

    Integer count = (Integer) session.getAttribute("count");
    if (count == null)
        count = new Integer(1);
    else//from  www.j a v  a2  s.c  o  m
        count = new Integer(count.intValue() + 1);
    session.setAttribute("count", count);

    out.println("<HTML><HEAD><TITLE>Session Count</TITLE></HEAD>");
    out.println("<BODY><H1>Session Count</H1>");

    out.println("You've visited this page " + count + ((count == 1) ? " time." : " times."));

    out.println("<P>");

    out.println("<H3>Here is your saved session data:</H3>");
    Enumeration e = session.getAttributeNames();
    while (e.hasMoreElements()) {
        String name = (String) e.nextElement();
        out.println(name + ": " + session.getAttribute(name) + "<BR>");
    }

    out.println("<H3>Here are some vital stats on your session:</H3>");
    out.println("Session id: " + session.getId() + " <I>(keep it secret)</I><BR>");
    out.println("New session: " + session.isNew() + "<BR>");
    out.println("Timeout: " + session.getMaxInactiveInterval());
    out.println("<I>(" + session.getMaxInactiveInterval() / 60 + " minutes)</I><BR>");
    out.println("Creation time: " + session.getCreationTime());
    out.println("<I>(" + new Date(session.getCreationTime()) + ")</I><BR>");
    out.println("Last access time: " + session.getLastAccessedTime());
    out.println("<I>(" + new Date(session.getLastAccessedTime()) + ")</I><BR>");

    out.println("Requested session ID from cookie: " + req.isRequestedSessionIdFromCookie() + "<BR>");
    out.println("Requested session ID from URL: " + req.isRequestedSessionIdFromURL() + "<BR>");
    out.println("Requested session ID valid: " + req.isRequestedSessionIdValid() + "<BR>");

    out.println("<H3>Test URL Rewriting</H3>");
    out.println("Click <A HREF=\"" + res.encodeURL(req.getRequestURI()) + "\">here</A>");
    out.println("to test that session tracking works via URL");
    out.println("rewriting even when cookies aren't supported.");

    out.println("</BODY></HTML>");
}

From source file:MyServlet.java

public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    res.setContentType("text/html");
    PrintWriter out = res.getWriter();

    HttpSession session = req.getSession();

    Integer count = (Integer) session.getAttribute("snoop.count");
    if (count == null)
        count = new Integer(1);
    else/*from  w w  w  .java  2s  .  c  o m*/
        count = new Integer(count.intValue() + 1);
    session.setAttribute("snoop.count", count);

    out.println("<HTML><HEAD><TITLE>SessionSnoop</TITLE></HEAD>");
    out.println("<BODY><H1>Session Snoop</H1>");

    out.println("You've visited this page " + count + ((count.intValue() == 1) ? " time." : " times."));

    out.println("<P>");

    out.println("<H3>Here is your saved session data:</H3>");
    Enumeration e = session.getAttributeNames();
    while (e.hasMoreElements()) {
        String name = (String) e.nextElement();
        out.println(name + ": " + session.getAttribute(name) + "<BR>");
    }

    out.println("<H3>Here are some vital stats on your session:</H3>");
    out.println("Session id: " + session.getId() + " <I>(keep it secret)</I><BR>");
    out.println("New session: " + session.isNew() + "<BR>");
    out.println("Timeout: " + session.getMaxInactiveInterval());
    out.println("<I>(" + session.getMaxInactiveInterval() / 60 + " minutes)</I><BR>");
    out.println("Creation time: " + session.getCreationTime());
    out.println("<I>(" + new Date(session.getCreationTime()) + ")</I><BR>");
    out.println("Last access time: " + session.getLastAccessedTime());
    out.println("<I>(" + new Date(session.getLastAccessedTime()) + ")</I><BR>");

    out.println("Requested session ID from cookie: " + req.isRequestedSessionIdFromCookie() + "<BR>");
    out.println("Requested session ID from URL: " + req.isRequestedSessionIdFromURL() + "<BR>");
    out.println("Requested session ID valid: " + req.isRequestedSessionIdValid() + "<BR>");

    out.println("<H3>Test URL Rewriting</H3>");
    out.println("Click <A HREF=\"" + res.encodeURL(req.getRequestURI()) + "\">here</A>");
    out.println("to test that session tracking works via URL");
    out.println("rewriting even when cookies aren't supported.");

    out.println("</BODY></HTML>");
}

From source file:net.lightbody.bmp.proxy.jetty.servlet.SessionDump.java

public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html");
    Page page = new Page();

    HttpSession session = request.getSession(getURI(request).indexOf("new") > 0);

    page.title("Session Dump Servlet: ");

    TableForm tf = new TableForm(response.encodeURL(getURI(request)));
    tf.method("POST");

    if (session == null) {
        page.add("<H1>No Session</H1>");
        tf.addButton("Action", "New Session");
    } else {// www.ja  v a 2 s  .  c o m
        try {
            tf.addText("ID", session.getId());
            tf.addText("State", session.isNew() ? "NEW" : "Valid");
            tf.addText("Creation", new Date(session.getCreationTime()).toString());
            tf.addText("Last Access", new Date(session.getLastAccessedTime()).toString());
            tf.addText("Max Inactive", "" + session.getMaxInactiveInterval());

            tf.addText("Context", "" + session.getServletContext());

            Enumeration keys = session.getAttributeNames();
            while (keys.hasMoreElements()) {
                String name = (String) keys.nextElement();
                String value = session.getAttribute(name).toString();
                tf.addText(name, value);
            }

            tf.addTextField("Name", "Property Name", 20, "name");
            tf.addTextField("Value", "Property Value", 20, "value");
            tf.addTextField("MaxAge", "MaxAge(s)", 5, "");
            tf.addButtonArea();
            tf.addButton("Action", "Set");
            tf.addButton("Action", "Remove");
            tf.addButton("Action", "Invalidate");

            page.add(tf);
            tf = null;
            if (request.isRequestedSessionIdFromCookie())
                page.add("<P>Turn off cookies in your browser to try url encoding<BR>");

            if (request.isRequestedSessionIdFromURL())
                page.add("<P>Turn on cookies in your browser to try cookie encoding<BR>");

        } catch (IllegalStateException e) {
            log.debug(LogSupport.EXCEPTION, e);
            page.add("<H1>INVALID Session</H1>");
            tf = new TableForm(getURI(request));
            tf.addButton("Action", "New Session");
        }
    }

    if (tf != null)
        page.add(tf);

    Writer writer = response.getWriter();
    page.write(writer);
    writer.flush();
}

From source file:it.eng.spago.dispatching.httpchannel.AdapterHTTP.java

/**
 * Sets the http request data.//w  ww  . ja v a 2  s. c  o m
 * 
 * @param request the request
 * @param requestContainer the request container
 */
private void setHttpRequestData(HttpServletRequest request, RequestContainer requestContainer) {
    requestContainer.setAttribute(HTTP_REQUEST_AUTH_TYPE, request.getAuthType());
    requestContainer.setAttribute(HTTP_REQUEST_CHARACTER_ENCODING, request.getCharacterEncoding());
    requestContainer.setAttribute(HTTP_REQUEST_CONTENT_LENGTH, String.valueOf(request.getContentLength()));
    requestContainer.setAttribute(HTTP_REQUEST_CONTENT_TYPE, request.getContentType());
    requestContainer.setAttribute(HTTP_REQUEST_CONTEXT_PATH, request.getContextPath());
    requestContainer.setAttribute(HTTP_REQUEST_METHOD, request.getMethod());
    requestContainer.setAttribute(HTTP_REQUEST_PATH_INFO, request.getPathInfo());
    requestContainer.setAttribute(HTTP_REQUEST_PATH_TRANSLATED, request.getPathTranslated());
    requestContainer.setAttribute(HTTP_REQUEST_PROTOCOL, request.getProtocol());
    requestContainer.setAttribute(HTTP_REQUEST_QUERY_STRING, request.getQueryString());
    requestContainer.setAttribute(HTTP_REQUEST_REMOTE_ADDR, request.getRemoteAddr());
    requestContainer.setAttribute(HTTP_REQUEST_REMOTE_HOST, request.getRemoteHost());
    requestContainer.setAttribute(HTTP_REQUEST_REMOTE_USER, request.getRemoteUser());
    requestContainer.setAttribute(HTTP_REQUEST_REQUESTED_SESSION_ID, request.getRequestedSessionId());
    requestContainer.setAttribute(HTTP_REQUEST_REQUEST_URI, request.getRequestURI());
    requestContainer.setAttribute(HTTP_REQUEST_SCHEME, request.getScheme());
    requestContainer.setAttribute(HTTP_REQUEST_SERVER_NAME, request.getServerName());
    requestContainer.setAttribute(HTTP_REQUEST_SERVER_PORT, String.valueOf(request.getServerPort()));
    requestContainer.setAttribute(HTTP_REQUEST_SERVLET_PATH, request.getServletPath());
    if (request.getUserPrincipal() != null)
        requestContainer.setAttribute(HTTP_REQUEST_USER_PRINCIPAL, request.getUserPrincipal());
    requestContainer.setAttribute(HTTP_REQUEST_REQUESTED_SESSION_ID_FROM_COOKIE,
            String.valueOf(request.isRequestedSessionIdFromCookie()));
    requestContainer.setAttribute(HTTP_REQUEST_REQUESTED_SESSION_ID_FROM_URL,
            String.valueOf(request.isRequestedSessionIdFromURL()));
    requestContainer.setAttribute(HTTP_REQUEST_REQUESTED_SESSION_ID_VALID,
            String.valueOf(request.isRequestedSessionIdValid()));
    requestContainer.setAttribute(HTTP_REQUEST_SECURE, String.valueOf(request.isSecure()));
    Enumeration headerNames = request.getHeaderNames();
    while (headerNames.hasMoreElements()) {
        String headerName = (String) headerNames.nextElement();
        String headerValue = request.getHeader(headerName);
        requestContainer.setAttribute(headerName, headerValue);
    } // while (headerNames.hasMoreElements())
    requestContainer.setAttribute(HTTP_SESSION_ID, request.getSession().getId());
    requestContainer.setAttribute(Constants.HTTP_IS_XML_REQUEST, "FALSE");
}

From source file:eu.eidas.node.service.ColleagueRequestServlet.java

/**
 * Post method/*from w  ww  . jav a  2  s  .  co m*/
 *
 * @param request
 * @param response
 * @throws ServletException
 * @throws IOException
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    PropertiesUtil.checkProxyServiceActive();
    // Obtaining the assertion consumer url from SPRING context
    ServiceControllerService controllerService = (ServiceControllerService) getApplicationContext()
            .getBean(NodeBeanNames.EIDAS_SERVICE_CONTROLLER.toString());

    CorrelationMap<StoredAuthenticationRequest> requestCorrelationMap = controllerService
            .getProxyServiceRequestCorrelationMap();

    // Prevent cookies from being accessed through client-side script WITHOUT renew of session.
    setHTTPOnlyHeaderToSession(false, request, response);
    SessionHolder.setId(request.getSession());
    request.getSession().setAttribute(EidasParameterKeys.SAML_PHASE.toString(),
            EIDASValues.EIDAS_SERVICE_REQUEST);

    // Obtains the parameters from httpRequest
    WebRequest webRequest = new IncomingRequest(request);

    // Validating the only HTTP parameter: SAMLRequest.
    String samlRequest = webRequest.getEncodedLastParameterValue(EidasParameterKeys.SAML_REQUEST);
    NodeParameterValidator.paramName(EidasParameterKeys.SAML_REQUEST).paramValue(samlRequest)
            .eidasError(EidasErrorKey.COLLEAGUE_REQ_INVALID_SAML).validate();

    // Storing the Remote Address and Host for auditing proposes.
    String remoteIpAddress = webRequest.getRemoteIpAddress();

    // Validating the optional HTTP Parameter relayState.
    String relayState = webRequest.getEncodedLastParameterValue(NodeParameterNames.RELAY_STATE.toString());
    LOG.debug("Saving ProxyService relay state. " + relayState);

    // Obtaining the authData
    IAuthenticationRequest authData = controllerService.getProxyService()
            .processAuthenticationRequest(webRequest, relayState, requestCorrelationMap, remoteIpAddress);
    if (StringUtils.isNotBlank(relayState)) { // RelayState's HTTP Parameter is optional!
        NodeParameterValidator.paramName(NodeParameterNames.RELAY_STATE).paramValue(relayState)
                .eidasError(EidasErrorKey.SPROVIDER_SELECTOR_INVALID_RELAY_STATE).validate();
    }
    // Validating the personal attribute list
    IPersonalAttributeList persAttrList = PersonalAttributeList.copyOf(authData.getRequestedAttributes());
    List<PersonalAttribute> attrList = new ArrayList<PersonalAttribute>();

    boolean hasEidasAttributes = !Sets.intersection(EidasSpec.REGISTRY.getAttributes(),
            authData.getRequestedAttributes().getDefinitions()).isEmpty();
    //ImmutablePersonalAttributeSet
    for (PersonalAttribute pa : persAttrList) {
        attrList.add(pa);
    }
    String redirectUrl = authData.getAssertionConsumerServiceURL();
    LOG.debug("RedirectUrl: " + redirectUrl);
    // Validating the citizenConsentUrl
    NodeParameterValidator.paramName(EidasParameterKeys.EIDAS_SERVICE_REDIRECT_URL)
            .paramValue(controllerService.getCitizenConsentUrl())
            .eidasError(EidasErrorKey.COLLEAGUE_REQ_INVALID_DEST_URL).validate();
    LOG.debug("sessionId is on cookies () or fromURL ", request.isRequestedSessionIdFromCookie(),
            request.isRequestedSessionIdFromURL());

    request.setAttribute(NodeParameterNames.SAML_TOKEN_FAIL.toString(),
            controllerService.getProxyService().generateSamlTokenFail(authData,
                    EIDASStatusCode.REQUESTER_URI.toString(), EidasErrorKey.CITIZEN_RESPONSE_MANDATORY,
                    remoteIpAddress));

    request.setAttribute(EidasParameterKeys.SP_ID.toString(), authData.getProviderName());
    if (authData instanceof IStorkAuthenticationRequest) {
        request.setAttribute(NodeParameterNames.QAA_LEVEL.toString(),
                ((IStorkAuthenticationRequest) authData).getQaa());
    }

    request.setAttribute(NodeParameterNames.LOA_VALUE.toString(),
            EidasAttributesUtil.getUserFriendlyLoa(authData.getLevelOfAssurance()));
    request.setAttribute(NodeParameterNames.CITIZEN_CONSENT_URL.toString(),
            encodeURL(controllerService.getCitizenConsentUrl(), response)); // Correct URl redirect cookie implementation
    request.setAttribute(NodeParameterNames.ATTR_LIST.toString(), attrList);
    request.setAttribute(NodeParameterNames.REDIRECT_URL.toString(), encodeURL(redirectUrl, response));// Correct URl redirect cookie implementation
    request.setAttribute(NodeParameterNames.EIDAS_ATTRIBUTES_PARAM.toString(),
            Boolean.valueOf(hasEidasAttributes));

    request.setAttribute(NodeParameterNames.REQUEST_ID.toString(), authData.getId());
    request.setAttribute(NodeParameterNames.COLLEAGUE_REQUEST.toString(), authData);

    NodeViewNames forwardUrl;
    if (controllerService.isAskConsentType()) {
        forwardUrl = NodeViewNames.EIDAS_SERVICE_PRESENT_CONSENT;
    } else {
        forwardUrl = NodeViewNames.EIDAS_SERVICE_NO_CONSENT;
    }
    RequestDispatcher dispatcher = request.getRequestDispatcher(forwardUrl.toString());
    dispatcher.forward(request, response);
}

From source file:com.icesoft.faces.webapp.http.servlet.ServletEnvironmentRequest.java

public ServletEnvironmentRequest(Object request, HttpSession session, Authorization authorization) {
    HttpServletRequest initialRequest = (HttpServletRequest) request;
    this.session = session;
    this.authorization = authorization;
    //Copy common data
    authType = initialRequest.getAuthType();
    contextPath = initialRequest.getContextPath();
    remoteUser = initialRequest.getRemoteUser();
    userPrincipal = initialRequest.getUserPrincipal();
    requestedSessionId = initialRequest.getRequestedSessionId();
    requestedSessionIdValid = initialRequest.isRequestedSessionIdValid();

    attributes = new HashMap();
    Enumeration attributeNames = initialRequest.getAttributeNames();
    while (attributeNames.hasMoreElements()) {
        String name = (String) attributeNames.nextElement();
        Object attribute = initialRequest.getAttribute(name);
        if ((null != name) && (null != attribute)) {
            attributes.put(name, attribute);
        }//from www .ja v  a2s  . c o  m
    }

    // Warning:  For some reason, the various javax.include.* attributes are
    // not available via the getAttributeNames() call.  This may be limited
    // to a Liferay issue but when the MainPortlet dispatches the call to
    // the MainServlet, all of the javax.include.* attributes can be
    // retrieved using this.request.getAttribute() but they do NOT appear in
    // the Enumeration of names returned by getAttributeNames().  So here
    // we manually add them to our map to ensure we can find them later.
    String[] incAttrKeys = Constants.INC_CONSTANTS;
    for (int index = 0; index < incAttrKeys.length; index++) {
        String incAttrKey = incAttrKeys[index];
        Object incAttrVal = initialRequest.getAttribute(incAttrKey);
        if (incAttrVal != null) {
            attributes.put(incAttrKey, initialRequest.getAttribute(incAttrKey));
        }
    }

    headers = new HashMap();
    Enumeration headerNames = initialRequest.getHeaderNames();
    while (headerNames.hasMoreElements()) {
        String name = (String) headerNames.nextElement();
        Enumeration values = initialRequest.getHeaders(name);
        headers.put(name, Collections.list(values));
    }

    parameters = new HashMap();
    Enumeration parameterNames = initialRequest.getParameterNames();
    while (parameterNames.hasMoreElements()) {
        String name = (String) parameterNames.nextElement();
        parameters.put(name, initialRequest.getParameterValues(name));
    }

    scheme = initialRequest.getScheme();
    serverName = initialRequest.getServerName();
    serverPort = initialRequest.getServerPort();
    secure = initialRequest.isSecure();

    //Copy servlet specific data
    cookies = initialRequest.getCookies();
    method = initialRequest.getMethod();
    pathInfo = initialRequest.getPathInfo();
    pathTranslated = initialRequest.getPathTranslated();
    queryString = initialRequest.getQueryString();
    requestURI = initialRequest.getRequestURI();
    try {
        requestURL = initialRequest.getRequestURL();
    } catch (NullPointerException e) {
        //TODO remove this catch block when GlassFish bug is addressed
        if (log.isErrorEnabled()) {
            log.error("Null Protocol Scheme in request", e);
        }
        HttpServletRequest req = initialRequest;
        requestURL = new StringBuffer(
                "http://" + req.getServerName() + ":" + req.getServerPort() + req.getRequestURI());
    }
    servletPath = initialRequest.getServletPath();
    servletSession = initialRequest.getSession();
    isRequestedSessionIdFromCookie = initialRequest.isRequestedSessionIdFromCookie();
    isRequestedSessionIdFromURL = initialRequest.isRequestedSessionIdFromURL();
    characterEncoding = initialRequest.getCharacterEncoding();
    contentLength = initialRequest.getContentLength();
    contentType = initialRequest.getContentType();
    protocol = initialRequest.getProtocol();
    remoteAddr = initialRequest.getRemoteAddr();
    remoteHost = initialRequest.getRemoteHost();
    initializeServlet2point4Properties(initialRequest);
}

From source file:nl.ordina.jtech.http2.java8.server.tomcat.SimpleImagePush.java

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    System.out.println("request path: " + req.getContextPath() + " >> " + req.getServletPath() + " >> "
            + req.getPathTranslated());//from ww w .ja v  a  2  s .  c  om

    if (req.getPathTranslated() != null && req.getPathTranslated().contains("dynamic-image")) {
        handleDynamicImage(req, resp);
    }

    final HttpSession session = req.getSession(true);
    System.out.println(" (possibly new) sessionid: " + session.getId() + ", requested sessionid: "
            + req.getRequestedSessionId() + ", from cookie: " + req.isRequestedSessionIdFromCookie()
            + ", valid: " + req.isRequestedSessionIdValid());

    /*
     * Result:
     * GET https://localhost:8443/http2-java8-example-1.0/return.gif?answer=42
     *  header: x-my-header=[bar]
     *  header: x-my-header-1=[foo]
     *  header: x-my-header-1=[zaphod]
     */
    // Tomcat impl: http://svn.apache.org/viewvc/tomcat/tc9.0.x/branches/gsoc-jaspic/java/org/apache/catalina/core/ApplicationPushBuilder.java?view=markup
    PushBuilder pb = req.getPushBuilder().path("return.gif") // path is the only required value

            // note: the browser does not show these headers - only the ones delivered in the pushed resource itself
            .setHeader("x-my-header", "overwritten by subsequent setHeader").setHeader("x-my-header", "bar")
            .addHeader("x-my-header-1", "foo").addHeader("x-my-header-1", "zaphod") // note: had expected this to be reported as x-my-header-1=[foo,zaphod] ?

            // GET is default
            // ?! "IllegalArgumentException - if the method set expects a request body (eg POST)"; does not happen; Tomcat does not enforce it!
            .method("POST")

            .queryString("answer=42")

            //.sessionId("some-session-id") // dropped?! "pushed request will include the session ID either as a Cookie or as a URI parameter"
            .sessionId(session.getId())

    ;
    final boolean pushResult;
    try {
        //pb.push(); // results in 'java.lang.NoSuchMethodError: javax.servlet.http.PushBuilder.push()V'
        // - Tomcat's Servlet 4.0 API version return type is boolean, not void!
        final Method push = pb.getClass().getMethod("push");
        pushResult = (boolean) push.invoke(pb);
    } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
        if (e.getCause() instanceof UnsupportedOperationException) {
            respondWith(resp,
                    "<p>The following image was NOT provided via a push request! "
                            + "Cannot push over plain HTTP/1.x.</p>" + "<img src=\"" + req.getContextPath()
                            + "/return.gif\"/>");
            return;
        }
        respondWith(resp, e.getClass().getName() + ": " + e.getMessage() + ", cause: " + e.getCause());
        return;
    }

    simplePush(req, "Chrome Pony.png");
    simplePush(req, "second.html");

    respondWith(resp,
            "<p>The following static image was provided via a push request with result " + pushResult + "</p>"
                    + "<img src=\"" + req.getContextPath() + "/return.gif\"/><br/>"
                    + "<p>Dynamic push request: </p><img src=\"push/dynamic-image\"/><br/>"
                    + "<p><a href=\"second.html\">Link naar gepushte pagina</a></p>");
}