Example usage for javax.servlet.http HttpServletRequest getCookies

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

Introduction

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

Prototype

public Cookie[] getCookies();

Source Link

Document

Returns an array containing all of the Cookie objects the client sent with this request.

Usage

From source file:org.apache.atlas.web.filters.AtlasAuthenticationFilter.java

@Override
protected AuthenticationToken getToken(HttpServletRequest request) throws IOException, AuthenticationException {
    AuthenticationToken token = null;//from   w  w w . ja va 2 s .  c o  m
    String tokenStr = null;
    Cookie[] cookies = request.getCookies();
    if (cookies != null) {
        for (Cookie cookie : cookies) {
            if (cookie.getName().equals(AuthenticatedURL.AUTH_COOKIE)) {
                tokenStr = cookie.getValue();
                try {
                    tokenStr = this.signer.verifyAndExtract(tokenStr);
                } catch (SignerException ex) {
                    throw new AuthenticationException(ex);
                }
            }
        }
    }

    if (tokenStr != null) {
        token = AuthenticationToken.parse(tokenStr);
        if (token != null) {
            AuthenticationHandler authHandler = getAuthenticationHandler();
            if (!token.getType().equals(authHandler.getType())) {
                throw new AuthenticationException("Invalid AuthenticationToken type");
            }
            if (token.isExpired()) {
                throw new AuthenticationException("AuthenticationToken expired");
            }
        }
    }
    return token;
}

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

/**
 * Returns the {@link AuthenticationToken} for the request.
 * <p>//from ww  w  .  ja v  a2  s  .  co  m
 * It looks at the received HTTP cookies and extracts the value of the {@link AuthenticatedURL#AUTH_COOKIE}
 * if present. It verifies the signature and if correct it creates the {@link AuthenticationToken} and returns
 * it.
 * <p>
 * If this method returns <code>null</code> the filter will invoke the configured {@link AuthenticationHandler}
 * to perform user authentication.
 *
 * @param request request object.
 *
 * @return the Authentication token if the request is authenticated, <code>null</code> otherwise.
 *
 * @throws IOException thrown if an IO error occurred.
 * @throws AuthenticationException thrown if the token is invalid or if it has expired.
 */
protected AuthenticationToken getToken(HttpServletRequest request) throws IOException, AuthenticationException {
    AuthenticationToken token = null;
    String tokenStr = null;
    Cookie[] cookies = request.getCookies();
    if (cookies != null) {
        for (Cookie cookie : cookies) {
            if (AuthenticatedURL.AUTH_COOKIE.equals(cookie.getName())) {
                tokenStr = cookie.getValue();
                try {
                    tokenStr = signer.verifyAndExtract(tokenStr);
                } catch (SignerException ex) {
                    throw new AuthenticationException(ex);
                }
                break;
            }
        }
    }
    if (tokenStr != null) {
        token = AuthenticationToken.parse(tokenStr);
        if (token != null) {
            if (!token.getType().equals(authHandler.getType())) {
                throw new AuthenticationException("Invalid AuthenticationToken type");
            }
            if (token.isExpired()) {
                throw new AuthenticationException("AuthenticationToken expired");
            }
        }
    }
    return token;
}

From source file:org.apache.hadoop.yarn.server.webproxy.amfilter.AmIpFilter.java

@Override
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain)
        throws IOException, ServletException {
    if (!(req instanceof HttpServletRequest)) {
        throw new ServletException("This filter only works for HTTP/HTTPS");
    }/*  ww  w . java 2  s. co m*/

    HttpServletRequest httpReq = (HttpServletRequest) req;
    HttpServletResponse httpResp = (HttpServletResponse) resp;
    if (LOG.isDebugEnabled()) {
        LOG.debug("Remote address for request is: " + httpReq.getRemoteAddr());
    }
    if (!getProxyAddresses().contains(httpReq.getRemoteAddr())) {
        String redirectUrl = findRedirectUrl();
        redirectUrl = httpResp.encodeRedirectURL(redirectUrl + httpReq.getRequestURI());
        httpResp.sendRedirect(redirectUrl);
        return;
    }

    String user = null;

    if (httpReq.getCookies() != null) {
        for (Cookie c : httpReq.getCookies()) {
            if (WebAppProxyServlet.PROXY_USER_COOKIE_NAME.equals(c.getName())) {
                user = c.getValue();
                break;
            }
        }
    }
    if (user == null) {
        LOG.warn("Could not find " + WebAppProxyServlet.PROXY_USER_COOKIE_NAME
                + " cookie, so user will not be set");
        chain.doFilter(req, resp);
    } else {
        final AmIpPrincipal principal = new AmIpPrincipal(user);
        ServletRequest requestWrapper = new AmIpServletRequestWrapper(httpReq, principal);
        chain.doFilter(requestWrapper, resp);
    }
}

