Example usage for javax.servlet.http Cookie setPath

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

Introduction

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

Prototype

public void setPath(String uri) 

Source Link

Document

Specifies a path for the cookie to which the client should return the cookie.

Usage

From source file:org.moserp.infrastructure.gateway.config.OAuthConfiguration.java

/**
 * Spring security offers in-built protection for cross site request forgery
 * (CSRF) by needing a custom token in the header for any requests that are
 * NOT safe i.e. modify the resources from the server e.g. POST, PUT & PATCH
 * etc.<br>/*from w  w  w  . j  a  va2  s.c  om*/
 * <br>
 *
 * This protection is achieved using cookies that send a custom value (would
 * remain same for the session) in the first request and then the front-end
 * would send back the value as a custom header.<br>
 * <br>
 *
 * In this method we create a filter that is applied to the web security as
 * follows:
 * <ol>
 * <li>Spring security provides the CSRF token value as a request attribute;
 * so we extract it from there.</li>
 * <li>If we have the token, Angular wants the cookie name to be
 * "XSRF-TOKEN". So we add the cookie if it's not there and set the path for
 * the cookie to be "/" which is root. In more complicated cases, this might
 * have to be the context root of the api gateway.</li>
 * <li>We forward the request to the next filter in the chain</li>
 * </ol>
 *
 * The request-to-cookie filter that we add needs to be after the
 * <code>csrf()</code> filter so that the request attribute for CsrfToken
 * has been already added before we start to process it.
 *
 * @return
 */
private Filter createCSRFHeaderFilter() {
    return new OncePerRequestFilter() {
        @Override
        protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
                FilterChain filterChain) throws ServletException, IOException {
            CsrfToken csrf = (CsrfToken) request.getAttribute(CsrfToken.class.getName());
            if (csrf != null) {
                Cookie cookie = WebUtils.getCookie(request, CSRF_COOKIE_NAME);
                String token = csrf.getToken();
                if (cookie == null || token != null && !token.equals(cookie.getValue())) {
                    cookie = new Cookie(CSRF_COOKIE_NAME, token);
                    cookie.setPath("/");
                    response.addCookie(cookie);
                }
            }
            filterChain.doFilter(request, response);
        }
    };
}

From source file:com.junly.service.helper.TicketHelper.java

/** <p class="detail">
* cookie//from w  w  w  . j av  a 2s  . c o  m
* </p>
* @author junly
* @date 2016422 
* @param response
* @param ticket    
*/
public void setCookie(HttpServletRequest request, HttpServletResponse response, String ticket) {
    // ?
    Cookie cookie = new Cookie(ViewContants.LOGIN_TICKET_KEY, ticket);

    // ? ???
    cookie.setDomain(request.getServerName());
    // path
    cookie.setPath("/");
    // ??
    cookie.setMaxAge(ViewContants.TRUST_COOKIE_TIME); // 
    response.addCookie(cookie);
}

From source file:com.ms.commons.cookie.parser.CookieNameHelper.java

/**
 * ????CookieName?Response//from   w  w  w  . j ava 2s.c  o m
 * 
 * <pre>
 * cookie<code>null</code>blankCookie
 * </pre>
 */
public void saveIfModified(HttpServletResponse response) {
    if (!isModified) {
        return;
    }
    String value = config.isSimpleValue() ? simpleValue : CookieUtils.mapToStr(allCookieKeyValues);
    if (config.isEncrypt()) {
        value = CookieUtils.encrypt(value);
    }
    Cookie cookie = new Cookie(cookieName, value);
    if (StringUtils.isBlank(value)) {
        cookie.setMaxAge(CookieMaxAge.OUT_OF_DATE);
    } else {
        cookie.setMaxAge(config.getMaxAge());
    }
    cookie.setDomain(config.getDomain().getDomain());
    cookie.setPath(config.getPath().getPath());
    response.addCookie(cookie);

    // ?????
    this.isModified = false;
}

From source file:com.mmj.app.common.cookie.parser.CookieNameHelper.java

/**
 * ????CookieName?Response/* w w w  .  ja v  a  2  s .  c  om*/
 * 
 * <pre>
 * cookie<code>null</code>blankCookie
 * </pre>
 */
public void saveIfModified(HttpServletResponse response) {
    if (!isModified) {
        return;
    }
    String value = config.isSimpleValue() ? simpleValue : CookieUtils.mapToStr(allCookieKeyValues);
    if (config.isEncrypt()) {
        value = EncryptBuilder.getInstance().encrypt(value);
    }
    Cookie cookie = new Cookie(cookieName, value);
    if (StringUtils.isBlank(value)) {
        cookie.setMaxAge(CookieMaxAge.OUT_OF_DATE);
    } else {
        cookie.setMaxAge(config.getMaxAge());
    }
    cookie.setDomain(config.getDomain().getDomain());
    cookie.setPath(config.getPath().getPath());
    response.addCookie(cookie);

    // ?????
    this.isModified = false;
}

