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:de.theit.jenkins.crowd.CrowdServletFilter.java

/**
 * {@inheritDoc}/*from   w  w  w  .j  ava  2  s.  c  o m*/
 * 
 * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest,
 *      javax.servlet.ServletResponse, javax.servlet.FilterChain)
 */
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    if (request instanceof HttpServletRequest && response instanceof HttpServletResponse) {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse res = (HttpServletResponse) response;

        // check if we have a token
        // if it is not present, we are not / no longer authenticated
        boolean isValidated = false;
        try {
            isValidated = this.configuration.crowdHttpAuthenticator.isAuthenticated(req, res);
        } catch (OperationFailedException ex) {
            LOG.log(Level.SEVERE, operationFailed(), ex);
        }

        if (!isValidated) {
            if (LOG.isLoggable(Level.FINE)) {
                LOG.fine("User is not logged in (anymore) via Crowd => logout user");
            }
            SecurityContext sc = SecurityContextHolder.getContext();
            sc.setAuthentication(null);
            // close the SSO session
            if (null != this.rememberMe) {
                this.rememberMe.logout(req, res);
            }

            // invalidate the current session
            // (see SecurityRealm#doLogout())
            HttpSession session = req.getSession(false);
            if (session != null) {
                session.invalidate();
            }
            SecurityContextHolder.clearContext();

            // reset remember-me cookie
            Cookie cookie = new Cookie(SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY, "");
            cookie.setPath(req.getContextPath().length() > 0 ? req.getContextPath() : "/");
            res.addCookie(cookie);
        } else {
            SecurityContext sc = SecurityContextHolder.getContext();

            if (!(sc.getAuthentication() instanceof CrowdAuthenticationToken)) {
                // user logged in via Crowd, but no Crowd-specific
                // authentication token available
                // => try to auto-login the user
                if (null != this.rememberMe) {
                    if (LOG.isLoggable(Level.FINE)) {
                        LOG.fine(
                                "User is logged in via Crowd, but no authentication token available; trying auto-login...");
                    }
                    Authentication auth = this.rememberMe.autoLogin(req, res);
                    if (null != auth) {
                        if (LOG.isLoggable(Level.FINE)) {
                            LOG.fine("User sucessfully logged in");
                        }
                        sc.setAuthentication(auth);
                    }
                }
            }
        }
    }

    this.defaultFilter.doFilter(request, response, chain);
}

From source file:org.mitre.openid.connect.client.AbstractOIDCAuthenticationFilter.java

/**
 * Initiate an Authorization request/*w  w w.j av  a2s .  c om*/
 * 
 * @param request
 *            The request from which to extract parameters and perform the
 *            authentication
 * @param response
 *            The response, needed to set a cookie and do a redirect as part
 *            of a multi-stage authentication process
 * @param serverConfiguration
 * @throws IOException
 *             If an input or output exception occurs
 */
protected void handleAuthorizationRequest(HttpServletRequest request, HttpServletResponse response,
        OIDCServerConfiguration serverConfiguration) throws IOException {

    Map<String, String> urlVariables = new HashMap<String, String>();

    // Required parameters:

    urlVariables.put("response_type", "code");
    urlVariables.put("client_id", serverConfiguration.getClientId());
    urlVariables.put("scope", scope);
    urlVariables.put("redirect_uri", AbstractOIDCAuthenticationFilter.buildRedirectURI(request, null));

    // Create a string value used to associate a user agent session
    // with an ID Token to mitigate replay attacks. The value is
    // passed through unmodified to the ID Token. One method is to
    // store a random value as a signed session cookie, and pass the
    // value in the nonce parameter.

    String nonce = new BigInteger(50, new SecureRandom()).toString(16);

    Cookie nonceCookie = new Cookie(NONCE_SIGNATURE_COOKIE_NAME, sign(signer, privateKey, nonce.getBytes()));

    response.addCookie(nonceCookie);

    urlVariables.put("nonce", nonce);

    // Optional parameters:

    // TODO: display, prompt, request, request_uri

    String authRequest = AbstractOIDCAuthenticationFilter
            .buildURL(serverConfiguration.getAuthorizationEndpointURI(), urlVariables);

    logger.debug("Auth Request:  " + authRequest);

    response.sendRedirect(authRequest);
}

From source file:de.sainth.recipe.backend.security.AuthFilter.java

