Example usage for javax.servlet.http Cookie setHttpOnly

List of usage examples for javax.servlet.http Cookie setHttpOnly

Introduction

In this page you can find the example usage for javax.servlet.http Cookie setHttpOnly.

Prototype

public void setHttpOnly(boolean isHttpOnly) 

Source Link

Document

Marks or unmarks this Cookie as <i>HttpOnly</i>.

Usage

From source file:org.orcid.core.manager.impl.InternalSSOManagerImpl.java

@Override
public void deleteToken(String orcid, HttpServletRequest request, HttpServletResponse response) {
    this.deleteToken(orcid);
    // Delete the cookie
    if (request.getCookies() != null) {
        for (Cookie cookie : request.getCookies()) {
            if (cookie.getName().equals(COOKIE_NAME)) {
                cookie.setMaxAge(0);/*from  ww  w . j  av  a 2s .  c o m*/
                cookie.setValue(StringUtils.EMPTY);
                cookie.setSecure(true);
                cookie.setHttpOnly(true);
                cookie.setDomain(allowedDomain.trim());
                response.addCookie(cookie);
            }
        }
    }
}

From source file:org.orcid.core.manager.impl.InternalSSOManagerImpl.java

@SuppressWarnings("unchecked")
@Override// www  .j a va 2 s.c o  m
public void updateCookie(String orcid, HttpServletRequest request, HttpServletResponse response) {
    if (request.getCookies() != null) {
        for (Cookie cookie : request.getCookies()) {
            if (cookie.getName().equals(COOKIE_NAME)) {
                HashMap<String, String> cookieValues = JsonUtils.readObjectFromJsonString(cookie.getValue(),
                        HashMap.class);
                if (cookieValues.containsKey(COOKIE_KEY_TOKEN)) {
                    if (internalSSODao.update(orcid, cookieValues.get(COOKIE_KEY_TOKEN))) {
                        //Create new cookie
                        Cookie tokenCookie = new Cookie(COOKIE_NAME, cookie.getValue());
                        tokenCookie.setMaxAge(maxAgeMinutes * 60);
                        tokenCookie.setPath("/");
                        tokenCookie.setSecure(true);
                        tokenCookie.setHttpOnly(true);
                        tokenCookie.setDomain(allowedDomain.trim());
                        //Add new cookie to response
                        response.addCookie(tokenCookie);
                    }
                }
                break;
            }
        }
    }
}

From source file:com.thoughtworks.go.http.mocks.MockHttpServletResponseAssert.java

public SELF hasCookie(String path, String name, String value, int maxAge, boolean secured, boolean httpOnly) {
    Cookie actualCookie = actual.getCookie(name);

    Cookie expectedCookie = new Cookie(name, value);
    expectedCookie.setDomain("");
    expectedCookie.setPath(path);//from w  ww  .  ja v a  2 s.c om
    expectedCookie.setMaxAge(maxAge);
    expectedCookie.setSecure(secured);
    expectedCookie.setHttpOnly(httpOnly);

    if (!EqualsBuilder.reflectionEquals(expectedCookie, actualCookie)) {
        this.as("cookie");

        throw Failures.instance().failure(info,
                shouldBeEqual(ReflectionToStringBuilder.toString(actualCookie, ToStringStyle.MULTI_LINE_STYLE),
                        ReflectionToStringBuilder.toString(expectedCookie, ToStringStyle.MULTI_LINE_STYLE),
                        info.representation()));
    }
    return myself;
}

From source file:com.vmware.identity.openidconnect.server.AuthenticationRequestProcessor.java

private Cookie loggedInSessionCookie(SessionID sessionId) {
    Cookie cookie = new Cookie(SessionManager.getSessionCookieName(this.tenant), sessionId.getValue());
    cookie.setPath("/openidconnect");
    cookie.setSecure(true);/*from   www . j a v  a  2  s . co  m*/
    cookie.setHttpOnly(true);
    return cookie;
}

From source file:org.springframework.http.server.reactive.ServletServerHttpResponse.java

