Example usage for javax.servlet.http HttpServletResponse addCookie

List of usage examples for javax.servlet.http HttpServletResponse addCookie

Introduction

In this page you can find the example usage for javax.servlet.http HttpServletResponse addCookie.

Prototype

public void addCookie(Cookie cookie);

Source Link

Document

Adds the specified cookie to the response.

Usage

From source file:com.ms.commons.summer.security.web.DefaultSecurityFormResolver.java

/**
 * ?token????InvalidTokenException//w  ww. ja  va2s  . c om
 * 
 * @param request
 * @param response
 * @throws InvalidTokenException
 */
public void validSessionToken(final HttpServletRequest request, final HttpServletResponse response)
        throws InvalidTokenException {
    Cookie[] cookies = request.getCookies();
    String ctoken = null;
    if (cookies != null) {
        for (Cookie cookie : cookies) {
            if (FORM_RESUBMIT_TOKEN.equals(cookie.getName())) {
                ctoken = cookie.getValue();
                break;
            }
        }
    }
    String rtoken = request.getParameter(FORM_RESUBMIT_TOKEN);
    if (rtoken == null || rtoken.length() == 0) {
        throw new InvalidTokenException("can't find token in request");
    }
    if (ctoken == null || ctoken.length() == 0) {
        throw new InvalidTokenException("can't find token in cookie");
    }
    if (!ctoken.equals(rtoken)) {
        throw new InvalidTokenException("failed to check for token in request");
    }
    // cookietoken?
    Cookie c = new Cookie(FORM_RESUBMIT_TOKEN, "");
    c.setPath("/");
    response.addCookie(c);
}

From source file:org.apache.archiva.redback.integration.util.AutoLoginCookies.java

public void setSignonCookie(String principal, HttpServletResponse httpServletResponse,
        HttpServletRequest httpServletRequest) {
    try {/*from  www.j  a v a2  s.  c o  m*/
        CookieSettings settings = securitySystem.getPolicy().getSignonCookieSettings();
        int timeout = settings.getCookieTimeout();
        KeyManager keyManager = securitySystem.getKeyManager();
        AuthenticationKey authkey = keyManager.createKey(principal, "Signon Session Key", timeout);

        /* The path must remain as "/" in order for SSO to work on installations where the only
         * all of the servers are installed into the same web container but under different 
         * web contexts.
         */
        Cookie cookie = createCookie(SIGNON_KEY, authkey.getKey(), settings.getDomain(), settings.getPath(),
                httpServletRequest);
        if (timeout > 0) {
            cookie.setMaxAge(timeout);
        }
        httpServletResponse.addCookie(cookie);

    } catch (KeyManagerException e) {
        log.warn("Unable to set single sign on cookie.");

    }
}

From source file:com.tremolosecurity.proxy.SessionManagerImpl.java

@Override
public void clearSession(UrlHolder holder, HttpSession sharedSession, HttpServletRequest request,
        HttpServletResponse response) {
    Cookie sessionCookie;//  ww  w  .j  a  va2s . com
    sessionCookie = new Cookie(holder.getApp().getCookieConfig().getSessionCookieName(), "LOGGED_OUT");
    String domain = ProxyTools.getInstance().getCookieDomain(holder.getApp().getCookieConfig(), request);
    if (domain != null) {
        sessionCookie.setDomain(domain);
    }
    sessionCookie.setPath("/");
    sessionCookie.setSecure(false);
    sessionCookie.setMaxAge(0);
    response.addCookie(sessionCookie);
    sharedSession.invalidate();

}

From source file:com.google.ie.web.controller.UserController.java

/**
 * Delete all the cookies related to the user from the system
 * /*ww  w.  j a v  a 2  s . c  o m*/
 * @param request {@link HttpServletRequest} object
 * @param response {@link HttpServletResponse} object
 */
private void removeCookieFromSystem(HttpServletRequest request, HttpServletResponse response) {
    Cookie[] cookies = request.getCookies();
    if (cookies != null) {
        for (int i = 0; i < cookies.length; i++) {
            Cookie cookie = cookies[i];
            // Don't remove access token cookie
            if (!StringUtils.equals(cookie.getName(), AuthenticationFilter.ACCESS_TOKEN)) {
                /* Set the max age to zero so that the cookie is deleted */
                cookie.setMaxAge(WebConstants.ZERO);
                cookie.setPath("/");
                response.addCookie(cookie);
            }
        }
    }
    if (isDebugEnabled) {
        LOGGER.debug("The age of the cookies related to the "
                + "user has been set to zero and the cookies set into the response");
    }

}

