Example usage for javax.servlet.http HttpServletRequest isRequestedSessionIdValid

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

Introduction

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

Prototype

public boolean isRequestedSessionIdValid();

Source Link

Document

Checks whether the requested session ID is still valid.

Usage

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//w  w w .  j  a  v  a 2 s.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:de.betterform.agent.web.WebUtil.java

/**
 * this method is responsible for passing all context information needed by the Adapter and Processor from
 * ServletRequest to Context. Will be called only once when the form-session is inited (GET).
 * <p/>/*w  ww .j  a  v  a 2  s .c  o m*/
 * <p/>
 * todo: better logging of context params
 *
 * @param request     the Servlet request to fetch params from
 * @param httpSession the Http Session context
 * @param processor   the XFormsProcessor which receives the context params
 * @param sessionkey  the key to identify the XFormsSession
 */
public static void setContextParams(HttpServletRequest request, HttpSession httpSession,
        XFormsProcessor processor, String sessionkey) throws XFormsConfigException {
    Map servletMap = new HashMap();
    servletMap.put(WebProcessor.SESSION_ID, sessionkey);
    processor.setContextParam(XFormsProcessor.SUBMISSION_RESPONSE, servletMap);

    //adding requestURI to context
    processor.setContextParam(WebProcessor.REQUEST_URI, WebUtil.getRequestURI(request));

    //adding request URL to context
    String requestURL = request.getRequestURL().toString();
    processor.setContextParam(WebProcessor.REQUEST_URL, requestURL);

    // the web app name with an '/' prepended e.g. '/betterform' by default
    String contextRoot = WebUtil.getContextRoot(request);
    processor.setContextParam(WebProcessor.CONTEXTROOT, contextRoot);
    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("context root of webapp: " + processor.getContextParam(WebProcessor.CONTEXTROOT));
    }

    String requestPath = "";
    URL url = null;
    String plainPath = "";
    try {
        url = new URL(requestURL);
        requestPath = url.getPath();
    } catch (MalformedURLException e) {
        e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
    }
    if (requestPath.length() != 0) {
        //adding request path e.g. '/betterform/forms/demo/registration.xhtml'
        processor.setContextParam(WebProcessor.REQUEST_PATH, requestPath);

        //adding filename of requested doc to context
        String fileName = requestPath.substring(requestPath.lastIndexOf('/') + 1, requestPath.length());//FILENAME xforms
        processor.setContextParam(FILENAME, fileName);

        if (requestURL.contains(contextRoot)) { //case1: contextRoot is a part of the URL
            //adding plainPath which is the part between contextroot and filename e.g. '/forms' for a requestPath of '/betterform/forms/Status.xhtml'
            plainPath = requestPath.substring(contextRoot.length() + 1,
                    requestPath.length() - fileName.length());
            processor.setContextParam(PLAIN_PATH, plainPath);
        } else {//case2: contextRoot is not a part of the URL take the part previous the filename.
            String[] urlParts = requestURL.split("/");
            plainPath = urlParts[urlParts.length - 2];
        }

        //adding contextPath - requestPath without the filename
        processor.setContextParam(CONTEXT_PATH, contextRoot + "/" + plainPath);
    }

    //adding session id to context
    processor.setContextParam(HTTP_SESSION_ID, httpSession.getId());
    //adding context absolute path to context

    //EXIST-WORKAROUND: TODO triple check ...
    //TODO: triple check where this is used.
    if (request.isRequestedSessionIdValid()) {
        processor.setContextParam(EXISTDB_USER, httpSession.getAttribute(EXISTDB_USER));
    }

    //adding pathInfo to context - attention: this is only available when a servlet is requested
    String s1 = request.getPathInfo();
    if (s1 != null) {
        processor.setContextParam(WebProcessor.PATH_INFO, s1);
    }
    processor.setContextParam(WebProcessor.QUERY_STRING,
            (request.getQueryString() != null ? request.getQueryString() : ""));

    //storing the realpath for webapp

    String realPath = WebFactory.getRealPath(".", httpSession.getServletContext());
    File f = new File(realPath);
    URI fileURI = f.toURI();

    processor.setContextParam(WebProcessor.REALPATH, fileURI.toString());
    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("real path of webapp: " + realPath);
    }

    //storing the TransformerService
    processor.setContextParam(TransformerService.TRANSFORMER_SERVICE,
            httpSession.getServletContext().getAttribute(TransformerService.TRANSFORMER_SERVICE));
    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("TransformerService: "
                + httpSession.getServletContext().getAttribute(TransformerService.TRANSFORMER_SERVICE));
    }

    //[2] read any request params that are *not* betterForm params and pass them into the context map
    Enumeration params = request.getParameterNames();
    String s;
    while (params.hasMoreElements()) {
        s = (String) params.nextElement();
        //store all request-params we don't use in the context map of XFormsProcessorImpl
        String value = request.getParameter(s);
        processor.setContextParam(s, value);
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("added request param '" + s + "' added to context");
            LOGGER.debug("param value'" + value);
        }
    }

}

