List of usage examples for javax.servlet.http Cookie setSecure
public void setSecure(boolean flag)
From source file:edu.washington.iam.registry.ws.RelyingPartyController.java
@RequestMapping(value = "/logout/**", method = RequestMethod.GET) public ModelAndView logoutPage(HttpServletRequest request, HttpServletResponse response) { // clear cookies/*from www. ja va2s . c o m*/ Cookie[] cookies = request.getCookies(); if (cookies != null) { for (int i = 0; i < cookies.length; i++) { String ckName = cookies[i].getName(); if (ckName.equals(loginCookie) || ckName.startsWith("_shib")) { log.debug("cookie to clear " + ckName); Cookie c = new Cookie(ckName, "void"); c.setSecure(true); c.setPath("/"); c.setMaxAge(0); response.addCookie(c); } } } /** try { log.debug("redirect to: " + logoutUrl); response.sendRedirect(logoutUrl); } catch (IOException e) { log.error("redirect: " + e); } return emptyMV("configuration error"); **/ String view = "browser"; Device currentDevice = DeviceUtils.getCurrentDevice(request); if (currentDevice != null && currentDevice.isMobile()) view = "mobile"; ModelAndView mv = new ModelAndView(view + "/chooser"); mv.addObject("root", browserRootPath); mv.addObject("vers", request.getServletPath()); mv.addObject("pagetype", "browser/loggedout"); mv.addObject("pathextra", ""); mv.addObject("uwloginpath", standardLoginPath); mv.addObject("googleloginpath", googleLoginPath); mv.addObject("incommonloginpath", incommonLoginPath); return (mv); }
From source file:edu.washington.iam.registry.ws.RelyingPartyController.java
private void sendToLogin(HttpServletRequest request, HttpServletResponse response, String loginPath) { // delete any existing sessions first Cookie[] cookies = request.getCookies(); if (cookies != null) { for (int i = 0; i < cookies.length; i++) { if (cookies[i].getName().startsWith("_shib")) { log.debug("clearing cookie " + cookies[i].getName()); Cookie c = new Cookie(cookies[i].getName(), ""); c.setSecure(true); c.setPath("/"); c.setMaxAge(0);//from w w w .j a v a 2 s. com response.addCookie(c); } } } String rp = ""; if (request.getPathInfo() != null) rp = request.getPathInfo(); String rqs = ""; if (request.getQueryString() != null) rqs = "?" + request.getQueryString(); String red = browserRootPath + request.getServletPath() + loginPath + rp + rqs; log.debug("no user yet: redirect for login to " + red); try { response.sendRedirect(red); } catch (IOException e) { log.error("redirect: " + e); } }
From source file:edu.washington.iam.registry.ws.RelyingPartyController.java
private ModelAndView loginPage(HttpServletRequest request, HttpServletResponse response, int method) { String remoteUser = request.getRemoteUser(); if (remoteUser == null && method == 0) { // social login String idp = (String) request.getAttribute("Shib-Identity-Provider"); String mail = (String) request.getAttribute("mail"); log.info("social login from " + idp + ", email = " + mail); if (idp.equals(googleIdentityProvider)) { remoteUser = mail;//w ww . jav a 2 s.c om } else { log.debug("invalid social login"); return emptyMV("invalid social login"); } } String methodKey = "P"; if (method == 2) methodKey = "2"; String aclass = (String) request.getAttribute("Shib-AuthnContext-Class"); if (aclass != null && aclass.equals(SECURE_LOGIN_CLASS)) methodKey = "2"; log.debug("method = " + method + ", key = " + methodKey); if (remoteUser != null) { if (remoteUser.endsWith("@washington.edu")) { remoteUser = remoteUser.substring(0, remoteUser.lastIndexOf("@washington.edu")); log.info("dropped @washington.edu to get id = " + remoteUser); } if (remoteUser.endsWith("@uw.edu")) { // no longer allow google's @uw to be same as UW login // remoteUser = remoteUser.substring(0, remoteUser.lastIndexOf("@uw.edu")); // log.info("dropped @uw.edu to get id = " + remoteUser); ////return loginChooserMV(session, request, response); // return to login chooser // until we can report some misuse return emptyMV("invalid social login"); } double dbl = Math.random(); long modtime = new Date().getTime(); // milliseconds log.debug("login: ck = ...;" + remoteUser + ";" + dbl + ";" + methodKey + ";" + modtime / 1000); String enc = RPCrypt.encode(Double.toString(modtime) + ";" + remoteUser + ";" + dbl + ";" + methodKey + ";" + modtime / 1000); log.debug("login: enc = " + enc); Cookie c = new Cookie(loginCookie, enc); c.setSecure(true); c.setPath("/"); response.addCookie(c); try { String rp = request.getPathInfo(); int sp = rp.indexOf("/", 2); log.debug("in path = " + rp); String red = browserRootPath + request.getServletPath(); if (sp > 1) red = red + rp.substring(sp); if (request.getQueryString() != null) red = red + "?" + request.getQueryString(); log.debug("logon ok, return to " + red); response.sendRedirect(red); } catch (IOException e) { log.error("redirect: " + e); return emptyMV("redirect error"); } } else { // send login failed message ModelAndView mv = new ModelAndView("browser/nologin"); mv.addObject("root", browserRootPath); mv.addObject("vers", request.getServletPath()); mv.addObject("pageTitle", "login failed"); mv.addObject("myEntityId", myEntityId); return mv; } return emptyMV(); }
From source file:uk.ac.ox.webauth.FilterWorker.java
/** * Try to grab an app token and get the username from there. * @param privateKey The most suitable key to decrypt the token with. *//*from w ww .ja va 2s . co m*/ private void handleAppCookie(WebauthKey privateKey) throws ServletException { if (!cookies.containsKey("webauth_at")) { return; } Cookie webauth_at = cookies.get("webauth_at"); Token app = null; try { app = decrypt(webauth_at.getValue(), "app"); } // if the user has a bad app cookie then return catch (ServletException se) { return; } if (logger.debug()) { debug(app.toString()); } username = app.getString("s"); if (username == null || username.length() < 1) { return; } if (app.getBinary("lt") != null) { app.add("lt", Token.unixTimestampBytes(System.currentTimeMillis())); String encrypted = null; try { encrypted = app.encrypt(privateKey.key()); } catch (GeneralSecurityException gse) { throw new ServletException("Could not encrypt app-token.", gse); } webauth_at.setValue(encrypted); webauth_at.setSecure(true); webauth_at.setMaxAge(-1); webauth_at.setPath("/"); response.addCookie(webauth_at); debug("Setting a new last-used time on app token cookie."); } debug("Found a valid app-token cookie."); }
From source file:edu.washington.iam.registry.ws.RelyingPartyController.java
private RPSession processRequestInfo(HttpServletRequest request, HttpServletResponse response, boolean canLogin) { RPSession session = new RPSession(); session.isAdmin = false;//from w w w . j a v a 2s. c o m session.adminRole = false; session.isUWLogin = false; session.isProxy = false; String reloginPath = null; log.info("RP new session =============== path=" + request.getPathInfo()); session.isMobile = false; Device currentDevice = DeviceUtils.getCurrentDevice(request); if (currentDevice != null) session.isMobile = currentDevice.isMobile(); log.debug("mobile? " + session.isMobile); // see if logged in (browser has login cookie; cert user has cert) int resetAdmin = 1; // on expired or no cookie, reset the 'admin role cookei' Cookie[] cookies = request.getCookies(); if (cookies != null) { for (int i = 0; i < cookies.length; i++) { if (cookies[i].getName().equals(loginCookie)) { log.debug("got cookie " + cookies[i].getName()); String cookieStr = RPCrypt.decode(cookies[i].getValue()); if (cookieStr == null) continue; String[] cookieData = cookieStr.split(";"); if (cookieData.length == 5) { if (cookieData[3].charAt(0) == '2') session.authn2 = true; log.debug("login time = " + cookieData[4]); long cSec = new Long(cookieData[4]); long nSec = new Date().getTime() / 1000; if (cookieData[1].indexOf("@") < 0) session.isUWLogin = true; // klugey way to know UW people session.timeLeft = (cSec + standardLoginSec) - nSec; if (session.timeLeft > 0) { if ((nSec > (cSec + secureLoginSec)) && session.authn2) { log.debug("secure expired"); session.authn2 = false; resetAdmin = 2; } // cookie OK session.remoteUser = cookieData[1]; session.xsrfCode = cookieData[2]; log.debug("login for " + session.remoteUser); if (session.authn2) log.debug("secure login"); if (adminGroup.isMember(session.remoteUser)) { log.debug("is admin"); session.isAdmin = true; } if (resetAdmin == 1) resetAdmin = 0; } else { log.debug("cookie expired for " + cookieData[1]); // remember where they logged in last if (session.isUWLogin) reloginPath = browserRootPath + request.getServletPath() + standardLoginPath; else if (cookieData[1].indexOf("gmail.com") > 0) reloginPath = browserRootPath + request.getServletPath() + googleLoginPath; // let others choose } } } else if (cookies[i].getName().equals(roleCookie) && cookies[i].getValue().equals("a")) { log.debug("got role=admin cookie"); session.adminRole = true; } } } if (resetAdmin > 0) { log.debug("clearing expired admn request"); session.adminRole = false; Cookie c = new Cookie(roleCookie, "x"); c.setSecure(true); c.setPath("/"); response.addCookie(c); } if (session.remoteUser != null) { // ok, is a logged in browser session.viewType = "browser"; session.isBrowser = true; session.rootPath = browserRootPath; } else { // maybe is cert client // use the CN portion of the DN as the client userid X509Certificate[] certs = (X509Certificate[]) request .getAttribute("javax.servlet.request.X509Certificate"); if (certs != null) { session.viewType = "xml"; session.isBrowser = false; session.rootPath = certRootPath; X509Certificate cert = certs[0]; String dn = cert.getSubjectX500Principal().getName(); session.remoteUser = dn.replaceAll(".*CN=", "").replaceAll(",.*", ""); log.info(".. remote user by cert, dn=" + dn + ", cn=" + session.remoteUser); session.altNames = new Vector(); try { Collection altNames = cert.getSubjectAlternativeNames(); if (altNames != null) { for (Iterator i = altNames.iterator(); i.hasNext();) { List item = (List) i.next(); Integer type = (Integer) item.get(0); if (type.intValue() == 2) { String altName = (String) item.get(1); log.info(".. adding altname " + altName); session.altNames.add(altName); } } } else session.altNames.add(session.remoteUser); // rules say cn meaningful only when altnames not present } catch (CertificateParsingException e) { log.info(".. altname parse failed: " + e); } } } /* send missing remoteUser to login */ if (session.remoteUser == null) { if (canLogin) { if (reloginPath != null) { log.debug("no user yet: relogin at " + reloginPath); try { response.sendRedirect(reloginPath); } catch (IOException e) { log.error("redirect: " + e); } } log.debug("no user yet: send to choose"); session.mv = loginChooserMV(session, request, response); return session; } return null; } // only admins can get admin role if (!session.isAdmin) session.adminRole = false; if (session.adminRole && !session.authn2) { // admin needs 2f log.debug("need secure login for admin role"); sendToLogin(request, response, secureLoginPath); } session.servletPath = request.getServletPath(); session.remoteAddr = request.getRemoteAddr(); // etag headers session.ifMatch = getLongHeader(request, "If-Match"); session.ifNoneMatch = getLongHeader(request, "If-None-Match"); log.info("tags: match=" + session.ifMatch + ", nonematch=" + session.ifNoneMatch); log.info("user: " + session.remoteUser); response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate, max_age=1"); response.setHeader("X-UA-Compatible", "IE=7"); log.info("user: " + session.remoteUser); if (session.viewType.equals("browser") && session.isMobile) session.viewType = "mobile"; return session; }
From source file:org.sakaiproject.util.RequestFilter.java
/** * This is called when a request is made to a node that is in the process of closing down * and so we don't want to allow new session to be created. * @param req The servlet request./*from w w w. ja v a 2 s .c om*/ * @param res The servlet response. */ protected void closingRedirect(HttpServletRequest req, HttpServletResponse res) throws IOException { // We should avoid redirecting on non get methods as the body will be lost. if (!"GET".equals(req.getMethod())) { M_log.warn("Non GET request for " + req.getPathInfo()); } // We could check that we aren't in a redirect loop here, but if the load balancer doesn't know that // a node is no longer responding to new sessions it may still be sending it new clients, and so after // a couple of redirects it should hop off this node. String value = getRedirectNode(); // set the cookie Cookie c = new Cookie(cookieName, value); c.setPath("/"); // Delete the cookie c.setMaxAge(0); if (cookieDomain != null) { c.setDomain(cookieDomain); } if (req.isSecure() == true) { c.setSecure(true); } addCookie(res, c); // We want the non-decoded ones so we don't have to re-encode. StringBuilder url = new StringBuilder(req.getRequestURI()); if (req.getQueryString() != null) { url.append("?").append(req.getQueryString()); } res.sendRedirect(url.toString()); }
From source file:org.openmhealth.reference.servlet.Version1.java
/** * Creates an authentication request, authenticates the user and, if * successful, returns the user's credentials. * /*from w ww . ja v a 2 s . c o m*/ * @param username * The username of the user attempting to authenticate. * * @param password * The password of the user attempting to authenticate. * * @param request * The HTTP request object. * * @param response * The HTTP response object. * * @return The authorization token. * * @throws OmhException * There was a problem with the request. This could be any of the * sub-classes of {@link OmhException}. */ @RequestMapping(value = "auth", method = RequestMethod.POST) public @ResponseBody String getAuthentication( @RequestParam(value = PARAM_AUTHENTICATION_USERNAME, required = true) final String username, @RequestParam(value = PARAM_AUTHENTICATION_PASSWORD, required = true) final String password, final HttpServletRequest request, final HttpServletResponse response) throws OmhException { // Create the authentication request from parameters. AuthenticationToken token = handleRequest(request, response, new AuthenticationRequest(username, password)); // Add a cookie for the authentication token. Cookie cookie = new Cookie(PARAM_AUTHENTICATION_AUTH_TOKEN, token.getToken()); // Set the expiration on the cookie. cookie.setMaxAge(new Long((token.getExpires() - System.currentTimeMillis()) / 1000).intValue()); // Build the path without the "auth" part. String requestUri = request.getRequestURI(); cookie.setPath(requestUri.substring(0, requestUri.length() - 5)); // Make sure the cookie is only used with HTTPS. cookie.setSecure(true); // Add the cookie to the response. response.addCookie(cookie); // Return the token. return token.getToken(); }
From source file:io.restassured.module.mockmvc.internal.MockMvcRequestSenderImpl.java
private MockMvcResponse sendRequest(HttpMethod method, String path, Object[] pathParams) { notNull(path, "Path"); if (requestBody != null && !multiParts.isEmpty()) { throw new IllegalStateException( "You cannot specify a request body and a multi-part body in the same request. Perhaps you want to change the body to a multi part?"); }//from w ww . j a v a 2 s . c o m String baseUri; if (isNotBlank(basePath)) { baseUri = mergeAndRemoveDoubleSlash(basePath, path); } else { baseUri = path; } final UriComponentsBuilder uriComponentsBuilder = UriComponentsBuilder.fromUriString(baseUri); if (!queryParams.isEmpty()) { new ParamApplier(queryParams) { @Override protected void applyParam(String paramName, String[] paramValues) { uriComponentsBuilder.queryParam(paramName, paramValues); } }.applyParams(); } String uri = uriComponentsBuilder.build().toUriString(); final MockHttpServletRequestBuilder request; if (multiParts.isEmpty()) { request = MockMvcRequestBuilders.request(method, uri, pathParams); } else if (method != POST) { throw new IllegalArgumentException("Currently multi-part file data uploading only works for " + POST); } else { request = MockMvcRequestBuilders.fileUpload(uri, pathParams); } String requestContentType = findContentType(); if (!params.isEmpty()) { new ParamApplier(params) { @Override protected void applyParam(String paramName, String[] paramValues) { request.param(paramName, paramValues); } }.applyParams(); if (StringUtils.isBlank(requestContentType) && method == POST && !isInMultiPartMode(request)) { setContentTypeToApplicationFormUrlEncoded(request); } } if (!formParams.isEmpty()) { if (method == GET) { throw new IllegalArgumentException("Cannot use form parameters in a GET request"); } new ParamApplier(formParams) { @Override protected void applyParam(String paramName, String[] paramValues) { request.param(paramName, paramValues); } }.applyParams(); boolean isInMultiPartMode = isInMultiPartMode(request); if (StringUtils.isBlank(requestContentType) && !isInMultiPartMode) { setContentTypeToApplicationFormUrlEncoded(request); } } if (!attributes.isEmpty()) { new ParamApplier(attributes) { @Override protected void applyParam(String paramName, String[] paramValues) { request.requestAttr(paramName, paramValues[0]); } }.applyParams(); } if (RestDocsClassPathChecker.isSpringRestDocsInClasspath() && config.getMockMvcConfig().shouldAutomaticallyApplySpringRestDocsMockMvcSupport()) { request.requestAttr(ATTRIBUTE_NAME_URL_TEMPLATE, PathSupport.getPath(uri)); } if (StringUtils.isNotBlank(requestContentType)) { request.contentType(MediaType.parseMediaType(requestContentType)); } if (headers.exist()) { for (Header header : headers) { request.header(header.getName(), header.getValue()); } } if (cookies.exist()) { for (Cookie cookie : cookies) { javax.servlet.http.Cookie servletCookie = new javax.servlet.http.Cookie(cookie.getName(), cookie.getValue()); if (cookie.hasComment()) { servletCookie.setComment(cookie.getComment()); } if (cookie.hasDomain()) { servletCookie.setDomain(cookie.getDomain()); } if (cookie.hasMaxAge()) { servletCookie.setMaxAge(cookie.getMaxAge()); } if (cookie.hasPath()) { servletCookie.setPath(cookie.getPath()); } if (cookie.hasVersion()) { servletCookie.setVersion(cookie.getVersion()); } servletCookie.setSecure(cookie.isSecured()); request.cookie(servletCookie); } } if (!sessionAttributes.isEmpty()) { request.sessionAttrs(sessionAttributes); } if (!multiParts.isEmpty()) { MockMultipartHttpServletRequestBuilder multiPartRequest = (MockMultipartHttpServletRequestBuilder) request; for (MockMvcMultiPart multiPart : multiParts) { MockMultipartFile multipartFile; String fileName = multiPart.getFileName(); String controlName = multiPart.getControlName(); String mimeType = multiPart.getMimeType(); if (multiPart.isByteArray()) { multipartFile = new MockMultipartFile(controlName, fileName, mimeType, (byte[]) multiPart.getContent()); } else if (multiPart.isFile() || multiPart.isInputStream()) { InputStream inputStream; if (multiPart.isFile()) { try { inputStream = new FileInputStream((File) multiPart.getContent()); } catch (FileNotFoundException e) { return SafeExceptionRethrower.safeRethrow(e); } } else { inputStream = (InputStream) multiPart.getContent(); } try { multipartFile = new MockMultipartFile(controlName, fileName, mimeType, inputStream); } catch (IOException e) { return SafeExceptionRethrower.safeRethrow(e); } } else { // String multipartFile = new MockMultipartFile(controlName, fileName, mimeType, ((String) multiPart.getContent()).getBytes()); } multiPartRequest.file(multipartFile); } } if (requestBody != null) { if (requestBody instanceof byte[]) { request.content((byte[]) requestBody); } else if (requestBody instanceof File) { byte[] bytes = toByteArray((File) requestBody); request.content(bytes); } else { request.content(requestBody.toString()); } } logRequestIfApplicable(method, baseUri, path, pathParams); return performRequest(request); }
From source file:net.lightbody.bmp.proxy.jetty.jetty.servlet.AbstractSessionManager.java
public Cookie getSessionCookie(HttpSession session, boolean requestIsSecure) { if (_handler.isUsingCookies()) { Cookie cookie = _handler.getSessionManager().getHttpOnly() ? new HttpOnlyCookie(SessionManager.__SessionCookie, session.getId()) : new Cookie(SessionManager.__SessionCookie, session.getId()); String domain = _handler.getServletContext().getInitParameter(SessionManager.__SessionDomain); String maxAge = _handler.getServletContext().getInitParameter(SessionManager.__MaxAge); String path = _handler.getServletContext().getInitParameter(SessionManager.__SessionPath); if (path == null) path = getCrossContextSessionIDs() ? "/" : _handler.getHttpContext().getContextPath(); if (path == null || path.length() == 0) path = "/"; if (domain != null) cookie.setDomain(domain);//from w w w . j a v a 2 s . c o m if (maxAge != null) cookie.setMaxAge(Integer.parseInt(maxAge)); else cookie.setMaxAge(-1); cookie.setSecure(requestIsSecure && getSecureCookies()); cookie.setPath(path); return cookie; } return null; }
From source file:com.liferay.portal.util.HttpImpl.java
protected Cookie toServletCookie(org.apache.commons.httpclient.Cookie commonsCookie) { Cookie cookie = new Cookie(commonsCookie.getName(), commonsCookie.getValue()); String domain = commonsCookie.getDomain(); if (Validator.isNotNull(domain)) { cookie.setDomain(domain);// w w w . j a va 2 s .c o m } Date expiryDate = commonsCookie.getExpiryDate(); if (expiryDate != null) { int maxAge = (int) (expiryDate.getTime() - System.currentTimeMillis()); maxAge = maxAge / 1000; if (maxAge > -1) { cookie.setMaxAge(maxAge); } } String path = commonsCookie.getPath(); if (Validator.isNotNull(path)) { cookie.setPath(path); } cookie.setSecure(commonsCookie.getSecure()); cookie.setVersion(commonsCookie.getVersion()); return cookie; }