@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
        throws ServletException, IOException {
    String header = request.getHeader("Authorization");
    Optional<Cookie> cookie;
    if (request.getCookies() != null) {
        cookie = Arrays.stream(request.getCookies()).filter(c -> COOKIE_NAME.equals(c.getName())).findFirst();
    } else {//from w w  w  .j av a  2  s.  com
        cookie = Optional.empty();
    }
    if (!cookie.isPresent() && (header == null || header.length() == 0)) {
        throw new AccessDeniedException("No authentication information present");
    }
    RecipeManagerAuthenticationToken authentication;
    try {
        if (cookie.isPresent()) {
            authentication = parseToken(cookie.get().getValue());
        } else {
            Optional<RecipeManagerAuthenticationToken> maybeAuthentication;
            if (header.startsWith("Bearer ")) {
                maybeAuthentication = parseBearerToken(header);
            } else {
                maybeAuthentication = parseBasicAuth(header);
            }
            if (maybeAuthentication.isPresent()) {
                authentication = maybeAuthentication.get();
            } else {
                throw new AccessDeniedException("Bad credentials");
            }
        }
    } catch (ExpiredJwtException | SignatureException e) {
        throw new AccessDeniedException("Token not valid");
    }
    SecurityContextHolder.getContext().setAuthentication(authentication);
    response.addCookie(createCookie(authentication, request.isSecure()));

    chain.doFilter(request, response);
}

From source file:com.vmware.identity.openidconnect.sample.RelyingPartyController.java

@RequestMapping(value = "/redirect_implicit_flow_form_response", method = RequestMethod.POST)
public void redirectImplicitFlowFormResponse(HttpServletRequest request, HttpServletResponse response)
        throws OIDCClientException, OIDCServerException, TokenValidationException {
    AuthenticationTokensResponse authnTokensResponse = ListenerHelper.parseAuthenticationTokensResponse(request,
            clientConfig.getConnectionConfig().getProviderPublicKey(),
            clientConfig.getConnectionConfig().getIssuer(), clientConfig.getClientId(),
            clientConfig.getClockToleranceInSeconds());
    State state = authnTokensResponse.getState();
    OIDCTokens tokens = authnTokensResponse.getTokens();

    Nonce nonce = this.authnRequestTracker.remove(state);
    assert nonce != null;

    validateTokenResponse(tokens, TokenType.BEARER);
    assert Objects.equals(tokens.getIDToken().getNonce(), nonce);

    ResourceServerAccessToken.build(tokens.getAccessToken().getValue(), providerRSAPublicKey,
            providerMetadata.getIssuer(), resourceServers[0], CLOCK_TOLERANCE_SECONDS);

    SessionID sessionId = new SessionID();
    this.sessionManager.add(sessionId, tokens);

    response.addCookie(loginSessionCookie(sessionId));
    sendRedirect(response, rootUrl);//w w w .  j a v  a 2 s . co  m
}

From source file:com.google.gwt.jolokia.server.servlet.ProxyServlet.java

/**
 * Copy cookie from the proxy to the servlet client. Replaces cookie path to
 * local path and renames cookie to avoid collisions.
 *//*from   ww  w  .  j  a  v a 2s .c o  m*/
protected void copyProxyCookie(HttpServletRequest servletRequest, HttpServletResponse servletResponse,
        Header header) {
    List<HttpCookie> cookies = HttpCookie.parse(header.getValue());
    String path = getServletContext().getServletContextName();
    if (path == null) {
        path = "";
    }
    path += servletRequest.getServletPath();

    for (HttpCookie cookie : cookies) {
        // set cookie name prefixed w/ a proxy value so it won't collide w/
        // other cookies
        String proxyCookieName = getCookieNamePrefix() + cookie.getName();
        Cookie servletCookie = new Cookie(proxyCookieName, cookie.getValue());
        servletCookie.setComment(cookie.getComment());
        servletCookie.setMaxAge((int) cookie.getMaxAge());
        servletCookie.setPath(path); // set to the path of the proxy servlet
        // don't set cookie domain
        servletCookie.setSecure(cookie.getSecure());
        servletCookie.setVersion(cookie.getVersion());
        servletResponse.addCookie(servletCookie);
    }
}

From source file:org.itracker.web.util.LoginUtilities.java