From source file:com.citrix.cpbm.portal.fragment.controllers.AbstractAuthenticationController.java

@RequestMapping(value = { "/{userParam}/loggedout", "{userParam}/j_spring_security_logout" })
public String loggedout(@PathVariable String userParam, ModelMap map, HttpSession session,
        HttpServletResponse response, HttpServletRequest request) {
    logger.debug("###Entering in loggedout(response) method");
    String showSuffixControl = "false";
    String suffixControlType = "textbox";
    List<String> suffixList = null;
    if (config.getValue(Names.com_citrix_cpbm_username_duplicate_allowed).equals("true")) {
        showSuffixControl = "true";
        if (config.getValue(Names.com_citrix_cpbm_login_screen_tenant_suffix_dropdown_enabled).equals("true")) {
            suffixControlType = "dropdown";
            suffixList = tenantService.getSuffixList();
        }/*from   w ww  . j a  v a  2s.  c o m*/
    }
    map.addAttribute("showSuffixControl", showSuffixControl);
    map.addAttribute("suffixControlType", suffixControlType);
    map.addAttribute("suffixList", suffixList);
    if (config.getBooleanValue(Configuration.Names.com_citrix_cpbm_portal_directory_service_enabled)
            && config.getValue(Names.com_citrix_cpbm_directory_mode).equals("pull")) {
        map.addAttribute("directoryServiceAuthenticationEnabled", "true");
    }
    if (config.getValue(Names.com_citrix_cpbm_public_catalog_display).equals("true")
            && channelService.getDefaultServiceProviderChannel() != null) {
        map.addAttribute("showAnonymousCatalogBrowsing", "true");
    }
    map.addAttribute("showLanguageSelection", "true");
    map.addAttribute("supportedLocaleList", this.getLocaleDisplayName(listSupportedLocales()));
    map.addAttribute("logout", true);
    String redirect = null;
    Enumeration<String> en = session.getAttributeNames();
    while (en.hasMoreElements()) {
        String attr = en.nextElement();
        session.removeAttribute(attr);
    }
    Cookie cookie = new Cookie("JforumSSO", "");
    cookie.setMaxAge(0);
    cookie.setPath("/");
    response.addCookie(cookie);
    if (request.getRequestedSessionId() != null && request.isRequestedSessionIdValid()) {
        // create logout notification begins
        User user = userService.get(userParam);
        String message = "logged.out";
        String messageArgs = user.getUsername();
        eventService.createEvent(new Date(), user, message, messageArgs, Source.PORTAL, Scope.USER,
                Category.ACCOUNT, Severity.INFORMATION, true);
    }
    session.invalidate();
    if (config.getAuthenticationService().compareToIgnoreCase(CAS) == 0) {
        try {
            redirect = StringUtils.isEmpty(config.getCasLogoutUrl()) ? null
                    : config.getCasLogoutUrl() + "?service="
                            + URLEncoder.encode(config.getCasServiceUrl(), "UTF-8");
        } catch (UnsupportedEncodingException e) {
            logger.error("Exception encoding: " + redirect, e);
        }
        if (redirect == null) {
            throw new InternalError("CAS authentication required, but login url not set");
        }
    }

    SecurityContextHolder.getContext().setAuthentication(null);
    // ends
    logger.debug("###Exiting loggedout(response) method");
    return redirect == null ? "redirect:/j_spring_security_logout" : "redirect:" + redirect;
}

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