@Override
protected void writeCookies() {
    for (String name : getCookies().keySet()) {
        for (ResponseCookie httpCookie : getCookies().get(name)) {
            Cookie cookie = new Cookie(name, httpCookie.getValue());
            if (!httpCookie.getMaxAge().isNegative()) {
                cookie.setMaxAge((int) httpCookie.getMaxAge().getSeconds());
            }/*from www.  j  a v  a  2  s  .c  o  m*/
            httpCookie.getDomain().ifPresent(cookie::setDomain);
            httpCookie.getPath().ifPresent(cookie::setPath);
            cookie.setSecure(httpCookie.isSecure());
            cookie.setHttpOnly(httpCookie.isHttpOnly());
            this.response.addCookie(cookie);
        }
    }
}

From source file:com.haulmont.idp.controllers.IdpController.java

@PostMapping(value = "/auth", produces = "application/json; charset=UTF-8")
@ResponseBody//  ww  w . java2  s.c o m
public AuthResponse authenticate(@RequestBody AuthRequest auth,
        @CookieValue(value = CUBA_IDP_COOKIE_NAME, defaultValue = "") String idpSessionCookie,
        HttpServletResponse response) {
    String serviceProviderUrl = auth.getServiceProviderUrl();

    if (!Strings.isNullOrEmpty(serviceProviderUrl)
            && !idpConfig.getServiceProviderUrls().contains(serviceProviderUrl)) {
        log.warn("Incorrect serviceProviderUrl {} passed, will be used default", serviceProviderUrl);
        serviceProviderUrl = null;
    }

    if (Strings.isNullOrEmpty(serviceProviderUrl)) {
        if (!idpConfig.getServiceProviderUrls().isEmpty()) {
            serviceProviderUrl = idpConfig.getServiceProviderUrls().get(0);
        } else {
            log.error("IDP property cuba.idp.serviceProviderUrls is not set");
            response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
            return null;
        }
    }

    Locale sessionLocale = null;
    if (globalConfig.getLocaleSelectVisible() && auth.getLocale() != null) {
        Map<String, Locale> availableLocales = globalConfig.getAvailableLocales();
        Locale requestedLocale = Locale.forLanguageTag(auth.getLocale());

        if (availableLocales.containsValue(requestedLocale)) {
            sessionLocale = requestedLocale;
        }
    }
    if (sessionLocale == null) {
        sessionLocale = messageTools.getDefaultLocale();
    }

    if (!Strings.isNullOrEmpty(idpSessionCookie)) {
        boolean loggedOut = idpService.logout(idpSessionCookie);

        if (loggedOut) {
            log.info("Logged out IDP session {}", idpSessionCookie);

            logoutCallbackInvoker.performLogoutOnServiceProviders(idpSessionCookie);
        }
    }

    IdpService.IdpLoginResult loginResult;
    try {
        loginResult = idpService.login(auth.getUsername(), passwordEncryption.getPlainHash(auth.getPassword()),
                sessionLocale, ImmutableMap.of(ClientType.class.getName(), ClientType.WEB.name()));
    } catch (LoginException e) {
        // remove auth cookie
        Cookie cookie = new Cookie(CUBA_IDP_COOKIE_NAME, "");
        cookie.setMaxAge(0);
        response.addCookie(cookie);

        log.warn("Unable to login user {}", auth.getUsername());
        return AuthResponse.failed("invalid_credentials");
    }

    if (loginResult.getSessionId() != null) {
        Cookie idpCookie = new Cookie(CUBA_IDP_COOKIE_NAME, loginResult.getSessionId());
        idpCookie.setMaxAge(idpConfig.getIdpCookieMaxAge());
        idpCookie.setHttpOnly(idpConfig.getIdpCookieHttpOnly());
        response.addCookie(idpCookie);
    }

    String serviceProviderRedirectUrl;
    try {
        URIBuilder uriBuilder = new URIBuilder(serviceProviderUrl);

        if ("client-ticket".equals(auth.getResponseType())) {
            uriBuilder.setFragment(CUBA_IDP_TICKET_PARAMETER + "=" + loginResult.getServiceProviderTicket());
        } else {
            uriBuilder.setParameter(CUBA_IDP_TICKET_PARAMETER, loginResult.getServiceProviderTicket());
        }

        serviceProviderRedirectUrl = uriBuilder.build().toString();
    } catch (URISyntaxException e) {
        return AuthResponse.failed("invalid_params");
    }

    log.info("Logged in IDP session with ticket {}, user: {}", loginResult.getServiceProviderTicket(),
            auth.getUsername());

    return AuthResponse.authenticated(serviceProviderRedirectUrl);
}