public static User setupSession(User user, String encPassword, HttpServletRequest request,
        HttpServletResponse response) {
    if (user == null) {
        logger.warn("setupSession: null user", (logger.isDebugEnabled() ? new RuntimeException() : null));
        throw new IllegalArgumentException("null user");
    }//from  w w w .  ja v a2s  .co m

    UserService userService = ServletContextUtils.getItrackerServices().getUserService();

    if (logger.isDebugEnabled()) {
        logger.debug("Creating new session");
    }
    HttpSession session = request.getSession(true);

    if (logger.isDebugEnabled()) {
        logger.debug("Setting session timeout to " + getConfiguredSessionTimeout() + " minutes");
    }
    session.setMaxInactiveInterval(getConfiguredSessionTimeout() * 60);

    if (logger.isDebugEnabled()) {
        logger.debug("Setting session tracker");
    }
    session.setAttribute(Constants.SESSION_TRACKER_KEY, new SessionTracker(user.getLogin(), session.getId()));

    if (logger.isDebugEnabled()) {
        logger.debug("Setting user information");
    }
    session.setAttribute(Constants.USER_KEY, user);

    if (logger.isDebugEnabled()) {
        logger.debug("Setting preferences for user " + user.getLogin());
    }
    UserPreferences userPrefs = user.getPreferences();
    // TODO : this is a hack, remove when possible
    if (userPrefs == null) {
        logger.warn("setupSession: got user with no preferences!: " + user + " (prefs: " + user.getPreferences()
                + ")");
        userPrefs = new UserPreferences();
    }
    session.setAttribute(Constants.PREFERENCES_KEY, userPrefs);

    if (logger.isDebugEnabled()) {
        logger.debug("Setting user " + user + " locale to "
                + ITrackerResources.getLocale(userPrefs.getUserLocale()));
    }
    session.setAttribute(Constants.LOCALE_KEY, ITrackerResources.getLocale(userPrefs.getUserLocale()));

    // TODO: cookie could be removed
    Cookie cookie = new Cookie(Constants.COOKIE_NAME, "");
    cookie.setPath(request.getContextPath());

    cookie.setValue("");
    cookie.setMaxAge(0);

    response.addCookie(cookie);

    if (logger.isDebugEnabled()) {
        logger.debug("Setting permissions for user " + user.getLogin());
    }
    Map<Integer, Set<PermissionType>> usersMapOfProjectIdsAndSetOfPermissionTypes = userService
            .getUsersMapOfProjectIdsAndSetOfPermissionTypes(user, AuthenticationConstants.REQ_SOURCE_WEB);
    session.setAttribute(Constants.PERMISSIONS_KEY, usersMapOfProjectIdsAndSetOfPermissionTypes);

    // Reset some session forms
    session.setAttribute(Constants.SEARCH_QUERY_KEY, null);

    SessionManager.clearSessionNeedsReset(user.getLogin());
    if (logger.isDebugEnabled()) {
        logger.debug("User session data updated.");
    }
    return user;
}

From source file:com.fuseim.webapp.ProxyServlet.java

/**
 * Copy cookie from the proxy to the servlet client. Replaces cookie path to local path and
 * renames cookie to avoid collisions.//from ww  w .j  ava 2  s .  c o  m
 */
protected void copyProxyCookie(HttpServletRequest servletRequest, HttpServletResponse servletResponse,
        String headerValue) {
    List<HttpCookie> cookies = HttpCookie.parse(headerValue);
    String path = servletRequest.getContextPath(); // path starts with / or is empty string
    path += servletRequest.getServletPath(); // servlet path starts with / or is empty string

    for (HttpCookie cookie : cookies) {
        //set cookie name prefixed w/ a proxy value so it won't collide w/ other cookies
        String proxyCookieName = doPreserveCookies ? cookie.getName()
                : getCookieNamePrefix(cookie.getName()) + cookie.getName();
        Cookie servletCookie = new Cookie(proxyCookieName, cookie.getValue());
        servletCookie.setComment(cookie.getComment());
        servletCookie.setMaxAge((int) cookie.getMaxAge());
        servletCookie.setPath(path); //set to the path of the proxy servlet
        // don't set cookie domain
        servletCookie.setSecure(cookie.getSecure());
        servletCookie.setVersion(cookie.getVersion());
        servletResponse.addCookie(servletCookie);
    }
}

From source file:org.sakaiproject.metaobj.utils.mvc.impl.servlet.FormControllerImpl.java