From source file:com.egt.core.jsf.JSF.java

private static String putCookie(String key, String value, boolean qualified, int expiry) {
    Bitacora.trace(JSF.class, "putCookie", "key=" + key, "value=" + value, "qualified=" + qualified,
            "expiry=" + expiry);
    FacesContext facesContext = FacesContext.getCurrentInstance();
    HttpServletResponse response = (HttpServletResponse) facesContext.getExternalContext().getResponse();
    String qualifiedKey = key + getRequestQualifier();
    String name = qualified ? qualifiedKey : key;
    Cookie cookie = new Cookie(name, value);
    /*//from   w  w  w .j a  v a 2s  . c  o  m
     * maximum age of the cookie in seconds; if negative, the cookie is not stored; if zero, deletes the cookie.
     */
    cookie.setMaxAge(expiry);
    response.addCookie(cookie);
    return name;
}

From source file:com.mockey.model.ResponseFromService.java

public void writeToOutput(HttpServletResponse resp) throws IOException {
    // copy the headers out
    if (headers != null) {
        for (Header header : headers) {

            // copy the cookies
            if (ignoreHeader(header.getName())) {
                log.debug("Ignoring header: " + header.getName());
            } else if (header.getName().equalsIgnoreCase("Set-Cookie")) {
                // Ignore...
            } else if (header.getName().equals("Content-Type")) {
                // copy the content type
                resp.setContentType(header.getValue());
            } else
                resp.setHeader(header.getName(), header.getValue());
        }/*from  w w w.  jav  a2  s  .  com*/
    }

    // For cookie information we already extracted from initialization.
    for (Cookie cookie : this.cookieList) {
        resp.addCookie(cookie);
    }
    if (body != null) {
        byte[] myISO88591asBytes = body.getBytes(HTTP.ISO_8859_1);
        new PrintStream(resp.getOutputStream()).write(myISO88591asBytes);
        resp.getOutputStream().flush();
    } else {
        PrintStream out = new PrintStream(resp.getOutputStream());
        out.println(body);
    }

}

From source file:es.pode.soporte.seguridad.openId.ui.openid.OpenIDAuthenticationProcessingFilter.java

private void setCookieAutenticado(HttpServletResponse response, String claimedIdentity) throws IOException {

    Cookie cookieOpenId = new Cookie(nombreCookieOpenId, claimedIdentity);
    cookieOpenId.setPath("/");
    //El tiempo de expiracin de la cookie se recoger del Agrega.properties

    int caducidadCookie = new Long(((System.currentTimeMillis()) * 1000)).intValue()
            + (new Integer(this.getAgregaPropertyValue(AgregaProperties.TIMEOUTCOOKIEOPENID))).intValue();
    if (log.isDebugEnabled())
        log.debug("caducidadCookie " + caducidadCookie);
    cookieOpenId.setMaxAge(caducidadCookie);
    //cookieOpenId.setMaxAge(-1);
    response.addCookie(cookieOpenId);

}

From source file:org.appverse.web.framework.backend.frontfacade.rest.authentication.controllers.BasicAuthenticationRESTController.java

/**
 * Authenticates an user. Requires basic authentication header.
 * @param httpServletRequest//from w  w  w.j a va 2 s .  co m
 * @param httpServletResponse
 * @return
 * @throws Exception
 */