From source file:org.springframework.web.util.CookieGenerator.java

/**
 * Add a cookie with the given value to the response,
 * using the cookie descriptor settings of this generator.
 * <p>Delegates to {@link #createCookie} for cookie creation.
 * @param response the HTTP response to add the cookie to
 * @param cookieValue the value of the cookie to add
 * @see #setCookieName//w  ww. j a v a  2  s  . c o m
 * @see #setCookieDomain
 * @see #setCookiePath
 * @see #setCookieMaxAge
 */
public void addCookie(HttpServletResponse response, String cookieValue) {
    Assert.notNull(response, "HttpServletResponse must not be null");
    Cookie cookie = createCookie(cookieValue);
    Integer maxAge = getCookieMaxAge();
    if (maxAge != null) {
        cookie.setMaxAge(maxAge);
    }
    if (isCookieSecure()) {
        cookie.setSecure(true);
    }
    if (isCookieHttpOnly()) {
        cookie.setHttpOnly(true);
    }
    response.addCookie(cookie);
    if (logger.isDebugEnabled()) {
        logger.debug("Added cookie with name [" + getCookieName() + "] and value [" + cookieValue + "]");
    }
}

From source file:com.silverpeas.authentication.AuthenticationServlet.java

/**
 * Write session cookie./* w  w w  .j ava  2 s .c om*/
 *
 * @return
 */
private void writeSessionCookie(HttpServletResponse response, HttpSession session, boolean secured) {
    Cookie cookie = new Cookie("JSESSIONID", session.getId());
    cookie.setMaxAge(-1);
    cookie.setPath(session.getServletContext().getContextPath());
    cookie.setHttpOnly(true);
    if (secured) {
        cookie.setSecure(secured);
    }
    response.addCookie(cookie);
}

From source file:com.shenit.commons.utils.HttpUtils.java

/**
 * cookie//from w  w w.j av  a  2 s  .  c  om
 * 
 * @param name
 *            Cookie??
 * @param val
 *            
 * @param expiry
 *            
 * @param domain
 *            
 * @param path
 *            
 * @param httpOnly
 *            ??HTTPcooie
 * @param secure
 *            ?SSL
 * @return
 */
public static Cookie cookie(String name, Object val, Integer expiry, String domain, String path,
        boolean httpOnly, boolean secure) {
    Cookie cookie = new Cookie(name, val == null ? null : val.toString());
    if (expiry != null)
        cookie.setMaxAge(expiry);
    if (!StringUtils.isEmpty(domain))
        cookie.setDomain(domain);
    cookie.setSecure(secure);
    if (!StringUtils.isEmpty(path))
        cookie.setPath(path);
    cookie.setHttpOnly(httpOnly);
    return cookie;
}

From source file:com.nominanuda.web.http.ServletHelper.java

public Cookie servletCookie(HttpCookie c) {
    Cookie _c = new Cookie(c.getName(), c.getValue());
    if (c.getComment() != null) {
        _c.setComment(c.getComment());// w  w  w.  j  a va  2 s.  c  o m
    }
    if (c.getDomain() != null) {
        _c.setDomain(c.getDomain());
    }
    if (c.getPath() != null) {
        _c.setPath(c.getPath());
    }
    _c.setSecure(c.getSecure());
    _c.setVersion(c.getVersion());
    _c.setHttpOnly(c.getDiscard());
    _c.setMaxAge((int) c.getMaxAge());
    return _c;
}