From source file:org.infoscoop.web.AuthenticationServlet.java

protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    String action = ((HttpServletRequest) request).getPathInfo();
    String uid = request.getParameter("uid");
    if (uid != null) {
        uid = uid.trim();/*from  w  w  w. j  a v a 2  s.  c  o m*/
    }
    String password = request.getParameter("password");
    if (password != null) {
        password = password.trim();
    }
    String new_password = request.getParameter("new_password");
    if (new_password != null) {
        new_password = new_password.trim();
    }

    if (log.isDebugEnabled()) {
        log.debug("uid=" + uid + ",password=" + password);
    }
    String errorPath = "/login.jsp";
    if ("/changePassword".equals(action))
        errorPath = "/changePassword.jsp";

    HttpSession session = request.getSession();
    try {
        AuthenticationService service = AuthenticationService.getInstance();
        if (service == null) {
            log.error("No bean named \"authenticationService\" is defined."
                    + " When loginAuthentication property is true,"
                    + " authenticationService must be defined.");
            session.setAttribute("errorMsg", "ms_authServiceAccessFailed");
            ((HttpServletResponse) response).sendRedirect(request.getContextPath() + errorPath);
            return;
        }

        if (isDenyEmptyPassword && "".equals(password)) {
            session.setAttribute("errorMsg", "ms_noInputPassword");
            ((HttpServletResponse) response).sendRedirect(request.getContextPath() + errorPath);
            return;
        }

        if ("/changePassword".equals(action)) {
            if (isDenyEmptyPassword && "".equals(new_password)) {
                session.setAttribute("errorMsg", "ms_noInputPassword");
                ((HttpServletResponse) response).sendRedirect(request.getContextPath() + errorPath);
                return;
            }

            service.changePassword(uid, new_password, password);

            session.setAttribute("errorMsg", "ms_passwordChanged");
            ((HttpServletResponse) response).sendRedirect(request.getContextPath() + "/login.jsp");
            return;
        } else {
            service.login(uid, password);

            request.getSession().setAttribute("Uid", uid);
            //request.getSession().setAttribute(AuthenticationServlet.TMP_LOGINUSER_SUBJECT_ATTR_NAME, loginUser );
            String authType = PropertiesService.getHandle().getProperty("loginCredentialAuthType");
            if (authType != null) {
                authType = authType.trim().toLowerCase();
                if (!"".equals(authType))
                    AuthCredentialService.getHandle().addLoginCredential(uid, authType, password, null);
                else {
                    AuthCredential c = AuthCredentialService.getHandle().getLoginCredential(uid);
                    if (c != null)
                        AuthCredentialService.getHandle().removeCredential(c);
                }
            }

            int keepPeriod = 7;
            try {
                keepPeriod = Integer
                        .parseInt(PropertiesDAO.newInstance().findProperty("loginStateKeepPeriod").getValue());
            } catch (Exception ex) {
                log.warn("", ex);
            }

            if (keepPeriod > 0) {
                String saveLoginState = request.getParameter("saveLoginState");
                if ("on".equalsIgnoreCase(saveLoginState)) {
                    Cookie credentialCookie = new Cookie("portal-credential",
                            getCredentialString(uid, password));
                    credentialCookie.setPath("/");
                    credentialCookie.setMaxAge(keepPeriod * 24 * 60 * 60);
                    response.addCookie(credentialCookie);
                }
            }
        }
        String redirectPath = "/index.jsp";
        Cookie[] cookies = request.getCookies();
        for (int i = 0; i < cookies.length; i++) {
            if ("redirect_path".equals(cookies[i].getName())) {
                redirectPath = cookies[i].getValue();
                break;
            }
        }
        ((HttpServletResponse) response).sendRedirect(request.getContextPath() + redirectPath);
    } catch (AuthenticationException e) {
        String logMsg = "authentication failed. ";
        log.error(logMsg, e);

        String resourceId = e.getResourceId();
        session.setAttribute("errorMsg", (resourceId != null) ? resourceId : "ms_invalidUsernameOrPassword");
        //getServletContext().getRequestDispatcher(errorPath).forward(request, response);
        ((HttpServletResponse) response).sendRedirect(request.getContextPath() + errorPath);
    } catch (Exception e) {
        String logMsg = "unexpected error occured. ";
        log.error(logMsg, e);
        session.setAttribute("errorMsg", "ms_authServiceAccessFailed");
        //getServletContext().getRequestDispatcher(errorPath).forward(request, response);
        ((HttpServletResponse) response).sendRedirect(request.getContextPath() + errorPath);
    }
}

From source file:io.mapzone.controller.vm.http.HttpResponseForwarder.java