protected ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object command,
        BindException errors) throws Exception {

    Map requestMap = HttpServletHelper.getInstance().createRequestMap(request);
    Map session = HttpServletHelper.getInstance().createSessionMap(request);
    Map application = HttpServletHelper.getInstance().createApplicationMap(request);

    ModelAndView returnedMv;//w ww .ja v  a 2  s .co m

    if (controller instanceof CancelableController
            && ((CancelableController) controller).isCancel(requestMap)) {
        returnedMv = ((CancelableController) controller).processCancel(requestMap, session, application,
                command, errors);
    } else {
        returnedMv = controller.handleRequest(command, requestMap, session, application, errors);
    }

    boolean saveCookies = ServerConfigurationService.getBoolean(PROP_SAVE_COOKIES, false);

    if (errors.hasErrors()) {
        logger.debug("Form submission errors: " + errors.getErrorCount());
        HttpServletHelper.getInstance().reloadApplicationMap(request, application);
        HttpServletHelper.getInstance().reloadSessionMap(request, session);
        HttpServletHelper.getInstance().reloadRequestMap(request, requestMap);
        if (saveCookies) {
            Cookie cookie = new Cookie(FormHelper.FORM_SAVE_ATTEMPT, "yes");
            cookie.setMaxAge(30);
            cookie.setPath("/");
            response.addCookie(cookie);
        }
        return showForm(request, response, errors);
    }

    if (returnedMv.getViewName() != null) {
        // should get from mappings
        String mappedView = (String) screenMappings.get(returnedMv.getViewName());

        if (mappedView == null) {
            mappedView = returnedMv.getViewName();
        }

        //getControllerFilterManager().processFilters(requestMap, session, application, returnedMv, mappedView);

        returnedMv = new ModelAndView(mappedView, returnedMv.getModel());
    }

    //We have a successful save coming back, so we set/append to a cookie
    String savedForm = (String) session.get(FormHelper.FORM_SAVE_SUCCESS);
    if (savedForm != null && saveCookies) {
        Cookie cookie = null;
        if (request.getCookies() != null) {
            for (Cookie c : request.getCookies()) {
                if (FormHelper.FORM_SAVE_SUCCESS.equals(c.getName())) {
                    String[] forms = c.getValue().split(",");
                    StringBuilder value = new StringBuilder();
                    boolean alreadyIncluded = false;
                    for (String form : forms) {
                        if (form.equals(savedForm)) {
                            alreadyIncluded = true;
                        }
                        value.append(",").append(form);
                    }
                    if (!alreadyIncluded) {
                        value.append(",").append(savedForm);
                    }
                    cookie = new Cookie(FormHelper.FORM_SAVE_SUCCESS, value.substring(1));
                }
            }
        }
        if (cookie == null) {
            cookie = new Cookie(FormHelper.FORM_SAVE_SUCCESS, savedForm);
        }
        cookie.setMaxAge(2000000);
        cookie.setPath("/");
        response.addCookie(cookie);
    }

    HttpServletHelper.getInstance().reloadApplicationMap(request, application);
    HttpServletHelper.getInstance().reloadSessionMap(request, session);
    HttpServletHelper.getInstance().reloadRequestMap(request, requestMap);

    return returnedMv;
}

From source file:com.google.gsa.Kerberos.java

/**
 * Add a new cookie to the response/*from  w  w w. j av a2 s  .com*/
 * 
 * @param response HTTP response
 * @param krbCookie cookie
 */
private void addKrbCookie(HttpServletResponse response, Cookie krbCookie) {
    boolean sendCookies = true;
    if (valveConf.getSessionConfig().isSessionEnabled().equals("true")) {
        if (valveConf.getSessionConfig().getSendCookies().equals("false")) {
            sendCookies = false;
        }
    }
    if (!sendCookies) {
        //add Krb cookie into the response
        response.addCookie(krbCookie);
    }
}

From source file:com.vmware.identity.openidconnect.sample.RelyingPartyController.java

private void redirectAuthzCodeFlow(HttpServletRequest request, HttpServletResponse response, URI redirectUri)
        throws OIDCClientException, OIDCServerException, TokenValidationException, SSLConnectionException {
    AuthenticationCodeResponse authnCodeResponse = ListenerHelper.parseAuthenticationCodeResponse(request);
    State state = authnCodeResponse.getState();
    AuthorizationCode authzCode = authnCodeResponse.getAuthorizationCode();

    Nonce nonce = this.authnRequestTracker.remove(state);
    assert nonce != null;

    OIDCTokens tokens = client.acquireTokensByAuthorizationCode(authzCode, redirectUri);
    validateTokenResponse(tokens, TokenType.HOK);

    assert Objects.equals(tokens.getIDToken().getNonce(), nonce);

    ResourceServerAccessToken.build(tokens.getAccessToken().getValue(), providerRSAPublicKey,
            providerMetadata.getIssuer(), resourceServers[0], CLOCK_TOLERANCE_SECONDS);

    OIDCTokens tokensNotUsed = client.acquireTokensByRefreshToken(tokens.getRefreshToken());
    validateTokenResponse(tokensNotUsed, TokenType.HOK);

    SessionID sessionId = new SessionID();
    this.sessionManager.add(sessionId, tokens);

    response.addCookie(loginSessionCookie(sessionId));
    sendRedirect(response, rootUrl);/*  w w  w  . ja v  a  2 s .co  m*/
}