/**
 * Sets the http request data./*ww w  .  j  av a  2s .  co  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: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());//  www  . j a va  2s. c  o  m

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

From source file:org.apache.catalina.valves.ExtendedAccessLogValve.java

/**
 * Get app specific data./*  ww  w  .  ja v a 2s.  c  om*/
 * @param fieldInfo The field to decode
 * @param request Where we will pull the data from.
 * @return The appropriate value
 */
private String getAppSpecific(FieldInfo fieldInfo, Request request) {

    ServletRequest sr = request.getRequest();
    HttpServletRequest hsr = null;
    if (sr instanceof HttpServletRequest)
        hsr = (HttpServletRequest) sr;

    switch (fieldInfo.xType) {
    case FieldInfo.X_PARAMETER:
        return wrap(urlEncode(sr.getParameter(fieldInfo.value)));
    case FieldInfo.X_REQUEST:
        return wrap(sr.getAttribute(fieldInfo.value));
    case FieldInfo.X_SESSION:
        HttpSession session = null;
        if (hsr != null) {
            session = hsr.getSession(false);
            if (session != null)
                return wrap(session.getAttribute(fieldInfo.value));
        }
        break;
    case FieldInfo.X_COOKIE:
        Cookie[] c = hsr.getCookies();
        for (int i = 0; c != null && i < c.length; i++) {
            if (fieldInfo.value.equals(c[i].getName())) {
                return wrap(c[i].getValue());
            }
        }
    case FieldInfo.X_APP:
        return wrap(request.getContext().getServletContext().getAttribute(fieldInfo.value));
    case FieldInfo.X_SERVLET_REQUEST:
        if (fieldInfo.location == FieldInfo.X_LOC_AUTHTYPE) {
            return wrap(hsr.getAuthType());
        } else if (fieldInfo.location == FieldInfo.X_LOC_REMOTEUSER) {
            return wrap(hsr.getRemoteUser());
        } else if (fieldInfo.location == FieldInfo.X_LOC_REQUESTEDSESSIONID) {
            return wrap(hsr.getRequestedSessionId());
        } else if (fieldInfo.location == FieldInfo.X_LOC_REQUESTEDSESSIONIDFROMCOOKIE) {
            return wrap("" + hsr.isRequestedSessionIdFromCookie());
        } else if (fieldInfo.location == FieldInfo.X_LOC_REQUESTEDSESSIONIDVALID) {
            return wrap("" + hsr.isRequestedSessionIdValid());
        } else if (fieldInfo.location == FieldInfo.X_LOC_CONTENTLENGTH) {
            return wrap("" + hsr.getContentLength());
        } else if (fieldInfo.location == FieldInfo.X_LOC_CHARACTERENCODING) {
            return wrap(hsr.getCharacterEncoding());
        } else if (fieldInfo.location == FieldInfo.X_LOC_LOCALE) {
            return wrap(hsr.getLocale());
        } else if (fieldInfo.location == FieldInfo.X_LOC_PROTOCOL) {
            return wrap(hsr.getProtocol());
        } else if (fieldInfo.location == FieldInfo.X_LOC_SCHEME) {
            return wrap(hsr.getScheme());
        } else if (fieldInfo.location == FieldInfo.X_LOC_SECURE) {
            return wrap("" + hsr.isSecure());
        }
        break;
    default:
        ;
    }

    return "-";

}

From source file:org.apache.ranger.security.web.filter.RangerSSOAuthenticationFilter.java

