Example usage for javax.servlet.http Cookie setSecure

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

Introduction

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

Prototype

public void setSecure(boolean flag) 

Source Link

Document

Indicates to the browser whether the cookie should only be sent using a secure protocol, such as HTTPS or SSL.

Usage

From source file:servlets.MobileLogin.java

/** 
 * Initiated by login.jsp. Once this post request has been completely processed, the user will be logged in, the account will be one count closer to been temporarily been locked or will be locked out temporarily.
 * This method takes the credentials submitted and determines if they are correct. If they are correct, a session is prepared for the user and they are assigned a CSRF token.
 * @param login User's User Name/*w  w w. ja va2 s  . co m*/
 * @param pwd User's Password      
 */
@SuppressWarnings("unchecked")
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    //Setting IpAddress To Log and taking header for original IP if forwarded from proxy
    ShepherdLogManager.setRequestIp(request.getRemoteAddr(), request.getHeader("X-Forwarded-For"));
    log.debug("**** servlets.MobileLogin ***");
    HttpSession ses = request.getSession(true);
    PrintWriter out = response.getWriter();
    out.print(getServletInfo());
    response.setContentType("application/json");
    // params
    String p_login = request.getParameter("login");
    log.debug("userName: " + p_login);
    String p_pwd = request.getParameter("pwd");
    String csrfToken = new String();

    boolean authenticated = false;

    // session is not new, try to set credentials
    p_login = nvl(p_login, (String) ses.getAttribute("login"));
    p_pwd = nvl(p_pwd, (String) ses.getAttribute("password"));
    // get credentials
    String ApplicationRoot = getServletContext().getRealPath("");
    try {
        String user[] = Getter.authUser(ApplicationRoot, p_login, p_pwd);
        if (user != null && !user[0].isEmpty()) {

            //Kill Session and Create a new one with user logged in
            log.debug("Creating new session for " + user[2] + " " + user[1]);
            ses.invalidate();
            ses = request.getSession(true);
            ses.setAttribute("userStamp", user[0]);
            ses.setAttribute("userName", user[1]);
            ses.setAttribute("userRole", user[2]);
            //Used to make returned Keys user specific. Transferred to Exposed Server
            String encyptedUserName = Hash.encrypt(Hash.userNameKey, p_login);
            ses.setAttribute("ThreadSequenceId", encyptedUserName);
            log.debug("userClassId = " + user[4]);

            ses.setAttribute("userClass", user[4]);
            log.debug("Setting CSRF cookie");
            csrfToken = Hash.randomString();
            Cookie token = new Cookie("token", csrfToken);
            if (request.getRequestURL().toString().startsWith("https"))//If Requested over HTTPs
                token.setSecure(true);
            response.addCookie(token);
            authenticated = true;

            if (user[3].equalsIgnoreCase("true")) {
                log.debug("Temporary Password Detected, user will be prompted to change");
                ses.setAttribute("ChangePassword", "true");
            }
            //Removing user from kick list. If they were on it before, their suspension must have ended if they DB authentication Succeeded
            UserKicker.removeFromKicklist(user[1]);
        }
    } catch (Exception e) {
        log.error("Could not Find User: " + e.toString());
    }
    if (authenticated) {
        //returning SessionID and CSRF Token
        JSONObject jsonObj = new JSONObject();
        jsonObj.put("JSESSIONID", ses.getId());
        jsonObj.put("token", csrfToken);
        out.write(jsonObj.toString());
        return;
    } else {
        //Lagging Response
        try {
            Thread.sleep(2000);
        } catch (InterruptedException ex) {
            Thread.currentThread().interrupt();
        }
        out.write("ERROR: Could not Authenticate");
        return;
    }
}

From source file:com.sslexplorer.language.actions.SelectLanguageAction.java

public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    String referer = DAVUtilities.encodePath(CoreUtil.getRequestReferer(request), false);
    if (referer == null) {
        throw new CoreException(ErrorConstants.ERR_MISSING_REQUEST_PARAMETER, ErrorConstants.CATEGORY_NAME,
                "referer");
    }/* w  w  w. ja v  a 2  s. c  o  m*/
    String localeCode = request.getParameter("locale");
    if (localeCode == null) {
        throw new CoreException(ErrorConstants.ERR_MISSING_REQUEST_PARAMETER, ErrorConstants.CATEGORY_NAME,
                "locale");
    }

    /* Tokenize the locale parameter so we only get the first line. This prevents
     * a header injection exploit as the (not validated) locale gets added as 
     * a cookie.
     */
    StringTokenizer t = new StringTokenizer(localeCode);
    String locale = t.nextToken();

    // Parse the locale code
    String country = "";
    String variant = "";
    String lang = locale;
    int idx = locale.indexOf("_");
    if (idx != -1) {
        country = lang.substring(idx + 1);
        lang = lang.substring(0, idx);
    }
    idx = country.indexOf('_');
    if (idx != -1) {
        variant = country.substring(idx + 1);
        country = country.substring(0, idx);
    }

    // Store the new locale in the session and set a persistant cookie
    Locale l = new Locale(lang, country, variant);
    request.getSession().setAttribute(Globals.LOCALE_KEY, l);
    Cookie cookie = new Cookie(SystemProperties.get("sslexplorer.cookie", "SSLX_SSESHID") + "_LANG",
            locale.toString());
    cookie.setMaxAge(60 * 60 * 24 * 7); // a week
    cookie.setPath("/");
    cookie.setSecure(true);
    response.addCookie(cookie);
    return referer == null ? mapping.findForward("home") : new ActionForward(referer, true);
}

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