From source file:com.spshop.web.ShoppingController.java

@RequestMapping(value = "/logout")
public String logout(Model model, HttpServletRequest request, HttpServletResponse response) {
    request.getSession().invalidate();/*from   ww  w.j  av  a  2 s.  co m*/
    model.addAttribute(LOGOUT_ACTION, Boolean.TRUE.toString());
    Cookie[] cookies = request.getCookies();
    if (null != cookies) {
        for (Cookie cookie : cookies) {
            if (COOKIE_ACCOUNT.equals(cookie.getName())) {
                cookie = new Cookie(COOKIE_ACCOUNT, EMPTY_STR);
                cookie.setPath("/");
                cookie.setMaxAge(30 * 24 * 60 * 60);
                response.addCookie(cookie);
            }
        }
    }
    return "redirect:" + getSiteView().getHost();
}

From source file:org.gatein.sso.agent.opensso.OpenSSOAgentImpl.java

public void validateTicket(HttpServletRequest httpRequest, HttpServletResponse httpResponse) throws Exception {
    // Start with processing message from CDCServlet if this message is available (it should be in servlet request parameter "LARES")
    if (tryMessageFromCDC(httpRequest, httpResponse)) {
        return;/*from   w w w  .  j  av a  2  s . co m*/
    }

    // Now cookie should be set and we can continue with cookie processing
    String token = null;
    Cookie[] cookies = httpRequest.getCookies();
    if (cookies == null) {
        return;
    }

    for (Cookie cookie : cookies) {
        if (cookie.getName().equals(this.cookieName)) {
            token = cookie.getValue();
            break;
        }
    }

    if (token == null) {
        throwIllegalStateException("No SSO Tokens Found");
    }

    if (token != null) {
        boolean isValid = this.isTokenValid(token);

        if (!isValid) {
            throwIllegalStateException("OpenSSO Token is not valid!!");
        }

        String subject = this.getSubject(token);
        if (subject != null) {
            this.saveSSOCredentials(subject, httpRequest);
        }
    }
}

From source file:fr.mby.portal.coreimpl.session.MemorySessionManager.java

@Override
public String getPortalSessionId(final HttpServletRequest request) {
    String portalSessionId = null;

    // Put sessionId in current Http request
    final Object attrValue = request.getAttribute(IPortal.PORTAL_SESSION_ID_PARAM_NAME);
    if (attrValue != null && attrValue instanceof String) {
        portalSessionId = (String) attrValue;
    }/*from  w  w  w.  jav  a 2s .  co m*/

    if (!StringUtils.hasText(portalSessionId)) {
        final Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (final Cookie cookie : cookies) {
                if (cookie != null && IPortal.PORTAL_SESSION_ID_COOKIE_NAME.equals(cookie.getName())) {
                    portalSessionId = cookie.getValue();
                }
            }
        }
    }

    if (!StringUtils.hasText(portalSessionId)) {
        // Search Portal Session Id in Http Session
        portalSessionId = (String) request.getSession(true).getAttribute(IPortal.PORTAL_SESSION_ID_PARAM_NAME);
    }

    if (!StringUtils.hasText(portalSessionId)) {
        // Search Portal Session Id in Http Request params
        portalSessionId = request.getParameter(IPortal.PORTAL_SESSION_ID_PARAM_NAME);
    }

    // Null is the default value
    if (!StringUtils.hasText(portalSessionId) || !this.sessionBucketCache.containsKey(portalSessionId)) {
        // If the session Id cannot be found in the cache we cannot trust the session Id found.
        portalSessionId = null;
    }

    return portalSessionId;
}