/**
 * Copy cookie from the proxy to the servlet client. Replaces cookie path to
 * local path and renames cookie to avoid collisions.
 *///from   w  ww .jav  a 2 s.  c om
protected void copyProxyCookie(HttpServletRequest servletRequest, HttpServletResponse servletResponse,
        Header header) {
    List<HttpCookie> cookies = HttpCookie.parse(header.getValue());
    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 = requestForwarder.cookieNamePrefix.get() + 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:net.ymate.platform.webmvc.util.CookieHelper.java

/**
 * @param key    /*  w  w  w  .  j a v a2s.  co m*/
 * @param value  
 * @param maxAge 
 * @return ?Cookie
 */
public CookieHelper setCookie(String key, String value, int maxAge) {
    Cookie _cookie = new Cookie(__owner.getModuleCfg().getCookiePrefix() + key,
            StringUtils.isBlank(value) ? "" : encodeValue(value));
    _cookie.setMaxAge(maxAge);
    _cookie.setPath(__owner.getModuleCfg().getCookiePath());
    if (StringUtils.isNotBlank(__owner.getModuleCfg().getCookieDomain())) {
        _cookie.setDomain(__owner.getModuleCfg().getCookieDomain());
    }
    _cookie.setSecure(WebContext.getRequest().isSecure());
    WebContext.getResponse().addCookie(_cookie);
    return this;
}

From source file:org.gss_project.gss.server.rest.UserHandler.java

/**
 * Handle POST requests in the users namespace.
 *
  * @param req The servlet request we are processing
  * @param resp The servlet response we are processing
  * @throws IOException if an input/output error occurs
 *//* w w  w  . j  av a  2s  . c  o  m*/
void postUser(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    try {
        final User user = getUser(req);
        User owner = getOwner(req);
        if (!owner.equals(user))
            throw new InsufficientPermissionsException("User " + user.getUsername()
                    + " does not have permission to modify " + owner.getUsername());
        boolean hasResetWebDAVParam = req.getParameterMap().containsKey(RESET_WEBDAV_PARAMETER);
        if (hasResetWebDAVParam) {
            String newPassword = new TransactionHelper<String>().tryExecute(new Callable<String>() {
                @Override
                public String call() throws Exception {
                    return getService().resetWebDAVPassword(user.getId());
                }
            });

            // Set the cookie again to send new value
            Cookie cookie = new Cookie(Login.WEBDAV_COOKIE, newPassword);
            cookie.setMaxAge(-1);
            String domain = req.getRemoteHost();
            String path = req.getContextPath();
            cookie.setDomain(domain);
            cookie.setPath(path);
            resp.addCookie(cookie);
        }
        // Workaround for IE's broken caching behavior.
        resp.setHeader("Expires", "-1");
    } catch (ObjectNotFoundException e) {
        resp.sendError(HttpServletResponse.SC_NOT_FOUND, e.getMessage());
    } catch (RpcException e) {
        logger.error("", e);
        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    } catch (InsufficientPermissionsException e) {
        resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED, e.getMessage());
    } catch (Exception e) {
        logger.error("", e);
        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }
}

From source file:com.music.web.AuthenticationController.java

@RequestMapping("/logout")
public String logout(HttpSession session, HttpServletRequest request, HttpServletResponse response) {
    session.invalidate();// w  ww .j a  v  a  2 s  . co m
    Cookie cookie = WebUtils.getCookie(request, SocialSignInAdapter.AUTH_TOKEN_COOKIE_NAME);
    if (cookie != null) {
        cookie.setMaxAge(0);
        cookie.setDomain(".computoser.com");
        cookie.setPath("/");
        response.addCookie(cookie);
    }

    cookie = WebUtils.getCookie(request, SocialSignInAdapter.AUTH_TOKEN_SERIES_COOKIE_NAME);
    if (cookie != null) {
        cookie.setMaxAge(0);
        cookie.setDomain(".computoser.com");
        cookie.setPath("/");
        response.addCookie(cookie);
    }

    return "redirect:/";
}

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

@Override
public void initPortalSession(final HttpServletRequest request, final HttpServletResponse response) {
    String portalSessionId = this.getPortalSessionId(request);

    if (portalSessionId == null) {
        // Can't find session Id => session wasn't initialized
        portalSessionId = this.genSessionId(request);

        this.initSessionBucket(portalSessionId);

        // Put sessionId in Cookie
        final Cookie portalSessionCookie = new Cookie(IPortal.PORTAL_SESSION_ID_COOKIE_NAME, portalSessionId);
        portalSessionCookie.setPath("/");
        response.addCookie(portalSessionCookie);

        // Put sessionId in current Http request
        request.setAttribute(IPortal.PORTAL_SESSION_ID_PARAM_NAME, portalSessionId);
    }/*from   ww  w .  j  av a2 s . co  m*/

}