private Cookie personUserCertificateLoggedOutCookie() {
    Cookie cookie = new Cookie(SessionManager.getPersonUserCertificateLoggedOutCookieName(this.tenant), "");
    cookie.setPath("/openidconnect");
    cookie.setSecure(true);
    cookie.setHttpOnly(true);/*  ww w  .  j  av  a2s  .  c o m*/
    return cookie;
}

From source file:edu.ucmerced.cas.web.support.CasShibCookieRetrievingCookieGenerator.java

public void addCookie(final HttpServletRequest request, final HttpServletResponse response,
        final String cookieValue) {
    // instantiate a new CookieGenerator upon every request because the
    // cookie name and path are possibly going to be different for each
    // request//  w  ww. jav  a  2s .c  om
    LocalCookieGenerator cookieGenerator = newCookieGeneratorInstance(request);

    if (!StringUtils.hasText(request.getParameter(RememberMeCredentials.REQUEST_PARAMETER_REMEMBER_ME))) {
        cookieGenerator.addCookie(response, cookieValue);
    } else {
        final Cookie cookie = cookieGenerator.createCookie(cookieValue);
        cookie.setMaxAge(this.rememberMeMaxAge);
        if (cookieGenerator.isCookieSecure()) {
            cookie.setSecure(true);
        }
        response.addCookie(cookie);
    }
}

From source file:com.atlassian.jira.security.xsrf.SimpleXsrfTokenGenerator.java

private void addNewCookie(HttpServletRequest httpServletRequest, String token,
        HttpServletResponse httpServletResponse) {
    final Cookie cookie = new Cookie(TOKEN_HTTP_SESSION_KEY, token);
    cookie.setPath(getRequestContext(httpServletRequest));
    cookie.setMaxAge(-1); // expire with the browser exit
    cookie.setSecure(httpServletRequest.isSecure());
    httpServletResponse.addCookie(cookie);
    httpServletRequest.setAttribute(SET_COOKIE_PENDING, token);
}

From source file:au.gov.dto.springframework.security.web.context.CookieSecurityContextRepository.java

private Cookie createExpireAuthenticationCookie(HttpServletRequest request) {
    Cookie removeSessionCookie = new Cookie(authenticationCookieName, "");
    removeSessionCookie.setPath(authenticationCookiePath);
    removeSessionCookie.setMaxAge(0);//from   ww w. java  2s  .c om
    removeSessionCookie.setHttpOnly(true);
    removeSessionCookie.setSecure(request.isSecure());
    return removeSessionCookie;
}

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  w w  w . j a v a  2  s .  c om*/
                cookie.setValue(StringUtils.EMPTY);
                cookie.setSecure(true);
                cookie.setHttpOnly(true);
                cookie.setDomain(allowedDomain.trim());
                response.addCookie(cookie);
            }
        }
    }
}

From source file:org.wso2.carbon.identity.sso.cas.processor.SSOLoginProcessor.java

public Cookie storeTicketGrantingCookie(String sessionId, IdentityRequest req) {
    Cookie ticketGrantingCookie = getTicketGrantingCookie(req);
    if (ticketGrantingCookie == null) {
        ticketGrantingCookie = new Cookie(SSOLoginProcessor.CAS_COOKIE_NAME, sessionId);
    }//  w  w w . j  a  va2  s.  c o m
    ticketGrantingCookie.setPath(CASConfiguration.getBasePath());
    ticketGrantingCookie.setSecure(true);
    return ticketGrantingCookie;
}

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

@SuppressWarnings("unchecked")
@Override//  w  ww . j  a  v  a  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:au.gov.dto.dibp.appointments.security.csrf.CookieBasedCsrfTokenRepository.java

@Override
public void saveToken(CsrfToken token, HttpServletRequest request, HttpServletResponse response) {
    Cookie csrfCookie;
    if (token == null) {
        csrfCookie = new Cookie(CSRF_COOKIE_AND_PARAMETER_NAME, "");
        csrfCookie.setMaxAge(0);/*  w  w w  .  ja v a 2s .c  o  m*/
    } else {
        csrfCookie = new Cookie(token.getParameterName(), token.getToken());
        csrfCookie.setMaxAge(COOKIE_MAX_AGE_SECONDS);
    }
    csrfCookie.setHttpOnly(true);
    csrfCookie.setSecure(request.isSecure());
    response.addCookie(csrfCookie);
}