From source file:net.geant.edugain.filter.EduGAINFilter.java

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {

    HttpServletRequest httpRequest = (HttpServletRequest) request;
    HttpServletResponse httpResponse = (HttpServletResponse) response;

    Cookie[] cookies = httpRequest.getCookies();
    //Check where the query is coming from

    //If returnIDParam has a value, then the request comes from the WFAYF
    if (httpRequest.getParameter("returnIDParam") != null)
        fromWFAYF(httpRequest, httpResponse);

    //If SAMLResponse has a value, then the request comes from the HomeBE
    else if (httpRequest.getParameter("SAMLResponse") != null)
        fromHome(httpRequest, httpResponse);

    //If cookies are available, and cookie name is lcook, check for SSO functionality 
    else if ((cookies != null) && (getCookie(httpRequest, httpResponse, "lcook")) != null)
        fromSSO(httpRequest, httpResponse, chain);

    /*      //If cookies are available, and cookie name is statecook, it's a self-redirect
          else if ((cookies != null) && (cookies[0].getName().equals("statecook")))
             fromFilter(httpRequest, httpResponse, chain);
    *///from w  w  w . j  av  a 2s.c o  m
    //Otherwise, this is the first access to the app
    else
        fromStart(httpRequest, httpResponse);

}

From source file:com.pureinfo.tgirls.sns.servlet.TestSNSEntryServlet.java

@Override
protected void doPost(HttpServletRequest _req, HttpServletResponse _resp) throws ServletException, IOException {
    System.out.println("==================test entry=====POST==============");

    try {/*  www  .  j a  v  a2s  .c  om*/
        String userId = _req.getParameter("id");
        if (StringUtils.isEmpty(userId)) {
            userId = "1";
        }

        System.out.println("----user id----" + userId);

        IUserMgr mgr = (IUserMgr) ArkContentHelper.getContentMgrOf(User.class);
        User u = mgr.getUserByTaobaoId(userId);

        System.out.println("user:::;" + u);

        addCookie(u, _req, _resp);

        Cookie[] cookies = _req.getCookies();

        if (cookies == null) {
            System.out.println("=====cookie is null=======");
        } else {
            for (int i = 0; i < cookies.length; i++) {
                Cookie cookie = cookies[i];
                System.out.println("cookie[" + i + "]:[" + cookie.getName() + ":" + cookie.getValue() + "("
                        + cookie.getMaxAge() + ")]");
            }

        }

        int i = new Random().nextInt();
        Cookie c = new Cookie("topsessionid", "abc" + i);

        _resp.addCookie(c);

        System.out.println("========================");

        //            Cookie[] cs = _req.getCookies();
        //             for (int ii = 0; ii < cs.length; ii++) {
        //                 Cookie cc = cs[ii];
        //                 System.out.println("cookie[" + cc.getName() + "]:" + cc.getValue());
        //             }

        //_resp.sendRedirect(_req.getContextPath() + "/index.html");

        RequestDispatcher rd = _req.getRequestDispatcher("/index.html");
        rd.forward(_req, _resp);

        //_req.getSession().setAttribute(ArkHelper.ATTR_LOGIN_USER, u);
        // _resp.sendRedirect(_req.getContextPath());
        //            _req.getCookies()[0].
    } catch (PureException e) {
        // TODO Auto-generated catch block
        e.printStackTrace(System.err);
    }

}

From source file:custom.application.login.java

public void logout() {
    HttpServletRequest request = (HttpServletRequest) this.context.getAttribute("HTTP_REQUEST");
    HttpServletResponse response = (HttpServletResponse) this.context.getAttribute("HTTP_RESPONSE");

    try {// w ww  . ja  v  a 2 s  .  c  o  m
        this.passport = new passport(request, response, "waslogined");
        this.passport.logout();

        if (request.getCookies() != null) {
            Cookie[] cookies = request.getCookies();
            int i = 0;
            Cookie cookie;
            while (cookies.length > i) {
                cookie = cookies[i];
                cookie.setMaxAge(0);
                cookie.setValue("");
                response.addCookie(cookie);
                i++;
            }
        }

        Reforward reforward = new Reforward(request, response);

        reforward.setDefault(this.getLink(this.context.getAttribute("default.login.page").toString()));
        reforward.forward();
    } catch (ApplicationException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}