List of usage examples for javax.servlet.http HttpServletResponse addCookie
public void addCookie(Cookie cookie);
From source file:net.sourceforge.subsonic.service.PlayerService.java
/** * Returns the player associated with the given HTTP request. If no such player exists, a new * one is created./*from ww w . j a v a 2s . c o m*/ * * @param request The HTTP request. * @param response The HTTP response. * @param remoteControlEnabled Whether this method should return a remote-controlled player. * @param isStreamRequest Whether the HTTP request is a request for streaming data. * @return The player associated with the given HTTP request. */ public synchronized Player getPlayer(HttpServletRequest request, HttpServletResponse response, boolean remoteControlEnabled, boolean isStreamRequest) { // Find by 'player' request parameter. Player player = getPlayerById(request.getParameter("player")); // Find in session context. if (player == null && remoteControlEnabled) { String playerId = (String) request.getSession().getAttribute("player"); if (playerId != null) { player = getPlayerById(playerId); } } // Find by cookie. String username = securityService.getCurrentUsername(request); if (player == null && remoteControlEnabled) { player = getPlayerById(getPlayerIdFromCookie(request, username)); } // Make sure we're not hijacking the player of another user. if (player != null && player.getUsername() != null && username != null && !player.getUsername().equals(username)) { player = null; } // Look for player with same IP address and user name. if (player == null) { player = getPlayerByIpAddressAndUsername(request.getRemoteAddr(), username); // Don't use this player if it's used by REST API. if (player != null && player.getClientId() != null) { player = null; } } // If no player was found, create it. if (player == null) { player = new Player(); createPlayer(player); // LOG.debug("Created player " + player.getId() + " (remoteControlEnabled: " + remoteControlEnabled + // ", isStreamRequest: " + isStreamRequest + ", username: " + username + // ", ip: " + request.getRemoteAddr() + ")."); } // Update player data. boolean isUpdate = false; if (username != null && player.getUsername() == null) { player.setUsername(username); isUpdate = true; } if (player.getIpAddress() == null || isStreamRequest || (!isPlayerConnected(player) && player.isDynamicIp() && !request.getRemoteAddr().equals(player.getIpAddress()))) { player.setIpAddress(request.getRemoteAddr()); isUpdate = true; } String userAgent = request.getHeader("user-agent"); if (isStreamRequest) { player.setType(userAgent); player.setLastSeen(new Date()); isUpdate = true; } if (isUpdate) { updatePlayer(player); } // Set cookie in response. if (response != null) { String cookieName = COOKIE_NAME + "-" + StringUtil.utf8HexEncode(username); Cookie cookie = new Cookie(cookieName, player.getId()); cookie.setMaxAge(COOKIE_EXPIRY); String path = request.getContextPath(); if (StringUtils.isEmpty(path)) { path = "/"; } cookie.setPath(path); response.addCookie(cookie); } // Save player in session context. if (remoteControlEnabled) { request.getSession().setAttribute("player", player.getId()); } return player; }
From source file:net.lightbody.bmp.proxy.jetty.servlet.Dump.java
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setAttribute("Dump", this); request.setCharacterEncoding("ISO_8859_1"); getServletContext().setAttribute("Dump", this); String info = request.getPathInfo(); if (info != null && info.endsWith("Exception")) { try {/*from w w w. j ava 2 s. c o m*/ throw (Throwable) (Loader.loadClass(this.getClass(), info.substring(1)).newInstance()); } catch (Throwable th) { throw new ServletException(th); } } String redirect = request.getParameter("redirect"); if (redirect != null && redirect.length() > 0) { response.getOutputStream().println("THIS SHOULD NOT BE SEEN!"); response.sendRedirect(redirect); response.getOutputStream().println("THIS SHOULD NOT BE SEEN!"); return; } String error = request.getParameter("error"); if (error != null && error.length() > 0) { response.getOutputStream().println("THIS SHOULD NOT BE SEEN!"); response.sendError(Integer.parseInt(error)); response.getOutputStream().println("THIS SHOULD NOT BE SEEN!"); return; } String length = request.getParameter("length"); if (length != null && length.length() > 0) { response.setContentLength(Integer.parseInt(length)); } String buffer = request.getParameter("buffer"); if (buffer != null && buffer.length() > 0) response.setBufferSize(Integer.parseInt(buffer)); request.setCharacterEncoding("UTF-8"); response.setContentType("text/html"); if (info != null && info.indexOf("Locale/") >= 0) { try { String locale_name = info.substring(info.indexOf("Locale/") + 7); Field f = java.util.Locale.class.getField(locale_name); response.setLocale((Locale) f.get(null)); } catch (Exception e) { LogSupport.ignore(log, e); response.setLocale(Locale.getDefault()); } } String cn = request.getParameter("cookie"); String cv = request.getParameter("value"); String v = request.getParameter("version"); if (cn != null && cv != null) { Cookie cookie = new Cookie(cn, cv); cookie.setComment("Cookie from dump servlet"); if (v != null) { cookie.setMaxAge(300); cookie.setPath("/"); cookie.setVersion(Integer.parseInt(v)); } response.addCookie(cookie); } String pi = request.getPathInfo(); if (pi != null && pi.startsWith("/ex")) { OutputStream out = response.getOutputStream(); out.write("</H1>This text should be reset</H1>".getBytes()); if ("/ex0".equals(pi)) throw new ServletException("test ex0", new Throwable()); if ("/ex1".equals(pi)) throw new IOException("test ex1"); if ("/ex2".equals(pi)) throw new UnavailableException("test ex2"); if ("/ex3".equals(pi)) throw new HttpException(501); } PrintWriter pout = response.getWriter(); Page page = null; try { page = new Page(); page.title("Dump Servlet"); page.add(new Heading(1, "Dump Servlet")); Table table = new Table(0).cellPadding(0).cellSpacing(0); page.add(table); table.newRow(); table.addHeading("getMethod: ").cell().right(); table.addCell("" + request.getMethod()); table.newRow(); table.addHeading("getContentLength: ").cell().right(); table.addCell(Integer.toString(request.getContentLength())); table.newRow(); table.addHeading("getContentType: ").cell().right(); table.addCell("" + request.getContentType()); table.newRow(); table.addHeading("getCharacterEncoding: ").cell().right(); table.addCell("" + request.getCharacterEncoding()); table.newRow(); table.addHeading("getRequestURI: ").cell().right(); table.addCell("" + request.getRequestURI()); table.newRow(); table.addHeading("getRequestURL: ").cell().right(); table.addCell("" + request.getRequestURL()); table.newRow(); table.addHeading("getContextPath: ").cell().right(); table.addCell("" + request.getContextPath()); table.newRow(); table.addHeading("getServletPath: ").cell().right(); table.addCell("" + request.getServletPath()); table.newRow(); table.addHeading("getPathInfo: ").cell().right(); table.addCell("" + request.getPathInfo()); table.newRow(); table.addHeading("getPathTranslated: ").cell().right(); table.addCell("" + request.getPathTranslated()); table.newRow(); table.addHeading("getQueryString: ").cell().right(); table.addCell("" + request.getQueryString()); table.newRow(); table.addHeading("getProtocol: ").cell().right(); table.addCell("" + request.getProtocol()); table.newRow(); table.addHeading("getScheme: ").cell().right(); table.addCell("" + request.getScheme()); table.newRow(); table.addHeading("getServerName: ").cell().right(); table.addCell("" + request.getServerName()); table.newRow(); table.addHeading("getServerPort: ").cell().right(); table.addCell("" + Integer.toString(request.getServerPort())); table.newRow(); table.addHeading("getLocalName: ").cell().right(); table.addCell("" + request.getLocalName()); table.newRow(); table.addHeading("getLocalAddr: ").cell().right(); table.addCell("" + request.getLocalAddr()); table.newRow(); table.addHeading("getLocalPort: ").cell().right(); table.addCell("" + Integer.toString(request.getLocalPort())); table.newRow(); table.addHeading("getRemoteUser: ").cell().right(); table.addCell("" + request.getRemoteUser()); table.newRow(); table.addHeading("getRemoteAddr: ").cell().right(); table.addCell("" + request.getRemoteAddr()); table.newRow(); table.addHeading("getRemoteHost: ").cell().right(); table.addCell("" + request.getRemoteHost()); table.newRow(); table.addHeading("getRemotePort: ").cell().right(); table.addCell("" + request.getRemotePort()); table.newRow(); table.addHeading("getRequestedSessionId: ").cell().right(); table.addCell("" + request.getRequestedSessionId()); table.newRow(); table.addHeading("isSecure(): ").cell().right(); table.addCell("" + request.isSecure()); table.newRow(); table.addHeading("isUserInRole(admin): ").cell().right(); table.addCell("" + request.isUserInRole("admin")); table.newRow(); table.addHeading("getLocale: ").cell().right(); table.addCell("" + request.getLocale()); Enumeration locales = request.getLocales(); while (locales.hasMoreElements()) { table.newRow(); table.addHeading("getLocales: ").cell().right(); table.addCell(locales.nextElement()); } table.newRow(); table.newHeading().cell().nest(new Font(2, true)).add("<BR>Other HTTP Headers") .attribute("COLSPAN", "2").left(); Enumeration h = request.getHeaderNames(); String name; while (h.hasMoreElements()) { name = (String) h.nextElement(); Enumeration h2 = request.getHeaders(name); while (h2.hasMoreElements()) { String hv = (String) h2.nextElement(); table.newRow(); table.addHeading(name + ": ").cell().right(); table.addCell(hv); } } table.newRow(); table.newHeading().cell().nest(new Font(2, true)).add("<BR>Request Parameters") .attribute("COLSPAN", "2").left(); h = request.getParameterNames(); while (h.hasMoreElements()) { name = (String) h.nextElement(); table.newRow(); table.addHeading(name + ": ").cell().right(); table.addCell(request.getParameter(name)); String[] values = request.getParameterValues(name); if (values == null) { table.newRow(); table.addHeading(name + " Values: ").cell().right(); table.addCell("NULL!!!!!!!!!"); } else if (values.length > 1) { for (int i = 0; i < values.length; i++) { table.newRow(); table.addHeading(name + "[" + i + "]: ").cell().right(); table.addCell(values[i]); } } } table.newRow(); table.newHeading().cell().nest(new Font(2, true)).add("<BR>Cookies").attribute("COLSPAN", "2").left(); Cookie[] cookies = request.getCookies(); for (int i = 0; cookies != null && i < cookies.length; i++) { Cookie cookie = cookies[i]; table.newRow(); table.addHeading(cookie.getName() + ": ").cell().attribute("VALIGN", "TOP").right(); table.addCell(cookie.getValue()); } /* ------------------------------------------------------------ */ table.newRow(); table.newHeading().cell().nest(new Font(2, true)).add("<BR>Request Attributes") .attribute("COLSPAN", "2").left(); Enumeration a = request.getAttributeNames(); while (a.hasMoreElements()) { name = (String) a.nextElement(); table.newRow(); table.addHeading(name + ": ").cell().attribute("VALIGN", "TOP").right(); table.addCell("<pre>" + toString(request.getAttribute(name)) + "</pre>"); } /* ------------------------------------------------------------ */ table.newRow(); table.newHeading().cell().nest(new Font(2, true)).add("<BR>Servlet InitParameters") .attribute("COLSPAN", "2").left(); a = getInitParameterNames(); while (a.hasMoreElements()) { name = (String) a.nextElement(); table.newRow(); table.addHeading(name + ": ").cell().attribute("VALIGN", "TOP").right(); table.addCell("<pre>" + toString(getInitParameter(name)) + "</pre>"); } table.newRow(); table.newHeading().cell().nest(new Font(2, true)).add("<BR>Context InitParameters") .attribute("COLSPAN", "2").left(); a = getServletContext().getInitParameterNames(); while (a.hasMoreElements()) { name = (String) a.nextElement(); table.newRow(); table.addHeading(name + ": ").cell().attribute("VALIGN", "TOP").right(); table.addCell("<pre>" + toString(getServletContext().getInitParameter(name)) + "</pre>"); } table.newRow(); table.newHeading().cell().nest(new Font(2, true)).add("<BR>Context Attributes") .attribute("COLSPAN", "2").left(); a = getServletContext().getAttributeNames(); while (a.hasMoreElements()) { name = (String) a.nextElement(); table.newRow(); table.addHeading(name + ": ").cell().attribute("VALIGN", "TOP").right(); table.addCell("<pre>" + toString(getServletContext().getAttribute(name)) + "</pre>"); } if (request.getContentType() != null && request.getContentType().startsWith("multipart/form-data") && request.getContentLength() < 1000000) { MultiPartRequest multi = new MultiPartRequest(request); String[] parts = multi.getPartNames(); table.newRow(); table.newHeading().cell().nest(new Font(2, true)).add("<BR>Multi-part content") .attribute("COLSPAN", "2").left(); for (int p = 0; p < parts.length; p++) { name = parts[p]; table.newRow(); table.addHeading(name + ": ").cell().attribute("VALIGN", "TOP").right(); table.addCell("<pre>" + multi.getString(parts[p]) + "</pre>"); } } String res = request.getParameter("resource"); if (res != null && res.length() > 0) { table.newRow(); table.newHeading().cell().nest(new Font(2, true)).add("<BR>Get Resource: " + res) .attribute("COLSPAN", "2").left(); table.newRow(); table.addHeading("this.getClass(): ").cell().right(); table.addCell("" + this.getClass().getResource(res)); table.newRow(); table.addHeading("this.getClass().getClassLoader(): ").cell().right(); table.addCell("" + this.getClass().getClassLoader().getResource(res)); table.newRow(); table.addHeading("Thread.currentThread().getContextClassLoader(): ").cell().right(); table.addCell("" + Thread.currentThread().getContextClassLoader().getResource(res)); table.newRow(); table.addHeading("getServletContext(): ").cell().right(); try { table.addCell("" + getServletContext().getResource(res)); } catch (Exception e) { table.addCell("" + e); } } /* ------------------------------------------------------------ */ page.add(Break.para); page.add(new Heading(1, "Request Wrappers")); ServletRequest rw = request; int w = 0; while (rw != null) { page.add((w++) + ": " + rw.getClass().getName() + "<br/>"); if (rw instanceof HttpServletRequestWrapper) rw = ((HttpServletRequestWrapper) rw).getRequest(); else if (rw instanceof ServletRequestWrapper) rw = ((ServletRequestWrapper) rw).getRequest(); else rw = null; } page.add(Break.para); page.add(new Heading(1, "International Characters")); page.add("Directly encoced: Drst<br/>"); page.add("HTML reference: Dürst<br/>"); page.add("Decimal (252) 8859-1: Dürst<br/>"); page.add("Hex (xFC) 8859-1: Dürst<br/>"); page.add( "Javascript unicode (00FC) : <script language='javascript'>document.write(\"D\u00FCrst\");</script><br/>"); page.add(Break.para); page.add(new Heading(1, "Form to generate GET content")); TableForm tf = new TableForm(response.encodeURL(getURI(request))); tf.method("GET"); tf.addTextField("TextField", "TextField", 20, "value"); tf.addButton("Action", "Submit"); page.add(tf); page.add(Break.para); page.add(new Heading(1, "Form to generate POST content")); tf = new TableForm(response.encodeURL(getURI(request))); tf.method("POST"); tf.addTextField("TextField", "TextField", 20, "value"); Select select = tf.addSelect("Select", "Select", true, 3); select.add("ValueA"); select.add("ValueB1,ValueB2"); select.add("ValueC"); tf.addButton("Action", "Submit"); page.add(tf); page.add(new Heading(1, "Form to upload content")); tf = new TableForm(response.encodeURL(getURI(request))); tf.method("POST"); tf.attribute("enctype", "multipart/form-data"); tf.addFileField("file", "file"); tf.addButton("Upload", "Upload"); page.add(tf); page.add(new Heading(1, "Form to get Resource")); tf = new TableForm(response.encodeURL(getURI(request))); tf.method("POST"); tf.addTextField("resource", "resource", 20, ""); tf.addButton("Action", "getResource"); page.add(tf); } catch (Exception e) { log.warn(LogSupport.EXCEPTION, e); } page.write(pout); String data = request.getParameter("data"); if (data != null && data.length() > 0) { int d = Integer.parseInt(data); while (d > 0) { pout.println("1234567890123456789012345678901234567890123456789\n"); d = d - 50; } } pout.close(); if (pi != null) { if ("/ex4".equals(pi)) throw new ServletException("test ex4", new Throwable()); if ("/ex5".equals(pi)) throw new IOException("test ex5"); if ("/ex6".equals(pi)) throw new UnavailableException("test ex6"); if ("/ex7".equals(pi)) throw new HttpException(501); } request.getInputStream().close(); }
From source file:com.google.gsa.valve.modules.ldap.LDAPUniqueCreds.java
/** * This is the main method that does the LDAP authentication using user's * credential in the format of username and password. It creates a * connection with the user credentials and reads his/her own information. * It does not read any other LDAP attribute out of the user entry. * <p>/* w w w .ja va 2 s . co m*/ * If the LDAP authentication result is OK, it creates an * authentication cookie. Anyway, the HTTP response code is returned in this * method to inform the caller on the status. * * @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 { logger.debug("LDAP Unique Credentials Start"); Cookie[] cookies = null; // Initialize status code int statusCode = HttpServletResponse.SC_UNAUTHORIZED; // Read cookies cookies = request.getCookies(); //First read the u/p the credentails store, in this case using the same as the root login logger.debug("LDAPUniqueCreds: trying to get creds from repository ID: " + id); Credential cred = null; try { cred = creds.getCredential(id); } catch (NullPointerException npe) { logger.error("NPE while reading credentials of ID: " + id); } if (cred == null) { cred = creds.getCredential("root"); if (cred != null) { logger.info("LDAPUniqueCreds: credential ID used is \"root\""); } else { logger.error("LDAPUniqueCreds: No credentials available for " + id); } } 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:"); } //If the required cookie was not found need to authenticate. logger.debug("Authenticating"); try { //read values from config file (if any) readLDAPParameters(id); //Check if the LDAP credentials are OK logger.debug("Base user is: " + ldapBaseuser); Ldap ldapconn = new Ldap(ldapHost, cred.getUsername(), cred.getPassword(), ldapBaseuser, ldapDomain, rdnAttr); try { logger.debug("Connection to LDAP"); DirContext ctx = ldapconn.openConnection(); if (ctx == null) { //Just send a comment logger.debug("The user(" + cred.getUsername() + ")/password doesn't match"); ldapconn.closeConnection(ctx); return (HttpServletResponse.SC_UNAUTHORIZED); } logger.debug("User properly authenticated against the LDAP"); //Close the connection ldapconn.closeConnection(ctx); } catch (Exception ex) { logger.error("LDAP connection problem during user access: " + ex.getMessage(), ex); return (HttpServletResponse.SC_UNAUTHORIZED); } finally { } Cookie extAuthCookie = null; extAuthCookie = settingCookie(); //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); //This would be set to OK or 401 in a real AuthN module statusCode = HttpServletResponse.SC_OK; } catch (Exception e) { // Log error logger.error("Sample authentication failure: " + e.getMessage(), e); // Update status code statusCode = HttpServletResponse.SC_UNAUTHORIZED; } // Debug logger.debug("Sample Authentication completed (" + statusCode + ")"); // Return status code return statusCode; }
From source file:org.guanxi.idp.service.AuthHandler.java
/** * Looks for an existing GuanxiPrincipal referenced by a request cookie. When a cookie is created after * a successful authentication at the IdP, either via the login page or an application cookie handler, * the corresponding GuanxiPrincipal is stored in the servlet context against the cookie value. * The new GuanxiPrincipal that is created after successful authentication is stored in the servlet * context under GuanxiPrincipal.id//from w w w .jav a2s .c o m * * @param request Standard HttpServletRequest * @param response Standard HttpServletResponse * @param object handler * @return true * @throws Exception if an error occurs */ public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object object) throws Exception { request.setCharacterEncoding("UTF-8"); String missingParams = checkRequestParameters(request); if (missingParams != null) { logger.info("Missing param(s) : " + missingParams); request.setAttribute("message", messageSource.getMessage("missing.param", new Object[] { missingParams }, request.getLocale())); request.getRequestDispatcher(errorPage).forward(request, response); return false; } IdpDocument.Idp idpConfig = (IdpDocument.Idp) servletContext.getAttribute(Guanxi.CONTEXT_ATTR_IDP_CONFIG); boolean spSupported = false; EntityFarm farm = (EntityFarm) servletContext.getAttribute(Guanxi.CONTEXT_ATTR_IDP_ENTITY_FARM); EntityManager manager = farm.getEntityManagerForID(request.getParameter(spIDRequestParam)); if (manager != null) { SPMetadata metadata = (SPMetadata) manager.getMetadata(request.getParameter(spIDRequestParam)); // Apply the trust rules to the SP if (metadata != null) { if (manager.getTrustEngine().trustEntity(metadata, request.getParameter("shire"))) { spSupported = true; } else { logger.error("Trust failure for " + request.getParameter(spIDRequestParam) + " --> " + request.getParameter("shire")); } } else { logger.error("No Metadata Manager found for " + request.getParameter(spIDRequestParam)); } } else { logger.error("No Metadata Manager"); } // Check the locally registered SPs if (!spSupported) { ServiceProvider[] spList = idpConfig.getServiceProviderArray(); for (int c = 0; c < spList.length; c++) { if (spList[c].getName().equals(request.getParameter(spIDRequestParam))) { // If it's in here, we trust it explicitly spSupported = true; } } } // Did we find the service provider? if (!spSupported) { logger.error( "Service Provider providerId " + request.getParameter(spIDRequestParam) + " not supported"); request.setAttribute("message", messageSource.getMessage("sp.not.supported", new Object[] { request.getParameter(spIDRequestParam) }, request.getLocale())); request.getRequestDispatcher(errorPage).forward(request, response); return false; } // Look for our cookie. This is after any application cookie handler has authenticated the user String cookieName = getCookieName(); Cookie[] cookies = request.getCookies(); if (cookies != null) { for (int c = 0; c < cookies.length; c++) { if (cookies[c].getName().equals(cookieName)) { // Retrieve the principal from the servlet context if (servletContext.getAttribute(cookies[c].getValue()) == null) { // Out of date cookie value, so remove the cookie cookies[c].setMaxAge(0); response.addCookie(cookies[c]); } else { // Found the principal from a previously established authentication request.setAttribute(Guanxi.REQUEST_ATTR_IDP_PRINCIPAL, (GuanxiPrincipal) servletContext.getAttribute(cookies[c].getValue())); return true; } } } } // Are we getting an authentication request from the login page? if (request.getParameter("guanxi:mode") != null) { if (request.getParameter("guanxi:mode").equalsIgnoreCase("authenticate")) { // Get a new GuanxiPrincipal... GuanxiPrincipal principal = gxPrincipalFactory.createNewGuanxiPrincipal(request); if (authenticator.authenticate(principal, request.getParameter("userid"), request.getParameter("password"))) { // ...associate it with a login name... if (principal.getName() == null) { //The login name from the authenticator page principal.setName(request.getParameter("userid")); } // ...store it in the request for the SSO to use... request.setAttribute(Guanxi.REQUEST_ATTR_IDP_PRINCIPAL, principal); // ...and store it in application scope for the rest of the profile to use servletContext.setAttribute(principal.getUniqueId(), principal); // Get a new cookie ready to reference the principal in the servlet context Cookie cookie = new Cookie(getCookieName(), principal.getUniqueId()); cookie.setDomain((String) servletContext.getAttribute(Guanxi.CONTEXT_ATTR_IDP_COOKIE_DOMAIN)); cookie.setPath(idpConfig.getCookie().getPath()); if (((Integer) (servletContext.getAttribute(Guanxi.CONTEXT_ATTR_IDP_COOKIE_AGE))) .intValue() != -1) cookie.setMaxAge( ((Integer) (servletContext.getAttribute(Guanxi.CONTEXT_ATTR_IDP_COOKIE_AGE))) .intValue()); response.addCookie(cookie); return true; } // if (authenticator.authenticate... else { logger.error("Authentication error : " + authenticator.getErrorMessage()); request.setAttribute("message", messageSource.getMessage("authentication.error", null, request.getLocale())); request.getRequestDispatcher(errorPage).forward(request, response); return false; } } } // No embedded cookie authentication or local auth, so show the login page String authPage = null; AuthPage[] authPages = idpConfig.getAuthenticatorPages().getAuthPageArray(); for (int c = 0; c < authPages.length; c++) { // We'll use the default auth page if none is specified for this service provider if (authPages[c].getProviderId().equals(Guanxi.DEFAULT_AUTH_PAGE_MARKER)) { authPage = authPages[c].getUrl(); } // Customised auth page for this service provider if (authPages[c].getProviderId().equals(request.getParameter(spIDRequestParam))) { authPage = authPages[c].getUrl(); } } addRequiredParamsAsPrefixedAttributes(request); request.getRequestDispatcher(authPage).forward(request, response); return false; }
From source file:de.tu_dortmund.ub.api.paia.auth.PaiaAuthEndpoint.java
/** * PAIAauth services: Prfe jeweils die scopes und liefere die Daten */// w w w. ja v a2s . c o m private void provideService(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, String service, String access_token, String requestBody, String format, String language, String redirect_url) throws IOException { ObjectMapper mapper = new ObjectMapper(); switch (service) { case "login": { if (Lookup.lookupAll(AuthorizationInterface.class).size() > 0) { AuthorizationInterface authorizationInterface = Lookup.lookup(AuthorizationInterface.class); // init Authorization Service authorizationInterface.init(this.config); // if access_token not equals "" >> delete token + new login if (!access_token.equals("")) { // AuthorizationInterface.revokeToken() try { boolean isRevoked = authorizationInterface.revokeToken(access_token); } catch (AuthorizationException e) { // TODO correct error handling this.logger.error(HttpServletResponse.SC_UNAUTHORIZED + "!"); } // delete cookie Cookie cookie = new Cookie("PaiaService", null); if (this.config.getProperty("service.cookie.domain") != null && !this.config.getProperty("service.cookie.domain").equals("")) { cookie.setDomain(this.config.getProperty("service.cookie.domain")); } cookie.setMaxAge(0); cookie.setPath("/"); httpServletResponse.addCookie(cookie); // cleanup variable access_token = ""; } // analyse on request data LoginRequest loginRequest = null; try { loginRequest = mapper.readValue(requestBody, LoginRequest.class); if (httpServletRequest.getParameter("redirect_url") != null && !httpServletRequest.getParameter("redirect_url").equals("")) { redirect_url = httpServletRequest.getParameter("redirect_url"); } } catch (Exception e) { if (requestBody != null && !requestBody.equals("")) { String[] params = requestBody.split("&"); if (params.length > 1) { loginRequest = new LoginRequest(); for (String param : params) { if (param.startsWith("grant_type")) { loginRequest.setGrant_type(param.split("=")[1]); } else if (param.startsWith("username")) { loginRequest.setUsername(param.split("=")[1]); } else if (param.startsWith("password")) { loginRequest.setPassword(param.split("=")[1]); } else if (param.startsWith("scope")) { loginRequest.setScope(param.split("=")[1]); } else if (param.startsWith("format")) { format = param.split("=")[1]; this.logger.info("format = " + format); } else if (param.startsWith("redirect_url")) { redirect_url = URLDecoder.decode(param.split("=")[1], "UTF-8"); this.logger.info("redirect_url = " + redirect_url); } else { // Tu nix } } } } else if (httpServletRequest.getParameter("grant_type") != null && !httpServletRequest.getParameter("grant_type").equals("") && httpServletRequest.getParameter("username") != null && !httpServletRequest.getParameter("username").equals("") && httpServletRequest.getParameter("password") != null && !httpServletRequest.getParameter("password").equals("")) { loginRequest = new LoginRequest(); loginRequest.setGrant_type(httpServletRequest.getParameter("grant_type")); loginRequest.setUsername(httpServletRequest.getParameter("username")); loginRequest.setPassword(httpServletRequest.getParameter("password")); if (httpServletRequest.getParameter("scope") != null && !httpServletRequest.getParameter("scope").equals("")) { loginRequest.setScope(httpServletRequest.getParameter("scope")); } if (httpServletRequest.getParameter("redirect_url") != null && !httpServletRequest.getParameter("redirect_url").equals("")) { redirect_url = httpServletRequest.getParameter("redirect_url"); } } else { loginRequest = null; } } // do login if (loginRequest != null && loginRequest.getUsername() != null && loginRequest.getPassword() != null && loginRequest.getGrant_type() != null && loginRequest.getGrant_type().equals("password")) { String scope = "read_patron read_fees read_items write_items"; // TODO config-properties if (loginRequest.getScope() != null && !loginRequest.getScope().equals("")) { scope = loginRequest.getScope(); } // AuthorizationInterface.getToken() String responseJson = ""; try { responseJson = authorizationInterface.getToken(scope, loginRequest.getUsername(), loginRequest.getPassword()); } catch (AuthorizationException e) { // TODO correct error handling this.logger.error(HttpServletResponse.SC_UNAUTHORIZED + "!"); } if (!responseJson.equals("")) { LoginResponse loginResponse = mapper.readValue(responseJson, LoginResponse.class); // anpassen des loginResponse loginResponse.setRefresh_token(null); loginResponse.setRefresh_expires_in(null); loginResponse.setPatron(loginRequest.getUsername()); httpServletResponse.setHeader("Access-Control-Allow-Origin", this.config.getProperty("Access-Control-Allow-Origin")); httpServletResponse.setHeader("Cache-Control", this.config.getProperty("Cache-Control")); httpServletResponse.setStatus(HttpServletResponse.SC_OK); // add cookie StringWriter stringWriter = new StringWriter(); mapper.writeValue(stringWriter, loginResponse); Cookie cookie = new Cookie("PaiaService", URLEncoder.encode(stringWriter.toString(), "UTF-8")); if (this.config.getProperty("service.cookie.domain") != null && !this.config.getProperty("service.cookie.domain").equals("")) { cookie.setDomain(this.config.getProperty("service.cookie.domain")); } cookie.setMaxAge(-1); cookie.setPath("/"); httpServletResponse.addCookie(cookie); // extent redirect_url this.logger.info("redirect_url: " + redirect_url); if (redirect_url.startsWith(this.config.getProperty("service.base_url") + "/core")) { if (redirect_url.endsWith("core/")) { redirect_url += loginResponse.getPatron(); } else if (redirect_url.endsWith("core")) { redirect_url += "/" + loginResponse.getPatron(); } else if (redirect_url.contains("/patronid/")) { redirect_url = redirect_url.replaceAll("/patronid/", "/" + loginResponse.getPatron() + "/"); } else { // nix } } this.logger.info("redirect_url: " + redirect_url); // XML-Ausgabe mit JAXB if (format.equals("xml")) { try { JAXBContext context = JAXBContext.newInstance(LoginResponse.class); Marshaller m = context.createMarshaller(); m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); // Write to HttpResponse httpServletResponse.setContentType("application/xml;charset=UTF-8"); m.marshal(loginResponse, httpServletResponse.getWriter()); } catch (JAXBException e) { this.logger.error(e.getMessage(), e.getCause()); httpServletResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Internal Server Error: Error while rendering the results."); } } // JSON-Ausgabe mit Jackson if (format.equals("json")) { httpServletResponse.setContentType("application/json;charset=UTF-8"); mapper.writeValue(httpServletResponse.getWriter(), loginResponse); } // html >> redirect if (format.equals("html")) { // if QueryString contains redirect_url and value of it contains /paia/core/ >> expand URL with username if (redirect_url.contains("/paia/core/")) { // TODO redirect_url += loginResponse.getPatron(); } this.logger.info("redirect_url = " + redirect_url); httpServletResponse.sendRedirect(redirect_url); } } else { // Error handling mit suppress_response_codes=true if (httpServletRequest.getParameter("suppress_response_codes") != null) { httpServletResponse.setStatus(HttpServletResponse.SC_OK); } // Error handling mit suppress_response_codes=false (=default) else { httpServletResponse.setStatus(HttpServletResponse.SC_FORBIDDEN); } // Json fr Response body RequestError requestError = new RequestError(); requestError.setError(this.config .getProperty("error." + Integer.toString(HttpServletResponse.SC_FORBIDDEN) + ".2")); requestError.setCode(HttpServletResponse.SC_FORBIDDEN); requestError.setDescription(this.config.getProperty( "error." + Integer.toString(HttpServletResponse.SC_FORBIDDEN) + ".2.description")); requestError.setErrorUri(this.config.getProperty( "error." + Integer.toString(HttpServletResponse.SC_FORBIDDEN) + ".2.uri")); this.sendRequestError(httpServletResponse, requestError, format, language, redirect_url); } } // else Baue HTML-Seite mit login-Formular mittels XSLT else { httpServletResponse.setHeader("WWW-Authentificate", "Bearer"); httpServletResponse.setHeader("WWW-Authentificate", "Bearer realm=\"PAIA auth\""); httpServletResponse.setContentType("application/json"); httpServletResponse.setHeader("Access-Control-Allow-Origin", config.getProperty("Access-Control-Allow-Origin")); httpServletResponse.setHeader("Cache-Control", config.getProperty("Cache-Control")); // Error handling mit suppress_response_codes=true if (httpServletRequest.getParameter("suppress_response_codes") != null) { httpServletResponse.setStatus(HttpServletResponse.SC_OK); } // Error handling mit suppress_response_codes=false (=default) else { httpServletResponse.setStatus(HttpServletResponse.SC_FORBIDDEN); } // Json fr Response body RequestError requestError = new RequestError(); requestError.setError(this.config .getProperty("error." + Integer.toString(HttpServletResponse.SC_FORBIDDEN) + ".2")); requestError.setCode(HttpServletResponse.SC_FORBIDDEN); requestError.setDescription(this.config.getProperty( "error." + Integer.toString(HttpServletResponse.SC_FORBIDDEN) + ".2.description")); requestError.setErrorUri(this.config .getProperty("error." + Integer.toString(HttpServletResponse.SC_FORBIDDEN) + ".2.uri")); if (format.equals("html")) { if (Lookup.lookupAll(ObjectToHtmlTransformation.class).size() > 0) { try { ObjectToHtmlTransformation htmlTransformation = Lookup .lookup(ObjectToHtmlTransformation.class); // init transformator htmlTransformation.init(this.config); HashMap<String, String> parameters = new HashMap<String, String>(); parameters.put("lang", language); parameters.put("redirect_url", redirect_url); //String provider = "http://" + httpServletRequest.getServerName() + ":" + httpServletRequest.getServerPort() + this.config.getProperty("service.endpoint.auth") + "/" + service; String provider = this.config.getProperty("service.base_url") + this.config.getProperty("service.endpoint.auth") + "/" + service; parameters.put("formURL", provider); httpServletResponse.setContentType("text/html;charset=UTF-8"); httpServletResponse.setStatus(HttpServletResponse.SC_OK); httpServletResponse.getWriter() .println(htmlTransformation.transform(new Document(), parameters)); } catch (TransformationException e) { e.printStackTrace(); httpServletResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Internal Server Error: Error while rendering a HTML message."); } } else { this.logger.error("ObjectToHtmlTransformation not configured! Switch to JSON."); format = "json"; } } // XML-Ausgabe mit JAXB if (format.equals("xml")) { try { JAXBContext context = JAXBContext.newInstance(RequestError.class); Marshaller m = context.createMarshaller(); m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); // Write to HttpResponse httpServletResponse.setContentType("application/xml;charset=UTF-8"); m.marshal(requestError, httpServletResponse.getWriter()); } catch (JAXBException e) { this.logger.error(e.getMessage(), e.getCause()); httpServletResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Internal Server Error: Error while rendering the results."); } } // JSON-Ausgabe mit Jackson if (format.equals("json")) { httpServletResponse.setContentType("application/json;charset=UTF-8"); mapper.writeValue(httpServletResponse.getWriter(), requestError); } } } else { this.logger.error(HttpServletResponse.SC_SERVICE_UNAVAILABLE + ": Config Error!"); // Error handling mit suppress_response_codes=true if (httpServletRequest.getParameter("suppress_response_codes") != null) { httpServletResponse.setStatus(HttpServletResponse.SC_OK); } // Error handling mit suppress_response_codes=false (=default) else { httpServletResponse.setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } // Json fr Response body RequestError requestError = new RequestError(); requestError.setError(this.config .getProperty("error." + Integer.toString(HttpServletResponse.SC_SERVICE_UNAVAILABLE))); requestError.setCode(HttpServletResponse.SC_SERVICE_UNAVAILABLE); requestError.setDescription(this.config.getProperty( "error." + Integer.toString(HttpServletResponse.SC_SERVICE_UNAVAILABLE) + ".description")); requestError.setErrorUri(this.config.getProperty( "error." + Integer.toString(HttpServletResponse.SC_SERVICE_UNAVAILABLE) + ".uri")); this.sendRequestError(httpServletResponse, requestError, format, language, redirect_url); } break; } case "logout": { if (Lookup.lookupAll(AuthorizationInterface.class).size() > 0) { AuthorizationInterface authorizationInterface = Lookup.lookup(AuthorizationInterface.class); // init Authorization Service authorizationInterface.init(this.config); if (!access_token.equals("")) { // AuthorizationInterface.revokeToken() try { boolean isRevoked = authorizationInterface.revokeToken(access_token); } catch (AuthorizationException e) { // TODO correct error handling this.logger.error(HttpServletResponse.SC_UNAUTHORIZED + "!"); } } httpServletResponse.setHeader("Access-Control-Allow-Origin", config.getProperty("Access-Control-Allow-Origin")); httpServletResponse.setHeader("Cache-Control", config.getProperty("Cache-Control")); httpServletResponse.setStatus(HttpServletResponse.SC_OK); // delete cookie Cookie cookie = new Cookie("PaiaService", null); if (this.config.getProperty("service.cookie.domain") != null && !this.config.getProperty("service.cookie.domain").equals("")) { cookie.setDomain(this.config.getProperty("service.cookie.domain")); } cookie.setMaxAge(0); cookie.setPath("/"); httpServletResponse.addCookie(cookie); // html >> redirect if (format.equals("html")) { if (httpServletRequest.getParameter("redirect_url") != null && !httpServletRequest.getParameter("redirect_url").equals("")) { redirect_url = httpServletRequest.getParameter("redirect_url"); } else { redirect_url = this.config.getProperty("service.auth.logout.redirect.default"); } httpServletResponse.sendRedirect(redirect_url); } if (format.equals("json")) { httpServletResponse.setContentType("application/json;charset=UTF-8"); httpServletResponse.getWriter().println("{\"logged out\":\"true\"}"); } if (format.equals("xml")) { httpServletResponse.setContentType("application/xml;charset=UTF-8"); httpServletResponse.getWriter().println( "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><logout status=\"true\" />"); } } else { this.logger.error(HttpServletResponse.SC_SERVICE_UNAVAILABLE + ": Config Error!"); // Error handling mit suppress_response_codes=true if (httpServletRequest.getParameter("suppress_response_codes") != null) { httpServletResponse.setStatus(HttpServletResponse.SC_OK); } // Error handling mit suppress_response_codes=false (=default) else { httpServletResponse.setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } // Json fr Response body RequestError requestError = new RequestError(); requestError.setError(this.config .getProperty("error." + Integer.toString(HttpServletResponse.SC_SERVICE_UNAVAILABLE))); requestError.setCode(HttpServletResponse.SC_SERVICE_UNAVAILABLE); requestError.setDescription(this.config.getProperty( "error." + Integer.toString(HttpServletResponse.SC_SERVICE_UNAVAILABLE) + ".description")); requestError.setErrorUri(this.config.getProperty( "error." + Integer.toString(HttpServletResponse.SC_SERVICE_UNAVAILABLE) + ".uri")); this.sendRequestError(httpServletResponse, requestError, format, language, redirect_url); } break; } case "change": { // build ChangeRequest object ChangeRequest changeRequest = mapper.readValue(requestBody, ChangeRequest.class); // check token ... boolean isAuthorized = false; if (access_token != null && !access_token.equals("")) { if (Lookup.lookupAll(AuthorizationInterface.class).size() > 0) { AuthorizationInterface authorizationInterface = Lookup.lookup(AuthorizationInterface.class); // init Authorization Service authorizationInterface.init(this.config); try { isAuthorized = authorizationInterface.isTokenValid(httpServletResponse, service, changeRequest.getPatron(), access_token); } catch (AuthorizationException e) { // TODO correct error handling this.logger.error(HttpServletResponse.SC_UNAUTHORIZED + "!"); } } else { // TODO correct error handling this.logger.error(HttpServletResponse.SC_INTERNAL_SERVER_ERROR + ": " + "Authorization Interface not implemented!"); } } this.logger.debug("Authorization: " + access_token + " - " + isAuthorized); if (!isAuthorized) { // Authorization this.authorize(httpServletRequest, httpServletResponse, format); } else { if (Lookup.lookupAll(LibraryManagementSystem.class).size() > 0) { LibraryManagementSystem libraryManagementSystem = Lookup.lookup(LibraryManagementSystem.class); // init ILS libraryManagementSystem.init(this.config); // exists patron? // use LibraryManagementSystem.patron(): failed = Exception! try { Patron patron = libraryManagementSystem.patron(changeRequest.getPatron(), false); boolean isChanged = libraryManagementSystem.changePassword(changeRequest); if (isChanged) { // E-Mail to user Mailer mailer = new Mailer(this.config.getProperty("service.mailer.conf")); try { if (this.config.getProperty("isTestMode") != null && !Boolean.parseBoolean(this.config.getProperty("isTestMode"))) { mailer.postMail(patron.getEmail(), this.config.getProperty("service.mailer.change.subject"), this.config.getProperty("service.mailer.change.message")); } else { mailer.postMail(this.config.getProperty("service.mailer.change.subject"), this.config.getProperty("service.mailer.change.message")); } } catch (MessagingException e1) { this.logger.error(e1.getMessage(), e1.getCause()); } this.logger.info("Password changed. Mail send to '" + patron.getEmail() + "'."); // 200 OK if (format.equals("html")) { format = "json"; // TODO or what else? } Patron responsePatron = new Patron(); responsePatron.setUsername(patron.getUsername()); responsePatron.setStatus(patron.getStatus()); responsePatron.setEmail(new InternetAddress(patron.getEmail())); if (format.equals("json")) { httpServletResponse.setContentType("application/json;charset=UTF-8"); mapper.writeValue(httpServletResponse.getWriter(), responsePatron); } if (format.equals("xml")) { JAXBContext context = JAXBContext.newInstance(Patron.class); Marshaller m = context.createMarshaller(); m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); // Write to HttpResponse httpServletResponse.setContentType("application/xml;charset=UTF-8"); m.marshal(responsePatron, httpServletResponse.getWriter()); } } else { // 401 UNAUTHORIZED this.logger.error(HttpServletResponse.SC_UNAUTHORIZED + ": Wrong old password!"); // Error handling mit suppress_response_codes=true if (httpServletRequest.getParameter("suppress_response_codes") != null) { httpServletResponse.setStatus(HttpServletResponse.SC_OK); } // Error handling mit suppress_response_codes=false (=default) else { httpServletResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED); } // Json fr Response body RequestError requestError = new RequestError(); requestError.setError(this.config .getProperty("error." + Integer.toString(HttpServletResponse.SC_UNAUTHORIZED))); requestError.setCode(HttpServletResponse.SC_UNAUTHORIZED); requestError.setDescription(this.config.getProperty("error." + Integer.toString(HttpServletResponse.SC_UNAUTHORIZED) + ".description")); requestError.setErrorUri(this.config.getProperty( "error." + Integer.toString(HttpServletResponse.SC_UNAUTHORIZED) + ".uri")); this.sendRequestError(httpServletResponse, requestError, format, language, redirect_url); } } catch (LibraryManagementSystemException e) { // 401 UNAUTHORIZED this.logger.error(HttpServletResponse.SC_UNAUTHORIZED + ": " + e.getMessage()); // Error handling mit suppress_response_codes=true if (httpServletRequest.getParameter("suppress_response_codes") != null) { httpServletResponse.setStatus(HttpServletResponse.SC_OK); } // Error handling mit suppress_response_codes=false (=default) else { httpServletResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED); } // Json fr Response body RequestError requestError = new RequestError(); requestError.setError(this.config .getProperty("error." + Integer.toString(HttpServletResponse.SC_UNAUTHORIZED))); requestError.setCode(HttpServletResponse.SC_UNAUTHORIZED); requestError.setDescription(this.config.getProperty( "error." + Integer.toString(HttpServletResponse.SC_UNAUTHORIZED) + ".description")); requestError.setErrorUri(this.config.getProperty( "error." + Integer.toString(HttpServletResponse.SC_UNAUTHORIZED) + ".uri")); this.sendRequestError(httpServletResponse, requestError, format, language, redirect_url); } catch (Exception e) { this.logger.error(HttpServletResponse.SC_INTERNAL_SERVER_ERROR + ": Config Error!"); // Error handling mit suppress_response_codes=true if (httpServletRequest.getParameter("suppress_response_codes") != null) { httpServletResponse.setStatus(HttpServletResponse.SC_OK); } // Error handling mit suppress_response_codes=false (=default) else { httpServletResponse.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } // Json fr Response body RequestError requestError = new RequestError(); requestError.setError(this.config.getProperty( "error." + Integer.toString(HttpServletResponse.SC_INTERNAL_SERVER_ERROR))); requestError.setCode(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); requestError.setDescription(this.config.getProperty("error." + Integer.toString(HttpServletResponse.SC_INTERNAL_SERVER_ERROR) + ".description")); requestError.setErrorUri(this.config.getProperty("error." + Integer.toString(HttpServletResponse.SC_INTERNAL_SERVER_ERROR) + ".uri")); this.sendRequestError(httpServletResponse, requestError, format, language, redirect_url); } } else { this.logger.error(HttpServletResponse.SC_INTERNAL_SERVER_ERROR + ": Config Error!"); // Error handling mit suppress_response_codes=true if (httpServletRequest.getParameter("suppress_response_codes") != null) { httpServletResponse.setStatus(HttpServletResponse.SC_OK); } // Error handling mit suppress_response_codes=false (=default) else { httpServletResponse.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } // Json fr Response body RequestError requestError = new RequestError(); requestError.setError(this.config.getProperty( "error." + Integer.toString(HttpServletResponse.SC_INTERNAL_SERVER_ERROR))); requestError.setCode(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); requestError.setDescription(this.config.getProperty("error." + Integer.toString(HttpServletResponse.SC_INTERNAL_SERVER_ERROR) + ".description")); requestError.setErrorUri(this.config.getProperty( "error." + Integer.toString(HttpServletResponse.SC_INTERNAL_SERVER_ERROR) + ".uri")); this.sendRequestError(httpServletResponse, requestError, format, language, redirect_url); } } break; } case "renew": { if (Lookup.lookupAll(LibraryManagementSystem.class).size() > 0) { LibraryManagementSystem libraryManagementSystem = Lookup.lookup(LibraryManagementSystem.class); // init ILS libraryManagementSystem.init(this.config); // exists patron? // use LibraryManagementSystem.patron(): failed = Exception! try { // build NewPasswordRequest object NewPasswordRequest newPasswordRequest = mapper.readValue(requestBody, NewPasswordRequest.class); Patron patron = libraryManagementSystem.patron(newPasswordRequest.getPatron(), true); if (patron.getEmail() != null && !patron.getEmail().equals("")) { boolean isRenewed = libraryManagementSystem.renewPassword(newPasswordRequest, patron); if (isRenewed) { // E-Mail to user Mailer mailer = new Mailer(this.config.getProperty("service.mailer.conf")); try { if (this.config.getProperty("isTestMode") != null && !Boolean.parseBoolean(this.config.getProperty("isTestMode"))) { mailer.postMail(patron.getEmail(), this.config.getProperty("service.mailer.renew.subject"), this.config.getProperty("service.mailer.renew.message")); } else { mailer.postMail(this.config.getProperty("service.mailer.renew.subject"), this.config.getProperty("service.mailer.renew.message")); } } catch (MessagingException e1) { this.logger.error(e1.getMessage(), e1.getCause()); } this.logger.info("Password resetted. Mail send to '" + patron.getEmail() + "'."); // 200 OK if (format.equals("html")) { format = "json"; // TODO or what else? } Patron responsePatron = new Patron(); responsePatron.setUsername(patron.getUsername()); responsePatron.setStatus(patron.getStatus()); responsePatron.setEmail(new InternetAddress(patron.getEmail())); if (format.equals("json")) { httpServletResponse.setContentType("application/json;charset=UTF-8"); mapper.writeValue(httpServletResponse.getWriter(), responsePatron); } if (format.equals("xml")) { JAXBContext context = JAXBContext.newInstance(Patron.class); Marshaller m = context.createMarshaller(); m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); // Write to HttpResponse httpServletResponse.setContentType("application/xml;charset=UTF-8"); m.marshal(responsePatron, httpServletResponse.getWriter()); } } else { // 401 SC_UNAUTHORIZED this.logger.error(HttpServletResponse.SC_UNAUTHORIZED + ": Wrong usergroup!"); // Error handling mit suppress_response_codes=true if (httpServletRequest.getParameter("suppress_response_codes") != null) { httpServletResponse.setStatus(HttpServletResponse.SC_OK); } // Error handling mit suppress_response_codes=false (=default) else { httpServletResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED); } // Json fr Response body RequestError requestError = new RequestError(); requestError.setError(this.config .getProperty("error." + Integer.toString(HttpServletResponse.SC_UNAUTHORIZED))); requestError.setCode(HttpServletResponse.SC_UNAUTHORIZED); requestError.setDescription(this.config.getProperty("error." + Integer.toString(HttpServletResponse.SC_UNAUTHORIZED) + ".description")); requestError.setErrorUri(this.config.getProperty( "error." + Integer.toString(HttpServletResponse.SC_UNAUTHORIZED) + ".uri")); this.sendRequestError(httpServletResponse, requestError, format, language, redirect_url); } } else { // 401 SC_UNAUTHORIZED this.logger.error(HttpServletResponse.SC_UNAUTHORIZED + ": No E-Mail-Address exists!"); // Error handling mit suppress_response_codes=true if (httpServletRequest.getParameter("suppress_response_codes") != null) { httpServletResponse.setStatus(HttpServletResponse.SC_OK); } // Error handling mit suppress_response_codes=false (=default) else { httpServletResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED); } // Json fr Response body RequestError requestError = new RequestError(); requestError.setError(this.config .getProperty("error." + Integer.toString(HttpServletResponse.SC_UNAUTHORIZED))); requestError.setCode(HttpServletResponse.SC_UNAUTHORIZED); requestError.setDescription(this.config.getProperty( "error." + Integer.toString(HttpServletResponse.SC_UNAUTHORIZED) + ".description")); requestError.setErrorUri(this.config.getProperty( "error." + Integer.toString(HttpServletResponse.SC_UNAUTHORIZED) + ".uri")); this.sendRequestError(httpServletResponse, requestError, format, language, redirect_url); } } catch (LibraryManagementSystemException e) { e.printStackTrace(); // 400 SC_BAD_REQUEST this.logger.error(HttpServletResponse.SC_BAD_REQUEST + ": " + e.getMessage()); // Error handling mit suppress_response_codes=true if (httpServletRequest.getParameter("suppress_response_codes") != null) { httpServletResponse.setStatus(HttpServletResponse.SC_OK); } // Error handling mit suppress_response_codes=false (=default) else { httpServletResponse.setStatus(HttpServletResponse.SC_BAD_REQUEST); } // Json fr Response body RequestError requestError = new RequestError(); requestError.setError(this.config .getProperty("error." + Integer.toString(HttpServletResponse.SC_BAD_REQUEST))); requestError.setCode(HttpServletResponse.SC_BAD_REQUEST); requestError.setDescription(this.config.getProperty( "error." + Integer.toString(HttpServletResponse.SC_BAD_REQUEST) + ".description")); requestError.setErrorUri(this.config .getProperty("error." + Integer.toString(HttpServletResponse.SC_BAD_REQUEST) + ".uri")); this.sendRequestError(httpServletResponse, requestError, format, language, redirect_url); } catch (Exception e) { this.logger.error(HttpServletResponse.SC_INTERNAL_SERVER_ERROR + ": Config Error!"); // Error handling mit suppress_response_codes=true if (httpServletRequest.getParameter("suppress_response_codes") != null) { httpServletResponse.setStatus(HttpServletResponse.SC_OK); } // Error handling mit suppress_response_codes=false (=default) else { httpServletResponse.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } // Json fr Response body RequestError requestError = new RequestError(); requestError.setError(this.config.getProperty( "error." + Integer.toString(HttpServletResponse.SC_INTERNAL_SERVER_ERROR))); requestError.setCode(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); requestError.setDescription(this.config.getProperty("error." + Integer.toString(HttpServletResponse.SC_INTERNAL_SERVER_ERROR) + ".description")); requestError.setErrorUri(this.config.getProperty( "error." + Integer.toString(HttpServletResponse.SC_INTERNAL_SERVER_ERROR) + ".uri")); this.sendRequestError(httpServletResponse, requestError, format, language, redirect_url); } } else { this.logger.error(HttpServletResponse.SC_INTERNAL_SERVER_ERROR + ": Config Error!"); // Error handling mit suppress_response_codes=true if (httpServletRequest.getParameter("suppress_response_codes") != null) { httpServletResponse.setStatus(HttpServletResponse.SC_OK); } // Error handling mit suppress_response_codes=false (=default) else { httpServletResponse.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } // Json fr Response body RequestError requestError = new RequestError(); requestError.setError(this.config .getProperty("error." + Integer.toString(HttpServletResponse.SC_INTERNAL_SERVER_ERROR))); requestError.setCode(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); requestError.setDescription(this.config.getProperty("error." + Integer.toString(HttpServletResponse.SC_INTERNAL_SERVER_ERROR) + ".description")); requestError.setErrorUri(this.config.getProperty( "error." + Integer.toString(HttpServletResponse.SC_INTERNAL_SERVER_ERROR) + ".uri")); this.sendRequestError(httpServletResponse, requestError, format, language, redirect_url); } break; } default: { this.logger.error(HttpServletResponse.SC_BAD_REQUEST + "Unknown function! (" + service + ")"); // Error handling mit suppress_response_codes=true if (httpServletRequest.getParameter("suppress_response_codes") != null && !httpServletRequest.getParameter("suppress_response_codes").equals("")) { httpServletResponse.setStatus(HttpServletResponse.SC_OK); } // Error handling mit suppress_response_codes=false (=default) else { httpServletResponse.setStatus(HttpServletResponse.SC_BAD_REQUEST); } // Json fr Response body RequestError requestError = new RequestError(); requestError.setError( this.config.getProperty("error." + Integer.toString(HttpServletResponse.SC_BAD_REQUEST))); requestError.setCode(HttpServletResponse.SC_BAD_REQUEST); requestError.setDescription(this.config .getProperty("error." + Integer.toString(HttpServletResponse.SC_BAD_REQUEST) + ".description")); requestError.setErrorUri(this.config .getProperty("error." + Integer.toString(HttpServletResponse.SC_BAD_REQUEST) + ".uri")); this.sendRequestError(httpServletResponse, requestError, format, language, redirect_url); } } }
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;//from w w w . j a v a2 s . c o m } 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:com.google.gsa.valve.modules.ldap.LDAPSSO.java
/** * This is the main method that does the authentication and should be * invoked by the classes that would like to populate new user authentication * credentials from the LDAP server./*from w ww.j a v a2s.c om*/ * <p> * It also authenticates the user against the LDAP server, so that only * priviledged users are able to read the LDAP attributes. These multiple * credentials are stored in the directory server and populate them in the * user's credential container. It enables the other AuthN/AuthZ modules to * use them when securely accessing the backend systems. * <p> * If the LDAP authentication result is OK, it creates an * authentication cookie. Anyway, the HTTP response code is returned in this * method to inform the caller on the status. * * @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 { logger.debug("Start LDAPSSO AuthN process"); //protection repositories.clear(); ldapAttributes.clear(); //Insert LDAP attributes from the config file getLDAPAttributes(id); //First read the u/p the credentails store, in this case using the same as the root login logger.debug("LDAPSSO: trying to get creds from repository ID: " + id); Credential cred = null; try { cred = creds.getCredential(id); } catch (NullPointerException npe) { logger.error("NPE while reading credentials of ID: " + id); } if (cred == null) { cred = creds.getCredential("root"); if (cred != null) { logger.info("LDAPSSO: credential ID used is \"root\""); } else { logger.error("LDAPSSO: No credentials available for " + id); } } Cookie[] cookies = null; // Initialize status code int statusCode = HttpServletResponse.SC_UNAUTHORIZED; // Read cookies cookies = request.getCookies(); 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:"); } //If the required cookie was not found need to authenticate. logger.info("Authenticating root user with LDAP"); try { //Check if the LDAP credentials are OK Ldap ldapconn = new Ldap(ldapHost, cred.getUsername(), cred.getPassword(), ldapBaseuser, ldapDomain, rdnAttr); try { logger.debug("Connecting to LDAP"); DirContext ctx = ldapconn.openConnection(); if (ctx == null) { //Just send a comment logger.debug("The user(" + cred.getUsername() + ")/password doesn't match"); ldapconn.closeConnection(ctx); return (HttpServletResponse.SC_UNAUTHORIZED); } //Fetching credentials logger.debug("Fetching credentials from the LDAP"); fetchingCredentials(ldapconn, ctx, cred.getUsername(), creds); //Close the connection ldapconn.closeConnection(ctx); } catch (Exception ex) { logger.error("LDAP connection problem during user access: " + ex.getMessage(), ex); return (HttpServletResponse.SC_UNAUTHORIZED); } finally { } Cookie extAuthCookie = null; extAuthCookie = settingCookie(); //add sendCookies support logger.debug("Setting session"); 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); //This would be set to OK or 401 in a real AuthN module statusCode = HttpServletResponse.SC_OK; } catch (Exception e) { // Log error logger.error("LDAP SSO authentication failure: " + e.getMessage(), e); // Update status code statusCode = HttpServletResponse.SC_UNAUTHORIZED; } // Debug logger.debug("Sample Authentication completed (" + statusCode + ")"); // Return status code return statusCode; }
From source file:eu.eidas.node.AbstractNodeServlet.java
/** * Sets HTTPOnly Header on the session to prevent cookies from being accessed through * client-side script./*from w w w .j a v a 2 s .c om*/ * * @param renewSession indicates that the session cookie will be renewed */ protected final void setHTTPOnlyHeaderToSession(final boolean renewSession, HttpServletRequest request, HttpServletResponse response) { if (request != null && request.getSession(false) != null) { // Renewing the session if necessary String currentSession = null; String messageLog = null; if (renewSession) { currentSession = sessionIdRegenerationInWebApp(request); messageLog = "http session Renewed : {}"; } else { currentSession = request.getSession().getId(); messageLog = "http session obtained from request : {}"; } MDC.put(LoggingMarkerMDC.MDC_SESSIONID, currentSession); getLogger().info(LoggingMarkerMDC.SECURITY_SUCCESS, messageLog, currentSession); // changing session cookie to http only cookie if (request.getCookies() != null && request.isRequestedSessionIdFromCookie()) { //Session Id requested by the client, obtained from the cookie final String requestedSessionId = request.getRequestedSessionId(); for (Cookie cookie : request.getCookies()) { getLogger().debug("Treating cookie [domain][path][name][value] : [{}][{}][{}][{}]", cookie.getName(), cookie.getPath(), cookie.getName(), cookie.getValue()); if (currentSession.equals(requestedSessionId)) { // Removes old version boolean isSecure = request.isSecure(); getLogger().debug("Cookie==session : Remove and replacing with HttpOnly {}", cookie.toString()); getLogger().debug("Is using SSL?", isSecure); //TODO: when migrating to servlet 3, use the cookie interface calls below instead of writing the http header // //NOSONAR cookie.setMaxAge(0); //NOSONAR cookie.setPath(getServletContext().getContextPath()); //NOSONAR cookie.setDomain(request.getServerName()); //NOSONAR cookie.setSecure(isSecure); //NOSONAR cookie.setHttpOnly(true); //NOSONAR response.addCookie(cookie); // Create new one httpOnly StringBuilder httpOnlyCookie = new StringBuilder(cookie.getName()) .append(EIDASValues.EQUAL.toString()).append(cookie.getValue()) .append(EIDASValues.SEMICOLON.toString()).append(" ") .append(EIDASValues.DOMAIN.toString()).append(EIDASValues.EQUAL.toString()) .append(request.getServerName()).append(EIDASValues.SEMICOLON.toString()) .append(" ").append(EIDASValues.PATH.toString()) .append(EIDASValues.EQUAL.toString()).append(getServletContext().getContextPath()) .append(EIDASValues.SEMICOLON.toString()).append(" ") .append(EIDASValues.HTTP_ONLY.toString()).append(EIDASValues.SEMICOLON.toString()) .append(isSecure ? EIDASValues.SECURE.toString() : ""); response.setHeader(EIDASValues.SETCOOKIE.toString(), httpOnlyCookie.toString()); } } } //cookie _csrf // request.setAttribute("_csrf_header", "X-CSRF-TOKEN"); // UUID idOne = UUID.randomUUID(); // LOG.info("generate csrf id="+idOne); // request.setAttribute("_csrf", idOne); response.setHeader("_csrf_header", "X-CSRF-TOKEN"); UUID idOne = UUID.randomUUID(); UUID idTwo = UUID.randomUUID(); getLogger().info("generate csrf id1=" + idOne + " id2=" + idTwo); Cookie gato = new Cookie("_csrf", idOne.toString()); response.addCookie(gato); response.setHeader("X-CSRF-TOKEN", idTwo.toString()); } else { getLogger().warn(LoggingMarkerMDC.SECURITY_FAILURE, "Request or Session is null !"); } }
From source file:com.ylife.shoppingcart.service.impl.ShoppingCartServiceImpl.java
/** * /*w w w . j a v a2 s .com*/ * * @param shoppingCartId * id * @param marketingId * ??id * @param marketingActivityId * id * @return int */ @Override public int changeShoppingCartMarket(Long shoppingCartId, Long marketingId, Long marketingActivityId, HttpServletRequest request, HttpServletResponse response) { Long marketingIdNew = marketingId; Long marketingActivityIdNew = marketingActivityId; Long customerId = (Long) request.getSession().getAttribute(CUSTOMERID); // ? if (customerId != null) { ShoppingCart sc = new ShoppingCart(); sc.setShoppingCartId(shoppingCartId); // ??id0??? if (marketingIdNew != null && marketingIdNew == 0) { marketingIdNew = null; } sc.setMarketingId(marketingIdNew); // id0? if (marketingActivityIdNew != null && marketingActivityIdNew == 0) { marketingActivityIdNew = null; } sc.setMarketingActivityId(marketingActivityIdNew); return shoppingCartMapper.changeShoppingCartMarket(sc); } else { Cookie[] cookies = request.getCookies(); StringBuilder newMid = new StringBuilder(); if (null != cookies) { for (Cookie cookie : cookies) { if (cookie != null && NPSTORE_MID.equals(cookie.getName()) && cookie.getValue() != null && !"".equals(cookie.getValue())) { String[] mIds = cookie.getValue().split("-"); // ?cookie for (int j = 0; j < mIds.length; j++) { String[] mid = mIds[j].split("e"); // ?? if (mid[0] != null) { if (mid[0].equals(shoppingCartId.toString())) { newMid.append(shoppingCartId); newMid.append("e"); newMid.append(marketingIdNew); newMid.append("e"); newMid.append(marketingActivityIdNew); newMid.append("e"); newMid.append("1"); newMid.append("-"); } else { newMid.append(mIds[j]); newMid.append("-"); } } } } } Cookie cookie = new Cookie(NPSTORE_MID, newMid.toString()); cookie.setMaxAge(15 * 24 * 3600); cookie.setPath("/"); response.addCookie(cookie); } return 0; } }
From source file:com.ylife.shoppingcart.service.impl.ShoppingCartServiceImpl.java
/** * cookie?//ww w . ja v a 2 s .c o m * * @param request * * @param response * * @return ? * @throws UnsupportedEncodingException */ public int delCookShopCar(Long productId, HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException { Integer count = 0; Cookie[] cookies = request.getCookies(); String oldCar = ""; String[] cars = null; String[] car = null; Cookie cook; String newMid = ""; StringBuilder bufOldCar = new StringBuilder(); StringBuilder bufNewMid = new StringBuilder(); try { if (null != cookies) { for (Cookie cookie : cookies) { if (null != cookie && NPSTORE_SHOPCAR.equals(cookie.getName())) { oldCar = URLDecoder.decode(cookie.getValue(), "utf-8"); if (oldCar.indexOf("," + productId + "-") != -1) { oldCar = oldCar.substring(1, oldCar.length()); oldCar = oldCar.substring(0, oldCar.length() - 1); cars = oldCar.split("e,"); oldCar = ""; for (int j = 0; j < cars.length; j++) { car = cars[j].split("-"); if (!car[0].equals(productId.toString())) { bufOldCar.append(oldCar); bufOldCar.append(","); bufOldCar.append(car[0]); bufOldCar.append("-"); bufOldCar.append(car[1]); bufOldCar.append("e"); oldCar += bufOldCar.toString(); } } } } if (cookie != null && NPSTORE_MID.equals(cookie.getName()) && cookie.getValue() != null && !"".equals(cookie.getValue())) { String[] mIds = cookie.getValue().split("-"); // ?cookie for (int j = 0; j < mIds.length; j++) { String[] mid = mIds[j].split("e"); // ?? if (mid[0] != null && !mid[0].equals(productId.toString())) { bufNewMid.append(mIds[j]); bufNewMid.append("-"); newMid += bufNewMid.toString(); } } } } } cook = new Cookie(NPSTORE_SHOPCAR, URLEncoder.encode(oldCar, "utf-8")); cook.setMaxAge(15 * 24 * 3600); cook.setPath("/"); response.addCookie(cook); Cookie cookie = new Cookie(NPSTORE_MID, URLEncoder.encode(newMid, "utf-8")); cookie.setMaxAge(15 * 24 * 3600); cookie.setPath("/"); response.addCookie(cookie); return count; } finally { cook = null; cars = null; car = null; cookies = null; oldCar = null; } }