@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
        throws IOException, ServletException {

    HttpServletRequest httpRequest = (HttpServletRequest) servletRequest;

    String xForwardedURL = constructForwardableURL(httpRequest);

    if (httpRequest.getRequestedSessionId() != null && !httpRequest.isRequestedSessionIdValid()) {
        synchronized (httpRequest.getServletContext()) {
            if (httpRequest.getServletContext().getAttribute(httpRequest.getRequestedSessionId()) != null
                    && "locallogin".equals(httpRequest.getServletContext()
                            .getAttribute(httpRequest.getRequestedSessionId()).toString())) {
                httpRequest.getSession().setAttribute("locallogin", "true");
                httpRequest.getServletContext().removeAttribute(httpRequest.getRequestedSessionId());
            }//from  ww w.ja  va2 s . c o  m
        }
    }

    RangerSecurityContext context = RangerContextHolder.getSecurityContext();
    UserSessionBase session = context != null ? context.getUserSession() : null;
    boolean ssoEnabled = session != null ? session.isSSOEnabled()
            : PropertiesUtil.getBooleanProperty("ranger.sso.enabled", false);

    String userAgent = httpRequest.getHeader("User-Agent");
    if (httpRequest.getSession() != null) {
        if (httpRequest.getSession().getAttribute("locallogin") != null) {
            servletRequest.setAttribute("ssoEnabled", false);
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }
    }
    //If sso is enable and request is not for local login and is from browser then it will go inside and try for knox sso authentication
    if (ssoEnabled && !httpRequest.getRequestURI().contains(LOCAL_LOGIN_URL)) {
        //if jwt properties are loaded and is current not authenticated then it will go for sso authentication
        //Note : Need to remove !isAuthenticated() after knoxsso solve the bug from cross-origin script
        if (jwtProperties != null && !isAuthenticated()) {
            HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse;
            String serializedJWT = getJWTFromCookie(httpRequest);
            // if we get the hadoop-jwt token from the cookies then will process it further
            if (serializedJWT != null) {
                SignedJWT jwtToken = null;
                try {
                    jwtToken = SignedJWT.parse(serializedJWT);
                    boolean valid = validateToken(jwtToken);
                    //if the public key provide is correct and also token is not expired the process token
                    if (valid) {
                        String userName = jwtToken.getJWTClaimsSet().getSubject();
                        LOG.info("SSO login user : " + userName);

                        String rangerLdapDefaultRole = PropertiesUtil.getProperty("ranger.ldap.default.role",
                                "ROLE_USER");
                        //if we get the userName from the token then log into ranger using the same user
                        if (userName != null && !userName.trim().isEmpty()) {
                            final List<GrantedAuthority> grantedAuths = new ArrayList<>();
                            grantedAuths.add(new SimpleGrantedAuthority(rangerLdapDefaultRole));
                            final UserDetails principal = new User(userName, "", grantedAuths);
                            final Authentication finalAuthentication = new UsernamePasswordAuthenticationToken(
                                    principal, "", grantedAuths);
                            WebAuthenticationDetails webDetails = new WebAuthenticationDetails(httpRequest);
                            ((AbstractAuthenticationToken) finalAuthentication).setDetails(webDetails);
                            RangerAuthenticationProvider authenticationProvider = new RangerAuthenticationProvider();
                            authenticationProvider.setSsoEnabled(ssoEnabled);
                            Authentication authentication = authenticationProvider
                                    .authenticate(finalAuthentication);
                            authentication = getGrantedAuthority(authentication);
                            SecurityContextHolder.getContext().setAuthentication(authentication);
                        }

                        filterChain.doFilter(servletRequest, httpServletResponse);
                    }
                    // if the token is not valid then redirect to knox sso
                    else {
                        if (isWebUserAgent(userAgent)) {
                            String ssourl = constructLoginURL(httpRequest, xForwardedURL);
                            if (LOG.isDebugEnabled()) {
                                LOG.debug("SSO URL = " + ssourl);
                            }
                            httpServletResponse.sendRedirect(ssourl);
                        } else {
                            filterChain.doFilter(servletRequest, httpServletResponse);
                        }
                    }
                } catch (ParseException e) {
                    LOG.warn("Unable to parse the JWT token", e);
                }
            }
            // if the jwt token is not available then redirect it to knox sso
            else {
                if (isWebUserAgent(userAgent)) {
                    String ssourl = constructLoginURL(httpRequest, xForwardedURL);
                    if (LOG.isDebugEnabled()) {
                        LOG.debug("SSO URL = " + ssourl);
                    }
                    httpServletResponse.sendRedirect(ssourl);
                } else {
                    filterChain.doFilter(servletRequest, httpServletResponse);
                }
            }
        }
        //if property is not loaded or is already authenticated then proceed further with next filter
        else {
            filterChain.doFilter(servletRequest, servletResponse);
        }
    } else if (ssoEnabled && ((HttpServletRequest) servletRequest).getRequestURI().contains(LOCAL_LOGIN_URL)
            && isWebUserAgent(userAgent) && isAuthenticated()) {
        //If already there's an active session with sso and user want's to switch to local login(i.e without sso) then it won't be navigated to local login
        // In this scenario the user as to use separate browser
        String url = ((HttpServletRequest) servletRequest).getRequestURI().replace(LOCAL_LOGIN_URL + "/", "");
        url = url.replace(LOCAL_LOGIN_URL, "");
        LOG.warn(
                "There is an active session and if you want local login to ranger, try this on a separate browser");
        ((HttpServletResponse) servletResponse).sendRedirect(url);
    }
    //if sso is not enable or the request is not from browser then proceed further with next filter
    else {
        filterChain.doFilter(servletRequest, servletResponse);
    }
}