@POST
@Produces(MediaType.APPLICATION_JSON)
@Path("login")
public Response login(@Context HttpServletRequest httpServletRequest,
        @Context HttpServletResponse httpServletResponse) throws Exception {

    String[] userNameAndPassword;

    // Invalidate session if exists
    HttpSession httpSession = httpServletRequest.getSession(false);
    if (httpSession != null)
        httpSession.invalidate();

    authenticationServiceFacade = (AuthenticationServiceFacade) applicationContext
            .getBean(AUTHENTICATION_SERVICE_NAME);

    try {
        userNameAndPassword = obtainUserAndPasswordFromBasicAuthenticationHeader(httpServletRequest);
    } catch (BadCredentialsException e) {
        httpServletResponse.addHeader("WWW-Authenticate", "Basic");
        return Response.status(Response.Status.UNAUTHORIZED).entity(new AuthorizationDataVO()).build();
    }

    //Create and set the cookie
    httpServletRequest.getSession(true);
    String jsessionId = httpServletRequest.getSession().getId();
    Cookie sessionIdCookie = new Cookie("JSESSIONID", jsessionId);
    httpServletResponse.addCookie(sessionIdCookie);

    // Obtain XSRFToken and add it as a response header
    String xsrfToken = SecurityHelper.createXSRFToken(httpServletRequest);
    httpServletResponse.addHeader(SecurityHelper.XSRF_TOKEN_NAME, xsrfToken);

    // Authenticate principal and return authorization data
    AuthorizationDataVO authData = authenticationServiceFacade.authenticatePrincipal(userNameAndPassword[0],
            userNameAndPassword[1]);

    // AuthorizationDataVO
    return Response.status(Response.Status.OK).entity(authData).build();
}

From source file:edu.jhu.pha.vospace.oauth.AuthorizationServlet.java

/**
 * @param request//from  w w  w .  j  a  va2 s. co  m
 * @param response
 * @param callbackUrl
 * @throws IOException
 * @throws Oops
 */
private void authorizeRequestToken(HttpServletRequest request, HttpServletResponse response, String username)
        throws Oops {

    String token = null, callbackUrl = null;

    Cookie[] cookies = request.getCookies();

    String shareId = null;

    if (null != request.getParameter("oauth_token")) {
        token = request.getParameter("oauth_token");
        callbackUrl = request.getParameter("oauth_callback");
    } else if (cookies != null) {
        OauthCookie parsedCookie = null;

        for (Cookie cookie : cookies) {
            if (cookie.getName().equals(OauthCookie.COOKIE_NAME)) {
                // Remove the temporary 3rd party app cookie
                Cookie removeCookie = new Cookie(OauthCookie.COOKIE_NAME, "");
                removeCookie.setMaxAge(0);
                response.addCookie(removeCookie);
                try {
                    parsedCookie = OauthCookie.create(cookie);
                    shareId = parsedCookie.getShareId();
                    if (isBlank(parsedCookie.getRequestToken()))
                        throw new Oops(
                                "No request token present in oauth cookie (\"" + cookie.getValue() + "\").");
                    logger.debug("Parsed oauth cookie \"" + cookie.getValue() + "\" as \""
                            + parsedCookie.toString() + "\".");
                } catch (IOException e) {
                    logger.debug("Error parsing cookie. Just removing it.");
                }
            }
        }

        if (null != parsedCookie) {
            token = parsedCookie.getRequestToken();
            callbackUrl = parsedCookie.getCallbackUrl();
        }
    }

    if (null == token)
        throw new Oops("No request token found in request.");

    try {
        Token reqToken = MySQLOAuthProvider2.getRequestToken(token);
        if (null == reqToken)
            throw new PermissionDeniedException("401 Unauthorized");
        if (null != reqToken.getAttributes().getFirst("root_container")) { // pre-shared container accessor
            if (shareId != null) {//already created the share - user bound sharing
                List<String> groupUserLogins = MySQLOAuthProvider2.getShareUsers(shareId);
                if (!groupUserLogins.contains(username)) { // the username of the one authorized != user that share was created for
                    throw new PermissionDeniedException("401 Unauthorized");
                }
            } // else share is open for everyone
        }

        MySQLOAuthProvider2.markAsAuthorized(reqToken, username);

        if (null != callbackUrl && !callbackUrl.isEmpty()) {
            if (callbackUrl.indexOf('?') <= 0)
                callbackUrl += "?" + "oauth_token=" + reqToken.getToken();
            else
                callbackUrl += "&" + "oauth_token=" + reqToken.getToken();
            logger.debug("Redirecting user to " + callbackUrl);
            response.sendRedirect(callbackUrl);
        } else {
            response.setContentType("text/plain");
            PrintWriter out = response.getWriter();
            out.println("You have successfully authorized "
                    + ".\nPlease close this browser window and click continue" + " in the client.");
            out.close();
        }
    } catch (IOException e) {
        logger.error("Error performing the token authorization " + e.getMessage());
        e.printStackTrace();
        throw new Oops(e.getMessage());
    }
}