List of usage examples for javax.servlet.http HttpServletResponse addCookie
public void addCookie(Cookie cookie);
From source file:org.apache.hadoop.security.authentication.server.AuthenticationFilter.java
/** * If the request has a valid authentication token it allows the request to continue to the target resource, * otherwise it triggers an authentication sequence using the configured {@link AuthenticationHandler}. * * @param request the request object.//from w w w . j a v a2 s. c om * @param response the response object. * @param filterChain the filter chain object. * * @throws IOException thrown if an IO error occurred. * @throws ServletException thrown if a processing error occurred. */ @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException { HttpServletRequest httpRequest = (HttpServletRequest) request; HttpServletResponse httpResponse = (HttpServletResponse) response; try { boolean newToken = false; AuthenticationToken token = getToken(httpRequest); if (token == null) { if (LOG.isDebugEnabled()) { LOG.debug(MessageFormat.format("Request {0} triggering authentication", getRequestURL(httpRequest))); } token = authHandler.authenticate(httpRequest, httpResponse); if (token != null && token != AuthenticationToken.ANONYMOUS) { token.setExpires(System.currentTimeMillis() + getValidity() * 1000); } newToken = true; } if (token != null) { if (LOG.isDebugEnabled()) { LOG.debug(MessageFormat.format("Request {0} user {1} authenticated", getRequestURL(httpRequest), token.getUserName())); } final AuthenticationToken authToken = token; httpRequest = new HttpServletRequestWrapper(httpRequest) { @Override public String getAuthType() { return authToken.getType(); } @Override public String getRemoteUser() { return authToken.getUserName(); } @Override public Principal getUserPrincipal() { return (authToken != AuthenticationToken.ANONYMOUS) ? authToken : null; } }; if (newToken && token != AuthenticationToken.ANONYMOUS) { String signedToken = signer.sign(token.toString()); Cookie cookie = createCookie(signedToken); httpResponse.addCookie(cookie); } filterChain.doFilter(httpRequest, httpResponse); } } catch (AuthenticationException ex) { if (!httpResponse.isCommitted()) { Cookie cookie = createCookie(""); cookie.setMaxAge(0); httpResponse.addCookie(cookie); httpResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED, ex.getMessage()); } LOG.warn("Authentication exception: " + ex.getMessage(), ex); } }
From source file:com.tremolosecurity.proxy.SessionManagerImpl.java
@Override public void writeSession(UrlHolder holder, TremoloHttpSession session, HttpServletRequest request, HttpServletResponse response) throws IOException { /*/*from w w w . ja v a2 s . c o m*/ * Enumeration enumer = session.getAttributeNames(); while * (enumer.hasMoreElements()) { String name = (String) * enumer.nextElement(); String value = * session.getAttribute(name).toString(); logger.debug(name + "='" + * value + "'"); } */ ByteArrayOutputStream bos = new ByteArrayOutputStream(); GZIPOutputStream gzip = new GZIPOutputStream(bos); ObjectOutputStream oos = new ObjectOutputStream(gzip); oos.writeObject(session); oos.flush(); oos.close(); byte[] encSession = new byte[0]; try { Cipher cipher = Cipher.getInstance("AES"); cipher.init(Cipher.ENCRYPT_MODE, holder.getConfig().getSecretKey(holder.getApp().getCookieConfig().getKeyAlias())); encSession = cipher.doFinal(bos.toByteArray()); } catch (Exception e) { e.printStackTrace(); } Cookie sessionCookie; sessionCookie = new Cookie(holder.getApp().getCookieConfig().getSessionCookieName(), new String(Base64.encodeBase64(encSession))); // logger.debug("session size : " + // org.apache.directory.shared.ldap.util.Base64.encode(encSession).length); String domain = ProxyTools.getInstance().getCookieDomain(holder.getApp().getCookieConfig(), request); if (domain != null) { sessionCookie.setDomain(domain); } sessionCookie.setPath("/"); sessionCookie.setSecure(false); sessionCookie.setMaxAge(-1); response.addCookie(sessionCookie); }
From source file:com.google.gsa.valve.modules.krb.KerberosAuthenticationProcess.java
/** * Creates the authentication cookie sent back to the caller as a * result of a successful Kerberos authentication process * /*from w w w . ja v a2 s . c om*/ * @param request HTTP request * @param response HTTP response */ public void createCookie(HttpServletRequest request, HttpServletResponse response) { logger.debug("Creating the Kerberos Authn cookie"); //Cookie value String krbCookie = null; try { //Get the Base64-encoded ID for the Cookie String krbIDBase64Encoded = (new UserIDEncoder()).getID(getUsername(), System.currentTimeMillis()); //URL encode the value of the cookie before adding krbCookie = URLEncoder.encode(krbIDBase64Encoded, encoder); if (krbCookie == null) { krbCookie = ""; } } catch (Exception ex) { logger.error("Error when setting the Krb cookie value: " + ex.getMessage(), ex); krbCookie = ""; } // Instantiate authentication cookie with default value gsaKrbAuthCookie = new Cookie(COOKIE_NAME, krbCookie); // Set cookie domain gsaKrbAuthCookie.setDomain(valveConf.getAuthCookieDomain()); // Set cookie path gsaKrbAuthCookie.setPath(valveConf.getAuthCookiePath()); // Set cookie max age gsaKrbAuthCookie.setMaxAge(authMaxAge); // Debug if (logger.isDebugEnabled()) logger.debug("Kerb Auth cookie set"); //add sendCookies support boolean isSessionEnabled = new Boolean(valveConf.getSessionConfig().isSessionEnabled()).booleanValue(); boolean sendCookies = false; if (isSessionEnabled) { sendCookies = new Boolean(valveConf.getSessionConfig().getSendCookies()).booleanValue(); } if ((!isSessionEnabled) || ((isSessionEnabled) && (sendCookies))) { response.addCookie(gsaKrbAuthCookie); } }
From source file:de.kp.ames.web.core.service.ServiceImpl.java
/** * A specific method to enable file download even in a secure (SSL) environment * // w w w . jav a2 s . c o m * @param file * @param request * @param response * @throws IOException */ public void sendFileDownloadResponse(FileUtil file, HttpServletRequest request, HttpServletResponse response) throws IOException { if (file == null) return; String clientPath = request.getParameter("clientpath"); if (clientPath == null) return; /* * Distinguish between secure and non-secure download requests */ if (request.isSecure()) { response.addHeader("Cache-Control", "no-cache"); response.addHeader("Pragma", "no-cache"); response.addHeader("Expires", "-1"); } else { response.addHeader("Cache-Control", "private"); response.addHeader("Pragma", "public"); } /* * Determine user agent */ String ua = request.getHeader("User-Agent").toLowerCase(); boolean isIE = ((ua.indexOf("msie 6.0") != -1) || (ua.indexOf("msie 7.0") != -1)) ? true : false; /* * Encode file name */ String encFileName = URLEncoder.encode(file.getFilename(), "UTF-8"); if (isIE) { response.addHeader("Content-Disposition", "attachment; filename=\"" + encFileName + "\""); response.addHeader("Connection", "close"); response.setContentType("application/force-download; name=\"" + encFileName + "\""); } else { response.addHeader("Content-Disposition", "attachment; filename=\"" + encFileName + "\""); response.setContentType("application/octet-stream; name=\"" + encFileName + "\""); response.setContentLength(file.getLength()); } /* * Signal download ready with cookie */ Cookie cookie = new Cookie("DOWNLOAD_READY", "END"); cookie.setPath(clientPath); response.addCookie(cookie); // finally set http status response.setStatus(HttpServletResponse.SC_OK); OutputStream os = response.getOutputStream(); os.write(file.getFile()); os.close(); }
From source file:com.janrain.backplane2.server.Backplane2Controller.java
@RequestMapping(value = "/authorize", method = { RequestMethod.GET, RequestMethod.POST }) public ModelAndView authorize(HttpServletRequest request, HttpServletResponse response, @CookieValue(value = AUTH_SESSION_COOKIE, required = false) String authSessionCookie, @CookieValue(value = AUTHORIZATION_REQUEST_COOKIE, required = false) String authorizationRequestCookie) throws AuthorizationException { AuthorizationRequest authzRequest = null; String httpMethod = request.getMethod(); String authZdecisionKey = request.getParameter(AUTHZ_DECISION_KEY); if (authZdecisionKey != null) { logger.debug("received valid authZdecisionKey:" + authZdecisionKey); }//w w w . java2 s . co m // not return from /authenticate && not authz decision post if (request.getParameterMap().size() > 0 && StringUtils.isEmpty(authZdecisionKey)) { // incoming authz request authzRequest = parseAuthZrequest(request); } String authenticatedBusOwner = getAuthenticatedBusOwner(request, authSessionCookie); if (null == authenticatedBusOwner) { if (null != authzRequest) { try { logger.info("Persisting authorization request for client: " + authzRequest.get(AuthorizationRequest.Field.CLIENT_ID) + "[" + authzRequest.get(AuthorizationRequest.Field.COOKIE) + "]"); daoFactory.getAuthorizationRequestDAO().persist(authzRequest); response.addCookie(new Cookie(AUTHORIZATION_REQUEST_COOKIE, authzRequest.get(AuthorizationRequest.Field.COOKIE))); } catch (BackplaneServerException e) { throw new AuthorizationException(OAuth2.OAUTH2_AUTHZ_SERVER_ERROR, e.getMessage(), request, e); } } logger.info("Bus owner not authenticated, redirecting to /authenticate"); return new ModelAndView("redirect:https://" + request.getServerName() + "/v2/authenticate"); } if (StringUtils.isEmpty(authZdecisionKey)) { // authorization request if (null == authzRequest) { // return from /authenticate try { logger.debug("bp2.authorization.request cookie = " + authorizationRequestCookie); authzRequest = daoFactory.getAuthorizationRequestDAO().get(authorizationRequestCookie); logger.info("Retrieved authorization request for client:" + authzRequest.get(AuthorizationRequest.Field.CLIENT_ID) + "[" + authzRequest.get(AuthorizationRequest.Field.COOKIE) + "]"); } catch (BackplaneServerException e) { throw new AuthorizationException(OAuth2.OAUTH2_AUTHZ_SERVER_ERROR, e.getMessage(), request, e); } } return processAuthZrequest(authzRequest, authSessionCookie, authenticatedBusOwner); } else { // authZ decision from bus owner, accept only on post if (!"POST".equals(httpMethod)) { throw new InvalidRequestException( "Invalid HTTP method for authorization decision post: " + httpMethod); } return processAuthZdecision(authZdecisionKey, authSessionCookie, authenticatedBusOwner, authorizationRequestCookie, request); } }
From source file:edu.jhu.pha.vospace.oauth.AuthorizationServlet.java
private void handle(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { logger.debug("Handling request for \"" + request.getRequestURL() + "\""); try {//from w w w.j a v a 2s . c om List<String> userLogins = null; if (isShareRequest(request)) { userLogins = MySQLOAuthProvider2.getShareUsers(request.getParameter("share")); if (null == userLogins || userLogins.isEmpty()) { // open to any user TODO check NULL user authorizeRequestToken(request, response, null); return; } // returns not found exception if not found share } if (isOpenIdResponse(request)) { logger.debug("Handle OpenID"); handleOpenidResponse(request, response); } else { // initial login logger.debug("Initiate"); String userName = checkCertificate(request); if (null != userName) { // made X.509 authentication logger.debug("Certificate checked. Username: " + userName); if (!UserHelper.userExists(userName)) { UserHelper.addDefaultUser(userName); } authorizeRequestToken(request, response, userName); } else { // need to do openid logger.debug("OpenID init"); String provider = request.getParameter("provider"); String idLess = getIdentityless(provider); // set cookie for cases when user came directly to authorize from 3rd party application if (null != request.getParameter("oauth_token")) { OauthCookie cookie = new OauthCookie(); cookie.setRequestToken(request.getParameter("oauth_token")); cookie.setCallbackUrl(request.getParameter("oauth_callback")); cookie.setRegion(conf.getString("region")); cookie.setShareId(request.getParameter("share")); response.addCookie(new Cookie(OauthCookie.COOKIE_NAME, cookie.toString())); logger.debug("Created third party app cookie."); } String error = initiateOpenid(request, response, idLess); if (error != null) throw new Oops(error); } } } // for local error-reporting, use a private Exception class, Oops (see below) catch (Oops e) { handleError(request, response, e.getMessage()); } }
From source file:com.enonic.cms.web.portal.services.UserServicesProcessor.java
private void processLogout(SiteContext siteContext, HttpServletRequest request, HttpServletResponse response, ExtendedMap formItems) throws VerticalUserServicesException, RemoteException { final HttpSession session = ServletRequestAccessor.getSession(false); if (session != null) { // Create log entry: User user = securityService.getLoggedInPortalUser(); if (user != null && !user.isAnonymous()) { if (siteContext.isAuthenticationLoggingEnabled()) { logLogout(siteContext, user, request.getRemoteAddr()); }//from w w w . ja v a 2 s . com } else { String message = "User is not logged in."; VerticalUserServicesLogger.warn(message); redirectToErrorPage(request, response, formItems, ERR_USER_NOT_LOGGED_IN); return; } // Remove GUID cookie if present String cookieName = "guid-" + siteContext.getSiteKey(); Cookie cookie = CookieUtil.getCookie(request, cookieName); if (cookie != null) { cookie.setValue(null); response.addCookie(cookie); } removeGuidCookie(response, DeploymentPathResolver.getSiteDeploymentPath(request), siteContext); this.securityService.logoutPortalUser(); this.loginService.removeRememberedLogin(user.getKey()); redirectToPage(request, response, formItems); } }
From source file:com.haulmont.idp.controllers.IdpController.java
@PostMapping(value = "/auth", produces = "application/json; charset=UTF-8") @ResponseBody//from w w w. j a va 2 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.iwethey.forums.web.HeaderInterceptor.java
/** * Load the request attributes with the User object (if authenticated) * and start time for the page for audit purposes. * <p>//from w w w . j a va 2s .c om * @param request The servlet request object. * @param response The servlet response object. * @param handler The request handler processing this request. */ @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { Date now = new Date(); request.setAttribute("now", now); long start = now.getTime(); request.setAttribute("start", new Long(start)); Integer id = (Integer) WebUtils.getSessionAttribute(request, USER_ID_ATTRIBUTE); User user = null; if (id == null) { user = (User) WebUtils.getSessionAttribute(request, USER_ATTRIBUTE); if (user == null) { user = new User("Anonymous"); WebUtils.setSessionAttribute(request, USER_ATTRIBUTE, user); } } else { user = mUserManager.getUserById(id.intValue()); user.setLastPresent(new Date()); mUserManager.saveUserAttributes(user); } request.setAttribute("username", user.getNickname()); request.setAttribute(USER_ATTRIBUTE, user); System.out.println("Local Address = [" + request.getLocalAddr() + "]"); System.out.println("Local Name = [" + request.getLocalName() + "]"); System.out.println("Remote Address = [" + request.getRemoteAddr() + "]"); System.out.println("Remote Host = [" + request.getRemoteHost() + "]"); System.out.println("Remote Port = [" + request.getRemotePort() + "]"); System.out.println("Remote User = [" + request.getRemoteUser() + "]"); System.out.println("Context Path = [" + request.getContextPath() + "]"); System.out.println("===================="); Cookie[] cookies = request.getCookies(); if (cookies != null) { for (int i = 0; i < cookies.length; i++) { Cookie cookie = cookies[i]; System.out.println("Cookie Domain = [" + cookie.getDomain() + "]"); System.out.println("Cookie Name = [" + cookie.getName() + "]"); System.out.println("Cookie Value = [" + cookie.getValue() + "]"); System.out.println("Cookie Expire = [" + cookie.getMaxAge() + "]"); System.out.println("===================="); if ("iwt_cookie".equals(cookie.getName())) { cookie.setMaxAge(1000 * 60 * 60 * 24 * 30 * 6); response.addCookie(cookie); } } } else { System.out.println("No cookies were found in the request"); } Cookie newCookie = new Cookie("iwt_cookie", "harrr2!"); newCookie.setPath(request.getContextPath()); newCookie.setDomain(request.getLocalName()); newCookie.setMaxAge(1000 * 60 * 60 * 24 * 30 * 6); response.addCookie(newCookie); request.setAttribute(HEADER_IMAGE_ATTRIBUTE, "/images/iwethey-lrpd-small.png"); return true; }
From source file:com.google.gsa.valve.modules.noauth.HTTPNoAuthenticationProcess.java
/** * This method simulates the authentication process against a content * source, so that every document is consider here as public. * <p>// www . ja v a2 s . co m * Creates the authentication cookie and always return 200, unless there is * any problem processing the request. * * @param request HTTP request * @param response HTTP response * @param authCookies vector that contains the authentication cookies * @param url the document url * @param creds an array of credentials for all external sources * @param id the default credential id to be retrieved from creds * @return the HTTP error code * @throws HttpException * @throws IOException */ public int authenticate(HttpServletRequest request, HttpServletResponse response, Vector<Cookie> authCookies, String url, Credentials creds, String id) throws HttpException, IOException { Cookie[] cookies = null; // Initialize status code int statusCode = HttpServletResponse.SC_UNAUTHORIZED; // Read cookies cookies = request.getCookies(); // Debug logger.debug("HTTP No authentication start"); // // Launch the authentication process // // Protection try { Cookie extAuthCookie = null; extAuthCookie = new Cookie("gsa_basic_noauth", ""); extAuthCookie.setValue("true"); String authCookieDomain = null; String authCookiePath = null; int authMaxAge = -1; // Cache cookie properties authCookieDomain = (request.getAttribute("authCookieDomain")).toString(); authCookiePath = (request.getAttribute("authCookiePath")).toString(); //authMaxAge try { authMaxAge = Integer.parseInt(valveConf.getAuthMaxAge()); } catch (NumberFormatException nfe) { logger.error( "Configuration error: chack the configuration file as the number set for authMaxAge is not OK:"); } // Set extra cookie parameters extAuthCookie.setDomain(authCookieDomain); extAuthCookie.setPath(authCookiePath); extAuthCookie.setMaxAge(authMaxAge); // Log info if (logger.isDebugEnabled()) logger.debug("Adding gsa_basic_noauth cookie: " + extAuthCookie.getName() + ":" + extAuthCookie.getValue() + ":" + extAuthCookie.getPath() + ":" + extAuthCookie.getDomain() + ":" + extAuthCookie.getSecure()); //add sendCookies support boolean isSessionEnabled = new Boolean(valveConf.getSessionConfig().isSessionEnabled()).booleanValue(); boolean sendCookies = false; if (isSessionEnabled) { sendCookies = new Boolean(valveConf.getSessionConfig().getSendCookies()).booleanValue(); } if ((!isSessionEnabled) || ((isSessionEnabled) && (sendCookies))) { response.addCookie(extAuthCookie); } //add cookie to the array authCookies.add(extAuthCookie); statusCode = HttpServletResponse.SC_OK; } catch (Exception e) { // Log error logger.error("HTTP Basic authentication failure: " + e.getMessage(), e); // Update status code statusCode = HttpServletResponse.SC_UNAUTHORIZED; } // End of the authentication process logger.debug("HTTP No Authentication completed (" + statusCode + ")"); // Return status code return statusCode; }