From source file:org.apereo.portal.spring.security.preauth.PortalPreAuthenticatedProcessingFilter.java

private void doPortalAuthentication(final HttpServletRequest request,
        final org.springframework.security.core.Authentication originalAuthentication) {

    IdentitySwapHelper identitySwapHelper = null;
    final String requestedSessionId = request.getRequestedSessionId();
    if (request.isRequestedSessionIdValid()) {
        if (logger.isDebugEnabled()) {
            logger.debug("doPortalAuthentication for valid requested session id " + requestedSessionId);
        }//  ww  w  .  j av a  2s.  c om
        identitySwapHelper = getIdentitySwapDataAndInvalidateSession(request, originalAuthentication);
    } else {
        if (logger.isTraceEnabled()) {
            logger.trace("Requested session id " + requestedSessionId + " was not valid "
                    + "so no attempt to apply swapping rules.");
        }
    }

    HttpSession s = request.getSession(true);
    IPerson person = null;
    try {
        final HashMap<String, String> principals;
        final HashMap<String, String> credentials;
        person = personManager.getPerson(request);

        if (identitySwapHelper != null && identitySwapHelper.isSwapOrUnswapRequest()) {
            this.handleIdentitySwap(person, s, identitySwapHelper);
            principals = new HashMap<String, String>();
            credentials = new HashMap<String, String>();
        }
        //Norm authN path
        else {
            // WE grab all of the principals and credentials from the request and load
            // them into their respective HashMaps.
            principals = getPropertyFromRequest(principalTokens, request);
            credentials = getPropertyFromRequest(credentialTokens, request);
        }

        // Attempt to authenticate using the incoming request
        authenticationService.authenticate(request, principals, credentials, person);
    } catch (Exception e) {
        // Log the exception
        logger.error("Exception authenticating the request", e);
        // Reset everything
        request.getSession(false).invalidate();
        // Add the authentication failure
        request.getSession(true).setAttribute(LoginController.AUTH_ERROR_KEY, Boolean.TRUE);
    }

    this.publishProfileSelectionEvent(person, request, identitySwapHelper);
}

From source file:org.codelabor.system.security.web.filter.SessionValidationFilter.java

@Override
public void preprocessFilterChain(ServletRequest request, ServletResponse response)
        throws IOException, ServletException {

    HttpServletRequest httpServletRequest = (HttpServletRequest) request;
    String requestURI = httpServletRequest.getRequestURI();
    String requestedSessionId = httpServletRequest.getRequestedSessionId();
    boolean isRequestedSessionIdValid = httpServletRequest.isRequestedSessionIdValid();

    logger.debug("requestURI: {}", requestURI);
    logger.debug("requestedSessionId: {}", requestedSessionId);
    logger.debug("isRequestedSessionIdValid: {}", isRequestedSessionIdValid);

    if (StringUtils.isNotBlank(requestedSessionId) && isRequestedSessionIdValid && isSessionValid(request)) {
        logger.debug("session id is valid: {}", requestedSessionId);
    } else {/*w  ww . ja v  a  2s . c  om*/
        logger.error("session id is invalid: {}", requestedSessionId);
        logger.error("forward to expiredURL: {}", expiredURL);
        RequestDispatcher dispatcher = request.getRequestDispatcher(expiredURL);
        HttpSession httpSession = httpServletRequest.getSession();
        httpSession.setAttribute(RequestConstants.REQUEST_URI, requestURI);
        httpSession.setAttribute(RequestConstants.REQUEST_ATTRIBUTE_MAP,
                RequestUtils.getAttributeMap(httpServletRequest));
        httpSession.setAttribute(RequestConstants.REQUEST_PARAMETER_MAP,
                RequestUtils.getParameterMap(httpServletRequest));
        logger.debug("current session id: {}", httpSession.getId());
        dispatcher.forward(request, response);
    }
}