List of usage examples for org.apache.commons.codec.binary Base64 encodeBase64URLSafeString
public static String encodeBase64URLSafeString(final byte[] binaryData)
From source file:org.i3xx.step.uno.impl.ScriptCacheImpl.java
/** * Serializes the content to JSON// w ww . j a va 2 s . c o m * * @return The JSON String */ public String toJSON() { Gson gson = new Gson(); StringBuffer buf = new StringBuffer(); buf.append('{'); buf.append(gson.toJson("digest")); buf.append(':'); buf.append(gson.toJson(digest)); buf.append(','); buf.append(gson.toJson("compress")); buf.append(':'); buf.append(gson.toJson(Boolean.valueOf(compress))); buf.append(','); buf.append(gson.toJson("names")); buf.append(':'); buf.append('['); for (int i = 0; i < names.length; i++) { if (i > 0) buf.append(','); buf.append(gson.toJson(names[i])); } buf.append(']'); buf.append(','); buf.append(gson.toJson("buffer")); buf.append(':'); buf.append('['); for (int i = 0; i < buffer.length; i++) { if (i > 0) buf.append(','); String stmt = Base64.encodeBase64URLSafeString(buffer[i]); buf.append(gson.toJson(stmt)); } buf.append(']'); buf.append('}'); return buf.toString(); }
From source file:org.i3xx.step.uno.impl.service.builtin.ContextAdministrationService.java
/** * Writes the key value map to a JSON String * // ww w . j a v a 2 s.c om * @return The JSON String * @throws Exception */ public String toJSON() throws Exception { Gson gson = new Gson(); StringBuffer buffer = new StringBuffer(); Map<String, Object> values = context.getValues(); if (logger.isDebugEnabled()) { Iterator<Map.Entry<String, Object>> tempI = context.getValues().entrySet().iterator(); while (tempI.hasNext()) { Map.Entry<String, Object> e = tempI.next(); logger.debug("JSON object key:{}, value:{}, class:{}", e.getKey(), e.getValue(), e.getValue() == null ? "null" : e.getValue().getClass()); } } Context jscx = Context.getCurrentContext(); boolean jsf = jscx != null; if (!jsf) jscx = Context.enter(); Iterator<String> keys = values.keySet().iterator(); while (keys.hasNext()) { String key = keys.next(); buffer.append(','); buffer.append(gson.toJson(key)); buffer.append(':'); Object val = values.get(key); if (val == null) { buffer.append(gson.toJson(null)); } else if (val instanceof Number) { buffer.append(gson.toJson(val)); } else if (val instanceof String) { buffer.append(gson.toJson(val)); } else if (val instanceof Scriptable) { Scriptable scope = context.getScope(); Scriptable object = (Scriptable) val; String stmt = (String) NativeJSON.stringify(Context.getCurrentContext(), scope, object, null, null); buffer.append('{'); buffer.append(gson.toJson("Scriptable")); buffer.append(':'); buffer.append(gson.toJson(stmt)); buffer.append('}'); } else if (val instanceof Serializable) { buffer.append('{'); buffer.append(gson.toJson("Object")); buffer.append(':'); byte[] buf = readValue(val); if (buf == null) continue; String stmt = Base64.encodeBase64URLSafeString(buf); buffer.append(gson.toJson(stmt)); buffer.append('}'); } else { //error } //fi } if (buffer.length() > 0) { buffer.setCharAt(0, '{'); } else { buffer.append('{'); } buffer.append('}'); if (!jsf) Context.exit(); return buffer.toString(); }
From source file:org.i3xx.step.uno.impl.service.builtin.ContextPropertiesService.java
/** * Writes the key value map to a JSON String * //from w ww . j av a2 s . co m * @param names The names of the properties to be put into the JSON * (or null for all properties). * @return The JSON * @throws Exception */ public String toJSON(String[] names) throws Exception { Gson gson = new Gson(); StringBuffer buffer = new StringBuffer(); Map<String, Object> values = context.getValues(); if (names == null) names = values.keySet().toArray(new String[values.size()]); if (logger.isDebugEnabled()) { for (String key : names) { Object val = values.get(key); logger.debug("JSON object key:{}, value:{}, class:{}", key, val, val == null ? "null" : val.getClass()); } } Context jscx = Context.getCurrentContext(); boolean jsf = jscx != null; if (!jsf) jscx = Context.enter(); for (String key : names) { buffer.append(','); buffer.append(gson.toJson(key)); buffer.append(':'); Object val = values.get(key); if (val == null) { buffer.append(gson.toJson(null)); } else if (val instanceof Number) { buffer.append(gson.toJson(val)); } else if (val instanceof String) { buffer.append(gson.toJson(val)); } else if (val instanceof Scriptable) { Scriptable scope = context.getScope(); Scriptable object = (Scriptable) val; String stmt = (String) NativeJSON.stringify(Context.getCurrentContext(), scope, object, null, null); buffer.append('{'); buffer.append(gson.toJson("Scriptable")); buffer.append(':'); buffer.append(gson.toJson(stmt)); buffer.append('}'); } else if (val instanceof Serializable) { buffer.append('{'); buffer.append(gson.toJson("Object")); buffer.append(':'); byte[] buf = readValue(val); if (buf == null) continue; String stmt = Base64.encodeBase64URLSafeString(buf); buffer.append(gson.toJson(stmt)); buffer.append('}'); } else { //Not serializable field to skip } //fi } if (buffer.length() > 0) { buffer.setCharAt(0, '{'); } else { buffer.append('{'); } buffer.append('}'); if (!jsf) Context.exit(); return buffer.toString(); }
From source file:org.i3xx.step.uno.impl.service.DeployServiceImpl.java
private File getFile(File parent, String target) { while (target.contains("*")) { String tmp = target;// w w w. j a v a 2 s .c o m while (tmp.contains("*")) { int p = tmp.lastIndexOf('*'); byte[] bytes = new byte[4]; Random r = new Random(); r.nextBytes(bytes); String s = Base64.encodeBase64URLSafeString(bytes); tmp = tmp.substring(0, p) + s + tmp.substring(p + 1); } //while File f = new File(parent, tmp); if (!f.exists()) return f; //exit } //while return new File(parent, target); }
From source file:org.infoglue.cms.applications.common.VisualFormatter.java
public final String encodeBase64(String s) throws Exception { if (s == null) return null; return Base64.encodeBase64URLSafeString(s.getBytes("utf-8")); }
From source file:org.infoglue.cms.security.InfoGlueAuthenticationFilter.java
/** * This filter is basically what secures Infoglue and enforces the authentication framework. *//* w ww. ja va2s .com*/ public void doFilter(ServletRequest request, ServletResponse response, FilterChain fc) throws ServletException, IOException { HttpServletRequest httpServletRequest = (HttpServletRequest) request; HttpServletResponse httpServletResponse = (HttpServletResponse) response; try { if (CmsPropertyHandler.getServletContext() == null) { CmsPropertyHandler.setServletContext(httpServletRequest.getContextPath()); } String URI = httpServletRequest.getRequestURI(); String URL = httpServletRequest.getRequestURL().toString(); if (logger.isInfoEnabled()) { logger.info("URI: + " + URI); logger.info("URL: + " + URL); } String requestURI = URLDecoder.decode(getContextRelativeURI(httpServletRequest), "UTF-8"); if (URI == null) logger.error("URI was null - requestURI:" + requestURI); if (URL == null) logger.error("URL was null - requestURI:" + requestURI); if (requestURI == null) logger.error("requestURI was null"); if (loginUrl == null) { logger.error("loginUrl was null - fix this."); loginUrl = "Login.action"; } if (invalidLoginUrl == null) { logger.error("invalidLoginUrl was null - fix this."); invalidLoginUrl = "Login!invalidLogin.action"; } if (logoutUrl == null) { logger.error("logoutUrl was null - fix this."); logoutUrl = "ExtranetLogin!logout.action"; } if (uriMatcher == null) { logger.error("uriMatcher was null - fix this."); String filterURIs = filterConfig.getInitParameter(FILTER_URIS_PARAMETER); uriMatcher = URIMatcher.compilePatterns(splitString(filterURIs, ","), false); } if (!CmsPropertyHandler.getIsValidSetup() && (URI.indexOf("Install") == -1 && URI.indexOf(".action") > -1)) { httpServletResponse.sendRedirect("Install!input.action"); return; } //Here are the url:s/paths that must be skipped by the security framework for it to work. Login screens etc must be reachable naturally. if (URI != null && URL != null && (URI.indexOf(loginUrl) > -1 || URL.indexOf(loginUrl) > -1 || URI.indexOf("Login.action") > -1 || URL.indexOf("Login.action") > -1 || URI.indexOf(invalidLoginUrl) > -1 || URL.indexOf(invalidLoginUrl) > -1 || URI.indexOf("Login!invalidLogin.action") > -1 || URL.indexOf("Login!invalidLogin.action") > -1 || URI.indexOf(logoutUrl) > -1 || URI.indexOf("Login!logout.action") > -1 || URL.indexOf(logoutUrl) > -1 || URI.indexOf("UpdateCache") > -1 || URI.indexOf("protectedRedirect.jsp") > -1 || uriMatcher.matches(requestURI))) { fc.doFilter(request, response); return; } // make sure we've got an HTTP request if (!(request instanceof HttpServletRequest) || !(response instanceof HttpServletResponse)) throw new ServletException("InfoGlue Filter protects only HTTP resources"); HttpSession session = ((HttpServletRequest) request).getSession(); String sessionTimeout = CmsPropertyHandler.getSessionTimeout(); try { Integer.parseInt(sessionTimeout); } catch (Exception e) { sessionTimeout = "1800"; } if (sessionTimeout == null) sessionTimeout = "1800"; session.setMaxInactiveInterval(new Integer(sessionTimeout).intValue()); // if our attribute's already present, don't do anything //logger.info("User:" + session.getAttribute(INFOGLUE_FILTER_USER)); if (session != null && session.getAttribute(INFOGLUE_FILTER_USER) != null) { //logger.info("Found user in session:" + session.getAttribute(INFOGLUE_FILTER_USER)); //if(successLoginBaseUrl != null && !URL.startsWith(successLoginBaseUrl)) //{ // checkSuccessRedirect(request, response, URL); //} //else //{ fc.doFilter(request, response); return; //} } // otherwise, we need to authenticate somehow boolean isAdministrator = false; String userName = request.getParameter("j_username"); String password = request.getParameter("j_password"); if (userName != null && password != null) { String administratorUserName = CmsPropertyHandler.getAdministratorUserName(); boolean matchesRootPassword = CmsPropertyHandler.getMatchesAdministratorPassword(password); isAdministrator = (userName.equalsIgnoreCase(administratorUserName) && matchesRootPassword) ? true : false; } //First we check if the user is logged in to the container context if (!isAdministrator) { logger.info("Principal:" + httpServletRequest.getUserPrincipal()); if (httpServletRequest.getUserPrincipal() != null && !(httpServletRequest.getUserPrincipal() instanceof InfoGluePrincipal)) { userName = httpServletRequest.getUserPrincipal().getName(); logger.info("Now trusting the container logged in identity..."); } } String authenticatedUserName = userName; if (!isAdministrator) { String encodedUserNameCookie = httpHelper.getCookie(httpServletRequest, "iguserid"); logger.info("encodedUserNameCookie:" + encodedUserNameCookie); if (encodedUserNameCookie != null && !encodedUserNameCookie.equals("")) { byte[] bytes = Base64.decodeBase64(encodedUserNameCookie); encodedUserNameCookie = new String(bytes, "utf-8"); //encodedUserNameCookie = encodedUserNameCookie.replaceAll("IGEQ", "="); logger.info("encodedUserNameCookie:" + encodedUserNameCookie); String servletContextUserName = (String) filterConfig.getServletContext() .getAttribute(encodedUserNameCookie); logger.info("servletContextUserName:" + servletContextUserName); if (servletContextUserName != null && !servletContextUserName.equals("")) { authenticatedUserName = servletContextUserName; } else { Cookie cookie_iguserid = new Cookie("iguserid", "none"); cookie_iguserid.setPath("/"); cookie_iguserid.setMaxAge(0); httpServletResponse.addCookie(cookie_iguserid); Cookie cookie_igpassword = new Cookie("igpassword", "none"); cookie_igpassword.setPath("/"); cookie_igpassword.setMaxAge(0); httpServletResponse.addCookie(cookie_igpassword); authenticatedUserName = authenticateUser(httpServletRequest, httpServletResponse, fc); } } else { authenticatedUserName = authenticateUser(httpServletRequest, httpServletResponse, fc); } } logger.info("authenticatedUserName:" + authenticatedUserName); if (authenticatedUserName != null) { logger.info("Getting the principal from user name:" + authenticatedUserName); InfoGluePrincipal user = getAuthenticatedUser(authenticatedUserName); if (user == null || (!user.getIsAdministrator() && !hasAuthorizedRole(user))) { //throw new Exception("This user is not authorized to log in..."); httpServletResponse.sendRedirect("unauthorizedLogin.jsp"); NotificationMessage notificationMessage = new NotificationMessage("Authorization failed:", "Authorization", authenticatedUserName, NotificationMessage.AUTHORIZATION_FAILED, "" + authenticatedUserName, "name"); TransactionHistoryController.getController().create(notificationMessage); return; } //TODO - we must fix so these caches are individual to the person - now a login will slow down for all //CacheController.clearCache("authorizationCache"); //CacheController.clearCache("personalAuthorizationCache", user.getName()); CacheController.clearCacheForGroup("personalAuthorizationCache", user.getName()); // Store the authenticated user in the session if (session != null) { session.setAttribute(INFOGLUE_FILTER_USER, user); setUserProperties(session, user); } //TEST - transferring auth to deliverworking try { if (userName != null && password != null) { DesEncryptionHelper encHelper = new DesEncryptionHelper(); String encryptedName = encHelper.encrypt(userName); String encryptedPassword = encHelper.encrypt(password); String encryptedNameAsBase64 = Base64 .encodeBase64URLSafeString(encryptedName.getBytes("utf-8")); String encryptedPasswordAsBase64 = Base64 .encodeBase64URLSafeString(encryptedPassword.getBytes("utf-8")); String deliverBaseUrl = CmsPropertyHandler.getComponentRendererUrl(); String[] parts = deliverBaseUrl.split("/"); deliverBaseUrl = "/" + parts[parts.length - 1]; //logger.info("used cmsBaseUrl:" + cmsBaseUrl); ServletContext servletContext = filterConfig.getServletContext().getContext(deliverBaseUrl); if (servletContext == null) { logger.error("Could not autologin to " + deliverBaseUrl + ". Set cross context = true in Tomcat config."); } else { logger.info("Added encryptedName:" + encryptedName + " = " + user.getName() + " to deliver context"); servletContext.setAttribute(encryptedName, user.getName()); } int cmsCookieTimeout = 1800; //30 minutes default String cmsCookieTimeoutString = null; //CmsPropertyHandler.getCmsCookieTimeout(); if (cmsCookieTimeoutString != null) { try { cmsCookieTimeout = Integer.parseInt(cmsCookieTimeoutString.trim()); } catch (Exception e) { } } //Cookie cookie_iguserid = new Cookie("iguserid", encryptedName.replaceAll("=", "IGEQ")); Cookie cookie_iguserid = new Cookie("iguserid", encryptedNameAsBase64); cookie_iguserid.setPath("/"); cookie_iguserid.setMaxAge(cmsCookieTimeout); httpServletResponse.addCookie(cookie_iguserid); //Cookie cookie_igpassword = new Cookie ("igpassword", encryptedPassword.replaceAll("=", "IGEQ")); Cookie cookie_igpassword = new Cookie("igpassword", encryptedPasswordAsBase64); cookie_igpassword.setPath("/"); cookie_igpassword.setMaxAge(cmsCookieTimeout); httpServletResponse.addCookie(cookie_igpassword); //logger.info(encryptedName + "=" + userName); //logger.info("After attribute:" + servletContext.getAttribute(encryptedName)); } } catch (Exception e) { logger.error("Error: " + e.getMessage(), e); } //END TEST String logUserName = userName; if (logUserName == null || logUserName.equals("") && user != null) logUserName = user.getName(); if (logUserName == null || logUserName.equals("")) logUserName = authenticatedUserName; if (logUserName == null || logUserName.equals("")) logUserName = "Unknown"; NotificationMessage notificationMessage = new NotificationMessage("Login success:", "Authentication", logUserName, NotificationMessage.AUTHENTICATION_SUCCESS, "" + authenticatedUserName, "name"); TransactionHistoryController.getController().create(notificationMessage); if (successLoginBaseUrl != null && !URL.startsWith(successLoginBaseUrl)) { checkSuccessRedirect(request, response, URL); } else { fc.doFilter(request, response); return; } } else { if (userName != null && !userName.equals("")) { NotificationMessage notificationMessage = new NotificationMessage("Login failed:", "Authentication", userName, NotificationMessage.AUTHENTICATION_FAILED, "" + userName, "name"); TransactionHistoryController.getController().create(notificationMessage); } } } catch (Exception e) { logger.error("Error authenticating user:" + e.getMessage(), e); httpServletRequest.setAttribute("error", new Exception( "Error in authentication filter - look at the server error log (usually catalina.out) for reason but the most common one is problem connecting to the database or a faulty connection user or limited access for that account.")); httpServletResponse.sendError(500); return; } }
From source file:org.infoglue.deliver.applications.actions.ExtranetLoginAction.java
private void handleCookies() throws Exception { DesEncryptionHelper encHelper = new DesEncryptionHelper(); String userName = this.getRequest().getParameter("j_username"); String encryptedName = encHelper.encrypt(userName); String password = this.getRequest().getParameter("j_password"); String encryptedPassword = encHelper.encrypt(password); String encryptedNameAsBase64 = Base64.encodeBase64URLSafeString(encryptedName.getBytes("utf-8")); String encryptedPasswordAsBase64 = Base64.encodeBase64URLSafeString(encryptedPassword.getBytes("utf-8")); //logger.info("encryptedName:" + encryptedName); //logger.info("encryptedPassword:" + encryptedPassword); try {/* w ww. j av a2 s .co m*/ String cmsBaseUrl = CmsPropertyHandler.getCmsFullBaseUrl(); //logger.info("cmsBaseUrl:" + cmsBaseUrl); String[] parts = cmsBaseUrl.split("/"); cmsBaseUrl = "/" + parts[parts.length - 1]; //logger.info("used cmsBaseUrl:" + cmsBaseUrl); ServletContext servletContext = ActionContext.getServletContext().getContext(cmsBaseUrl); //logger.info("servletContext:" + servletContext.getServletContextName() + ":" + servletContext.getServletNames()); if (servletContext == null) { logger.error("Could not autologin to CMS. Set cross context = true in Tomcat config."); } else { servletContext.setAttribute(encryptedName, userName); } //logger.info(encryptedName + "=" + userName); //logger.info("After attribute:" + servletContext.getAttribute(encryptedName)); } catch (Exception e) { logger.error("Error: " + e.getMessage(), e); } int cmsCookieTimeout = 1800; //30 minutes default String cmsCookieTimeoutString = null; //CmsPropertyHandler.getCmsCookieTimeout(); if (cmsCookieTimeoutString != null) { try { cmsCookieTimeout = Integer.parseInt(cmsCookieTimeoutString.trim()); } catch (Exception e) { } } try { //Cookie cookie_iguserid = new Cookie("iguserid", encryptedName.replaceAll("=", "IGEQ")); Cookie cookie_iguserid = new Cookie("iguserid", encryptedNameAsBase64); cookie_iguserid.setPath("/"); cookie_iguserid.setMaxAge(cmsCookieTimeout); this.getResponse().addCookie(cookie_iguserid); //Cookie cookie_igpassword = new Cookie ("igpassword", encryptedPassword.replaceAll("=", "IGEQ")); Cookie cookie_igpassword = new Cookie("igpassword", encryptedPasswordAsBase64); cookie_igpassword.setPath("/"); cookie_igpassword.setMaxAge(cmsCookieTimeout); this.getResponse().addCookie(cookie_igpassword); } catch (Exception e) { logger.error("Could not set cookies:" + e.getMessage(), e); } //END CMS COOKIE if (storeUserInfoCookie == null || !storeUserInfoCookie.equalsIgnoreCase("true")) return; boolean enableExtranetCookies = getEnableExtranetCookies(); int extranetCookieTimeout = 43200; //30 days default String extranetCookieTimeoutString = CmsPropertyHandler.getExtranetCookieTimeout(); if (extranetCookieTimeoutString != null) { try { extranetCookieTimeout = Integer.parseInt(extranetCookieTimeoutString.trim()); } catch (Exception e) { } } if (enableExtranetCookies) { //Cookie cookie_userid = new Cookie("igextranetuserid", encryptedName); Cookie cookie_userid = new Cookie("igextranetuserid", encryptedNameAsBase64); cookie_userid.setMaxAge(30 * 24 * 60 * 60); //30 days this.getResponse().addCookie(cookie_userid); //Cookie cookie_password = new Cookie ("igextranetpassword", encryptedPassword); Cookie cookie_password = new Cookie("igextranetpassword", encryptedPasswordAsBase64); cookie_password.setMaxAge(30 * 24 * 60 * 60); //30 days this.getResponse().addCookie(cookie_password); } }
From source file:org.intermine.webservice.server.JWTBuilder.java
/** * Issue a token for the given subject and email address. * * This method has restricted visibility to recognise the fact that it can issue * inconsistent tokens (bad user names and email addresses) as well as the fact that * it is capable of issuing expired tokens. Do not use this method in production code - use * <code>issueToken(Profile, int)</code> * * @param subject The subject of the token * @param email The subject's email/*from ww w . j av a2s . c o m*/ * @param absoluteExpiry The absolute timestamp to use as the 'exp' claim in milliseconds. * @return A signed JWT * @throws InvalidKeyException If the private key is not valid. * @throws SignatureException If we cannot sign the token. */ String issueToken(String subject, String email, long absoluteExpiry) throws InvalidKeyException, SignatureException { Map<String, Object> header = new HashMap<String, Object>(); header.put("alg", algorithm.name()); header.put("typ", "JWT"); Map<String, Object> claims = new HashMap<String, Object>(); claims.put("sub", subject); claims.put("iss", issuer); claims.put("exp", (absoluteExpiry / 1000)); claims.put("iat", (System.currentTimeMillis() / 1000)); claims.put("http://wso2.org/claims/emailaddress", email); String toSign = encodeContent(header, claims); byte[] signature = sign(toSign); return toSign + "." + Base64.encodeBase64URLSafeString(signature); }
From source file:org.intermine.webservice.server.JWTBuilder.java
private String encodeContent(Map<String, Object> header, Map<String, Object> claims) { String toSign = String.format("%s.%s", Base64.encodeBase64URLSafeString(new JSONObject(header).toString().getBytes()), Base64.encodeBase64URLSafeString(new JSONObject(claims).toString().getBytes())); return toSign; }
From source file:org.jahia.modules.external.test.db.GenericDatabaseDataSource.java
@Override protected String getRowID(ResultSet rs, List<String> primaryKeys) throws SQLException { String val = null; if (primaryKeys.size() == 1) { val = rs.getString(primaryKeys.get(0)); if (val != null) { val = Base64.encodeBase64URLSafeString(val.getBytes(Charsets.UTF_8)); }/* w w w .j a v a2 s . com*/ } else { StringBuilder buff = new StringBuilder(); for (String col : primaryKeys) { if (buff.length() > 0) { buff.append("\n"); } buff.append(rs.getString(col)); } val = Base64.encodeBase64URLSafeString(buff.toString().getBytes(Charsets.UTF_8)); } return val; }