private boolean isSessionInvalid(HttpServletRequest httpServletRequest) { boolean sessionInValid = (httpServletRequest.getRequestedSessionId() != null) && !httpServletRequest.isRequestedSessionIdValid(); // System.out.println(httpServletRequest.isRequestedSessionIdValid()); return sessionInValid; }
public ReturnStatus login(String Auth, HttpServletRequest req, HttpSession session) { System.out.println("login"); String[] result = decodeToken(Auth); System.out.println("login, result = " + result[0]); if (result[0].equals("OK")) { System.out.println("login : "******" / password = "******"user", req.getRemoteUser()); } catch (ServletException e) { System.out.println("login ServletException"); return new ReturnStatus(false, "login ServletException" + e.getMessage()); } System.out.println("Login OK, remoteuser = "******"login, RequestedSessionId = " + req.getRequestedSessionId()); System.out.println("Login OK"); return new ReturnStatus(true, getroles(result[1])); } else { System.out.println("user niet gevonden (null)"); return new ReturnStatus(false, "user niet gevonden (null)"); } } else { System.out.println("invalid"); return new ReturnStatus(false, result[1]); } }
public Object authorize(AbstractSecurityContext context) throws Exception { startAuthorization(context); HttpGraniteContext graniteContext = (HttpGraniteContext) GraniteManager.getCurrentInstance(); HttpServletRequest httpRequest = graniteContext.getRequest(); Request request = getRequest(httpRequest); Session session = request.getSessionInternal(); request.setAuthType(session.getAuthType()); request.setUserPrincipal(session.getPrincipal()); if (context.getDestination().isSecured()) { Principal principal = getPrincipal(httpRequest); if (principal == null) { if (httpRequest.getRequestedSessionId() != null) { HttpSession httpSession = httpRequest.getSession(false); if (httpSession == null || httpRequest.getRequestedSessionId().equals(httpSession.getId())) throw SecurityServiceException.newSessionExpiredException("Session expired"); } throw SecurityServiceException.newNotLoggedInException("User not logged in"); } Realm realm = getRealm(httpRequest); boolean accessDenied = true; for (String role : context.getDestination().getRoles()) { if (realm.hasRole(principal, role)) { accessDenied = false; break; } } if (accessDenied) throw SecurityServiceException.newAccessDeniedException("User not in required role"); } try { return endAuthorization(context); } catch (InvocationTargetException e) { for (Throwable t = e; t != null; t = t.getCause()) { // Don't create a dependency to javax.ejb in SecurityService... if (t instanceof SecurityException || "javax.ejb.EJBAccessException".equals(t.getClass().getName())) throw SecurityServiceException.newAccessDeniedException(t.getMessage()); } throw e; } }
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception { response.addHeader("Access-Control-Allow-Origin", "*"); logger.info("SESSION ID:" + request.getRequestedSessionId()); SystemResponse systemResponse = ImergeFromHyperspace.dontKnowWhereShipIs(); ModelAndView modelAndView = new ModelAndView(new SystemView()); modelAndView.addObject(SystemView.JSON_ROOT, systemResponse); logger.info(modelAndView); return modelAndView; }
public URL getUrl(HttpServletRequest req) throws IOException { String servletPath = req.getServletPath(); String selectedServerFullPath = getServerAddress(servletPath); String queryString = req.getQueryString(); String newUrl = ""; HttpSession session = req.getSession(false); newUrl = selectedServerFullPath + servletPath; if (req.getRequestedSessionId() != null) newUrl = newUrl + ";jsessionid=" + req.getRequestedSessionId(); if (queryString != null) newUrl = newUrl + "?" + queryString; // if (session != null) newUrl = newUrl + ";jsessionid=" + session.getId(); return new URL(newUrl); }
@Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.setContentType("text/plain"); PrintWriter pw = resp.getWriter(); String sessionId = req.getRequestedSessionId(); if (sessionId == null) { sessionId = "none"; } pw.write(sessionId); }
public boolean login(String username, String password) { Admin admin = getAdminDao().getAdminByUsername(username); if (admin != null && admin.getPassword().equals(Tool.getMD5String(password))) { ActionContext.getContext().getSession().put(Admin.ID, admin.getId()); ActionContext.getContext().getSession().put(Admin.USERNAME, admin.getUsername()); ActionContext.getContext().getSession().put(Admin.Admin, admin); HttpServletRequest request = ServletActionContext.getRequest(); ActionContext.getContext().getSession().put("jsessionid", request.getRequestedSessionId()); logger.info("username: "******" isLogin: "******"username: "******" isLogin: " + false); return false; } }
/** * 获得请求的session id,但是HttpServletRequest#getRequestedSessionId()方法有一些问题。 * 当存在部署路径的时候,会获取到根路径下的jsessionid。 * * @see HttpServletRequest#getRequestedSessionId() * @param request * @return */ public static String getRequestedSessionId(HttpServletRequest request) { String sid = request.getRequestedSessionId(); String ctx = request.getContextPath(); // 如果session id是从url中获取,或者部署路径为空,那么是在正确的。 if (request.isRequestedSessionIdFromURL() || StringUtils.isBlank(ctx)) { return sid; } else { // 手动从cookie获取 Cookie cookie = CookieUtils.getCookie(request, "JSESSIONID"); if (cookie != null) { return cookie.getValue(); } else { return null; } } }
/** * Construct a message ID for the request. * * @return the message ID to use */ @Nonnull protected String getMessageID() { HttpServletRequest request = getHttpServletRequest(); String timeString = StringSupport.trimOrNull(request.getParameter(TIME_PARAM)); // If both a timestamp and session ID are available, construct a pseudo message ID // by combining them. Otherwise return a generated one. if (timeString != null) { String sessionID = request.getRequestedSessionId(); if (sessionID != null) { return "_" + sessionID + '!' + timeString; } else { return idGenerator.generateIdentifier(); } } else { return idGenerator.generateIdentifier(); } }
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception { response.addHeader("Access-Control-Allow-Origin", "*"); System.out.println("SESSION ID:" + request.getRequestedSessionId()); /* HttpSession httpSession = request.getSession(); UUID idOne = UUID.randomUUID(); httpSession.setAttribute(FIRST_ACCESS, idOne.toString()); System.out.println(FIRST_ACCESS+":"+idOne.toString()); log.info(FIRST_ACCESS+":"+idOne.toString()); UserDao userDao = new UserDao(); User user = new User(); user.setPassword(idOne.toString()); user.setUser_Status(UserStatus.candidate1); user.setFirstName("NONE"); user.setLastName("NONE"); user.setEmailAddress("*****@*****.**"); userDao.createUser(user); */ FirstAccessResponse firstAccessResponse = new FirstAccessResponse(); QuestionDao questionDao = new QuestionDao(); List<Integer> questionGroupList = questionDao.questionGroupCollecton(); Integer numberOfQuestions = questionDao.numberOfQuestions(); int questionNumber = (int) Math.floor(Math.random() * numberOfQuestions); int listNumber = questionGroupList.get(questionNumber); // httpSession.setAttribute(QUESTION_NUMBER, listNumber); // firstAccessResponse.setKey(idOne.toString()); firstAccessResponse.setQuestionNumber(listNumber); firstAccessResponse.setQuestionList(questionDao.readQuestion(listNumber)); int secondQuestionNumber1 = (int) Math.floor(Math.random() * 100); int secondQuestionNumber2 = (int) Math.floor(Math.random() * 100); String secondQuestion = secondQuestionNumber1 + "+" + secondQuestionNumber2; firstAccessResponse.setSecondQuestion(secondQuestion); ModelAndView modelAndView = new ModelAndView(new FirstAccessView()); modelAndView.addObject(FirstAccessView.JSON_ROOT, firstAccessResponse); System.out.println(modelAndView); return modelAndView; }
/** * 记录访问日志 [username][jsessionid][ip][accept][UserAgent][url][params][Referer] * * @param request http请求 */ public static void logAccess(HttpServletRequest request) { String username = getUsername(); String jsessionId = request.getRequestedSessionId(); String ip = IpUtils.getIpAddr(request); String accept = request.getHeader("accept"); String userAgent = request.getHeader("User-Agent"); String url = request.getRequestURI(); String params = getParams(request); String headers = getHeaders(request); StringBuilder s = new StringBuilder(); s.append(getBlock(username)); s.append(getBlock(jsessionId)); s.append(getBlock(ip)); s.append(getBlock(accept)); s.append(getBlock(userAgent)); s.append(getBlock(url)); s.append(getBlock(params)); s.append(getBlock(headers)); s.append(getBlock(request.getHeader("Referer"))); getAccessLog().info(s.toString()); }
@Override protected void doFilterInternal( HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { response.setDateHeader("Expires", 0L); response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate"); response.addHeader("Cache-Control", "post-check=0, pre-check=0"); response.setHeader("Pragma", "no-cache"); response.setContentType("image/jpeg"); String id = request.getRequestedSessionId(); BufferedImage bi = JCaptcha.captchaService.getImageChallengeForID(id); ServletOutputStream out = response.getOutputStream(); ImageIO.write(bi, "jpg", out); try { out.flush(); } finally { out.close(); } }
protected void doFilter( HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws IOException, ServletException { if (!isEnabled()) { filterChain.doFilter(request, response); return; } // Look for the rate tracker for this request. RateTracker tracker = (RateTracker) request.getAttribute(__TRACKER); if (tracker == null) { // This is the first time we have seen this request. if (LOG.isDebugEnabled()) LOG.debug("Filtering {}", request); // Get a rate tracker associated with this request, and record one hit. tracker = getRateTracker(request); // Calculate the rate and check it is over the allowed limit final boolean overRateLimit = tracker.isRateExceeded(System.currentTimeMillis()); // Pass it through if we are not currently over the rate limit. if (!overRateLimit) { if (LOG.isDebugEnabled()) LOG.debug("Allowing {}", request); doFilterChain(filterChain, request, response); return; } // We are over the limit. // So either reject it, delay it or throttle it. long delayMs = getDelayMs(); boolean insertHeaders = isInsertHeaders(); switch ((int) delayMs) { case -1: { // Reject this request. LOG.warn( "DOS ALERT: Request rejected ip={}, session={}, user={}", request.getRemoteAddr(), request.getRequestedSessionId(), request.getUserPrincipal()); if (insertHeaders) response.addHeader("DoSFilter", "unavailable"); response.sendError(getTooManyCode()); return; } case 0: { // Fall through to throttle the request. LOG.warn( "DOS ALERT: Request throttled ip={}, session={}, user={}", request.getRemoteAddr(), request.getRequestedSessionId(), request.getUserPrincipal()); request.setAttribute(__TRACKER, tracker); break; } default: { // Insert a delay before throttling the request, // using the suspend+timeout mechanism of AsyncContext. LOG.warn( "DOS ALERT: Request delayed={}ms, ip={}, session={}, user={}", delayMs, request.getRemoteAddr(), request.getRequestedSessionId(), request.getUserPrincipal()); if (insertHeaders) response.addHeader("DoSFilter", "delayed"); request.setAttribute(__TRACKER, tracker); AsyncContext asyncContext = request.startAsync(); if (delayMs > 0) asyncContext.setTimeout(delayMs); asyncContext.addListener(new DoSTimeoutAsyncListener()); return; } } } if (LOG.isDebugEnabled()) LOG.debug("Throttling {}", request); // Throttle the request. boolean accepted = false; try { // Check if we can afford to accept another request at this time. accepted = _passes.tryAcquire(getMaxWaitMs(), TimeUnit.MILLISECONDS); if (!accepted) { // We were not accepted, so either we suspend to wait, // or if we were woken up we insist or we fail. Boolean throttled = (Boolean) request.getAttribute(__THROTTLED); long throttleMs = getThrottleMs(); if (throttled != Boolean.TRUE && throttleMs > 0) { int priority = getPriority(request, tracker); request.setAttribute(__THROTTLED, Boolean.TRUE); if (isInsertHeaders()) response.addHeader("DoSFilter", "throttled"); AsyncContext asyncContext = request.startAsync(); request.setAttribute(_suspended, Boolean.TRUE); if (throttleMs > 0) asyncContext.setTimeout(throttleMs); asyncContext.addListener(_listeners[priority]); _queues[priority].add(asyncContext); if (LOG.isDebugEnabled()) LOG.debug("Throttled {}, {}ms", request, throttleMs); return; } Boolean resumed = (Boolean) request.getAttribute(_resumed); if (resumed == Boolean.TRUE) { // We were resumed, we wait for the next pass. _passes.acquire(); accepted = true; } } // If we were accepted (either immediately or after throttle)... if (accepted) { // ...call the chain. if (LOG.isDebugEnabled()) LOG.debug("Allowing {}", request); doFilterChain(filterChain, request, response); } else { // ...otherwise fail the request. if (LOG.isDebugEnabled()) LOG.debug("Rejecting {}", request); if (isInsertHeaders()) response.addHeader("DoSFilter", "unavailable"); response.sendError(getTooManyCode()); } } catch (InterruptedException e) { LOG.ignore(e); response.sendError(getTooManyCode()); } finally { if (accepted) { try { // Wake up the next highest priority request. for (int p = _queues.length - 1; p >= 0; --p) { AsyncContext asyncContext = _queues[p].poll(); if (asyncContext != null) { ServletRequest candidate = asyncContext.getRequest(); Boolean suspended = (Boolean) candidate.getAttribute(_suspended); if (suspended == Boolean.TRUE) { if (LOG.isDebugEnabled()) LOG.debug("Resuming {}", request); candidate.setAttribute(_resumed, Boolean.TRUE); asyncContext.dispatch(); break; } } } } finally { _passes.release(); } } } }
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); response.setCharacterEncoding("UTF-8"); PrintWriter writer = response.getWriter(); String message = "Bilinmeyen Bir Browser Kullanýyorsunuz."; if (request.getHeader("User-Agent").indexOf("Firefox") != -1) message = "Siz Firefox Kullanýcýsýnýz"; if (request.getHeader("User-Agent").indexOf("MSIE") != -1) message = "Siz Microsoft Internet Explorer Kullanýcýsýnýz"; if (request.getHeader("User-Agent").indexOf("Chrome") != -1) message = "Siz Google Chrome Kullanýcýsýnýz"; writer.println( "<!DOCTYPE html 4.0>" + "<html>" + "<head><title>requestHeadaer</title></head>" + "<body bgcolor = \"pink\" style=\"text-align = center;\">" + message + "<form>" + "<table border=2>" + "<tr>" + "<td>" + "<b>RequestCharacterEncoding : </b>" + request.getCharacterEncoding() + " ---- <b>RequestContentLength : </b>" + request.getContentLength() + "<p><b>RequestContentType : </b>" + request.getContentType() + " ---- <b>RequestContextPath : </b>" + request.getContextPath() + "<p><b>RequestLocalAddress : </b>" + request.getLocalAddr() + " ---- <b>RequestLocalName : </b>" + request.getLocalName() + "<p><b>RequestLocalPort : </b>" + request.getLocalPort() + " ---- <b>RequestMethod : </b>" + request.getMethod() + "<p><b>RequestPathInfo : </b>" + request.getPathInfo() + " ---- <b>RequestPathTranslated : </b>" + request.getPathTranslated() + "<p><b>RequestProtocol : </b>" + request.getProtocol() + " ---- <b>RequestQueryString : </b>" + request.getQueryString() + "<p><b>RequestSessionID : </b>" + request.getRequestedSessionId() + " ---- <b>RequestServerName : </b>" + request.getServerName() + "<p><b>RequestServerPort : </b>" + request.getServerPort() + " ---- <b>RequestPath : </b>" + request.getServletPath() + "<p><b>RequestURL : </b>" + request.getRequestURL() + " ---- <b>RequestSession : </b>" + request.getSession() + "<td>" + "<table border = 2>"); Enumeration<String> headerNames = request.getHeaderNames(); while (headerNames.hasMoreElements()) { String headerName = headerNames.nextElement(); String headerValues = request.getHeader(headerName); writer.println("<tr><th>" + headerName + "<td><i>" + headerValues + "</i></tr>"); } writer.println("</table></td></tr></table></body></html>"); }
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { if (filterConfig == null) return; StringWriter sw = new StringWriter(); PrintWriter writer = new PrintWriter(sw); writer.println( (new StringBuilder("Request Received at ")) .append(new Timestamp(System.currentTimeMillis())) .toString()); writer.println( (new StringBuilder(" characterEncoding=")) .append(request.getCharacterEncoding()) .toString()); writer.println( (new StringBuilder(" contentLength=")).append(request.getContentLength()).toString()); writer.println( (new StringBuilder(" contentType=")).append(request.getContentType()).toString()); writer.println( (new StringBuilder(" locale=")).append(request.getLocale()).toString()); writer.print(" locales="); Enumeration locales = request.getLocales(); boolean first = true; Locale locale; for (; locales.hasMoreElements(); writer.print(locale.toString())) { locale = (Locale) locales.nextElement(); if (first) first = false; else writer.print(", "); } writer.println(); for (Enumeration names = request.getParameterNames(); names.hasMoreElements(); writer.println()) { String name = (String) names.nextElement(); writer.print((new StringBuilder(" parameter=")).append(name).append("=").toString()); String values[] = request.getParameterValues(name); for (int i = 0; i < values.length; i++) { if (i > 0) writer.print(", "); writer.print(values[i]); } } writer.println( (new StringBuilder(" protocol=")).append(request.getProtocol()).toString()); writer.println( (new StringBuilder(" remoteAddr=")).append(request.getRemoteAddr()).toString()); writer.println( (new StringBuilder(" remoteHost=")).append(request.getRemoteHost()).toString()); writer.println( (new StringBuilder(" scheme=")).append(request.getScheme()).toString()); writer.println( (new StringBuilder(" serverName=")).append(request.getServerName()).toString()); writer.println( (new StringBuilder(" serverPort=")).append(request.getServerPort()).toString()); writer.println( (new StringBuilder(" isSecure=")).append(request.isSecure()).toString()); if (request instanceof HttpServletRequest) { writer.println("---------------------------------------------"); HttpServletRequest hrequest = (HttpServletRequest) request; writer.println( (new StringBuilder(" contextPath=")).append(hrequest.getContextPath()).toString()); Cookie cookies[] = hrequest.getCookies(); if (cookies == null) cookies = new Cookie[0]; for (int i = 0; i < cookies.length; i++) writer.println( (new StringBuilder(" cookie=")) .append(cookies[i].getName()) .append("=") .append(cookies[i].getValue()) .toString()); String name; String value; for (Enumeration names = hrequest.getHeaderNames(); names.hasMoreElements(); writer.println( (new StringBuilder(" header=")) .append(name) .append("=") .append(value) .toString())) { name = (String) names.nextElement(); value = hrequest.getHeader(name); } writer.println( (new StringBuilder(" method=")).append(hrequest.getMethod()).toString()); writer.println( (new StringBuilder(" pathInfo=")).append(hrequest.getPathInfo()).toString()); writer.println( (new StringBuilder(" queryString=")).append(hrequest.getQueryString()).toString()); writer.println( (new StringBuilder(" remoteUser="******"requestedSessionId=")) .append(hrequest.getRequestedSessionId()) .toString()); writer.println( (new StringBuilder(" requestURI=")).append(hrequest.getRequestURI()).toString()); writer.println( (new StringBuilder(" servletPath=")).append(hrequest.getServletPath()).toString()); } writer.println("============================================="); writer.flush(); filterConfig.getServletContext().log(sw.getBuffer().toString()); chain.doFilter(request, response); }
protected Principal checkSessionAuthentication(final HttpServletRequest request) throws FrameworkException { String requestedSessionId = request.getRequestedSessionId(); HttpSession session = request.getSession(false); boolean sessionValid = false; if (requestedSessionId == null) { // No session id requested => create new session AuthHelper.newSession(request); // we just created a totally new session, there can't // be a user with this session ID, so don't search. return null; } else { // Existing session id, check if we have an existing session if (session != null) { if (session.getId().equals(requestedSessionId)) { if (AuthHelper.isSessionTimedOut(session)) { sessionValid = false; // remove invalid session ID from user invalidateSessionId(requestedSessionId); } else { sessionValid = true; } } } else { // No existing session, create new session = AuthHelper.newSession(request); // remove invalid session ID from user invalidateSessionId(requestedSessionId); } } if (sessionValid) { final Principal user = AuthHelper.getPrincipalForSessionId(session.getId()); logger.log( Level.FINE, "Valid session found: {0}, last accessed {1}, authenticated with user {2}", new Object[] {session, session.getLastAccessedTime(), user}); return user; } else { final Principal user = AuthHelper.getPrincipalForSessionId(requestedSessionId); logger.log( Level.FINE, "Invalid session: {0}, last accessed {1}, authenticated with user {2}", new Object[] {session, (session != null ? session.getLastAccessedTime() : ""), user}); if (user != null) { AuthHelper.doLogout(request, user); } try { request.logout(); request.changeSessionId(); } catch (Throwable t) { } } return null; }
@Override public void onTrigger(final ProcessContext context, final ProcessSession session) throws ProcessException { try { if (!initialized.get()) { initializeServer(context); } } catch (Exception e) { context.yield(); throw new ProcessException("Failed to initialize the server", e); } final HttpRequestContainer container = containerQueue.poll(); if (container == null) { return; } final long start = System.nanoTime(); final HttpServletRequest request = container.getRequest(); FlowFile flowFile = session.create(); try { flowFile = session.importFrom(request.getInputStream(), flowFile); } catch (final IOException e) { getLogger() .error( "Failed to receive content from HTTP Request from {} due to {}", new Object[] {request.getRemoteAddr(), e}); session.remove(flowFile); return; } final String charset = request.getCharacterEncoding() == null ? context.getProperty(URL_CHARACTER_SET).getValue() : request.getCharacterEncoding(); final String contextIdentifier = UUID.randomUUID().toString(); final Map<String, String> attributes = new HashMap<>(); try { putAttribute(attributes, HTTPUtils.HTTP_CONTEXT_ID, contextIdentifier); putAttribute(attributes, "mime.type", request.getContentType()); putAttribute(attributes, "http.servlet.path", request.getServletPath()); putAttribute(attributes, "http.context.path", request.getContextPath()); putAttribute(attributes, "http.method", request.getMethod()); putAttribute(attributes, "http.local.addr", request.getLocalAddr()); putAttribute(attributes, HTTPUtils.HTTP_LOCAL_NAME, request.getLocalName()); if (request.getQueryString() != null) { putAttribute( attributes, "http.query.string", URLDecoder.decode(request.getQueryString(), charset)); } putAttribute(attributes, HTTPUtils.HTTP_REMOTE_HOST, request.getRemoteHost()); putAttribute(attributes, "http.remote.addr", request.getRemoteAddr()); putAttribute(attributes, "http.remote.user", request.getRemoteUser()); putAttribute(attributes, HTTPUtils.HTTP_REQUEST_URI, request.getRequestURI()); putAttribute(attributes, "http.request.url", request.getRequestURL().toString()); putAttribute(attributes, "http.auth.type", request.getAuthType()); putAttribute(attributes, "http.requested.session.id", request.getRequestedSessionId()); if (request.getDispatcherType() != null) { putAttribute(attributes, "http.dispatcher.type", request.getDispatcherType().name()); } putAttribute(attributes, "http.character.encoding", request.getCharacterEncoding()); putAttribute(attributes, "http.locale", request.getLocale()); putAttribute(attributes, "http.server.name", request.getServerName()); putAttribute(attributes, HTTPUtils.HTTP_PORT, request.getServerPort()); final Enumeration<String> paramEnumeration = request.getParameterNames(); while (paramEnumeration.hasMoreElements()) { final String paramName = paramEnumeration.nextElement(); final String value = request.getParameter(paramName); attributes.put("http.param." + paramName, value); } final Cookie[] cookies = request.getCookies(); if (cookies != null) { for (final Cookie cookie : cookies) { final String name = cookie.getName(); final String cookiePrefix = "http.cookie." + name + "."; attributes.put(cookiePrefix + "value", cookie.getValue()); attributes.put(cookiePrefix + "domain", cookie.getDomain()); attributes.put(cookiePrefix + "path", cookie.getPath()); attributes.put(cookiePrefix + "max.age", String.valueOf(cookie.getMaxAge())); attributes.put(cookiePrefix + "version", String.valueOf(cookie.getVersion())); attributes.put(cookiePrefix + "secure", String.valueOf(cookie.getSecure())); } } final String queryString = request.getQueryString(); if (queryString != null) { final String[] params = URL_QUERY_PARAM_DELIMITER.split(queryString); for (final String keyValueString : params) { final int indexOf = keyValueString.indexOf("="); if (indexOf < 0) { // no =, then it's just a key with no value attributes.put("http.query.param." + URLDecoder.decode(keyValueString, charset), ""); } else { final String key = keyValueString.substring(0, indexOf); final String value; if (indexOf == keyValueString.length() - 1) { value = ""; } else { value = keyValueString.substring(indexOf + 1); } attributes.put( "http.query.param." + URLDecoder.decode(key, charset), URLDecoder.decode(value, charset)); } } } } catch (final UnsupportedEncodingException uee) { throw new ProcessException( "Invalid character encoding", uee); // won't happen because charset has been validated } final Enumeration<String> headerNames = request.getHeaderNames(); while (headerNames.hasMoreElements()) { final String headerName = headerNames.nextElement(); final String headerValue = request.getHeader(headerName); putAttribute(attributes, "http.headers." + headerName, headerValue); } final Principal principal = request.getUserPrincipal(); if (principal != null) { putAttribute(attributes, "http.principal.name", principal.getName()); } final X509Certificate certs[] = (X509Certificate[]) request.getAttribute("javax.servlet.request.X509Certificate"); final String subjectDn; if (certs != null && certs.length > 0) { final X509Certificate cert = certs[0]; subjectDn = cert.getSubjectDN().getName(); final String issuerDn = cert.getIssuerDN().getName(); putAttribute(attributes, HTTPUtils.HTTP_SSL_CERT, subjectDn); putAttribute(attributes, "http.issuer.dn", issuerDn); } else { subjectDn = null; } flowFile = session.putAllAttributes(flowFile, attributes); final HttpContextMap contextMap = context.getProperty(HTTP_CONTEXT_MAP).asControllerService(HttpContextMap.class); final boolean registered = contextMap.register( contextIdentifier, request, container.getResponse(), container.getContext()); if (!registered) { getLogger() .warn( "Received request from {} but could not process it because too many requests are already outstanding; responding with SERVICE_UNAVAILABLE", new Object[] {request.getRemoteAddr()}); try { container.getResponse().setStatus(Status.SERVICE_UNAVAILABLE.getStatusCode()); container.getResponse().flushBuffer(); container.getContext().complete(); } catch (final Exception e) { getLogger() .warn( "Failed to respond with SERVICE_UNAVAILABLE message to {} due to {}", new Object[] {request.getRemoteAddr(), e}); } session.remove(flowFile); return; } final long receiveMillis = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - start); session .getProvenanceReporter() .receive( flowFile, HTTPUtils.getURI(attributes), "Received from " + request.getRemoteAddr() + (subjectDn == null ? "" : " with DN=" + subjectDn), receiveMillis); session.transfer(flowFile, REL_SUCCESS); getLogger() .info( "Transferring {} to 'success'; received from {}", new Object[] {flowFile, request.getRemoteAddr()}); }
public String getRequestedSessionId() { return request.getRequestedSessionId(); }
private void doPortalAuthentication(HttpServletRequest request) { // Clear out the existing session for the user if they have one String targetUid = null; String originalUid = null; String originalEventSessionId = null; boolean swap = false; String swapperProfile = null; final String requestedSessionId = request.getRequestedSessionId(); if (request.isRequestedSessionIdValid()) { if (logger.isDebugEnabled()) { logger.debug("doPortalAuthentication for valid requested session id " + requestedSessionId); } try { HttpSession s = request.getSession(false); if (s != null) { // Check if this is a swapped user hitting the Login servlet originalUid = this.identitySwapperManager.getOriginalUsername(s); } // No original person in session so check for swap request if (originalUid == null) { targetUid = this.identitySwapperManager.getTargetUsername(s); if (targetUid != null) { final IPerson person = personManager.getPerson(request); originalUid = person.getName(); swap = true; swapperProfile = identitySwapperManager.getTargetProfile(s); } } // Original person in session so this must be an un-swap request else { if (logger.isDebugEnabled()) { logger.trace( "This is an un-swap request swapping back from impersonated " + targetUid + " to original user " + originalUid + "."); } final IPerson person = personManager.getPerson(request); targetUid = person.getName(); } if (s != null) { if (logger.isDebugEnabled()) { logger.debug("Invalidating the impersonated session in un-swapping."); } s.invalidate(); } } catch (IllegalStateException ise) { // ISE indicates session was already invalidated. // This is fine. This servlet trying to guarantee that the session has been invalidated; // it doesn't have to insist that it is the one that invalidated it. if (logger.isTraceEnabled()) { logger.trace("LoginServlet attempted to invalidate an already invalid session.", ise); } } } else { if (logger.isTraceEnabled()) { logger.trace( "Requested session id " + requestedSessionId + " was not valid " + "so no attempt to apply swapping rules."); } } // Create the user's session HttpSession s = request.getSession(true); IPerson person = null; try { final HashMap<String, String> principals; final HashMap<String, String> credentials; // Get the person object associated with the request person = personManager.getPerson(request); // If doing an identity swap if (targetUid != null && originalUid != null) { if (swap) { swapperLog.warn("Swapping identity for '" + originalUid + "' to '" + targetUid + "'"); // Track the originating user this.identitySwapperManager.setOriginalUser(s, originalUid, targetUid); // Setup the swapped person person.setUserName(targetUid); } else { swapperLog.warn( "Reverting swapped identity from '" + targetUid + "' to '" + originalUid + "'"); person.setUserName(originalUid); } // Setup the custom security context final IdentitySwapperPrincipal identitySwapperPrincipal = new IdentitySwapperPrincipal(person); final IdentitySwapperSecurityContext identitySwapperSecurityContext = new IdentitySwapperSecurityContext(identitySwapperPrincipal); person.setSecurityContext(identitySwapperSecurityContext); principals = new HashMap<String, String>(); credentials = new HashMap<String, String>(); } // Norm authN path else { // WE grab all of the principals and credentials from the request and load // them into their respective HashMaps. principals = getPropertyFromRequest(principalTokens, request); credentials = getPropertyFromRequest(credentialTokens, request); } // Attempt to authenticate using the incoming request authenticationService.authenticate(request, principals, credentials, person); } catch (Exception e) { // Log the exception logger.error("Exception authenticating the request", e); // Reset everything request.getSession(false).invalidate(); // Add the authentication failure request.getSession(true).setAttribute(LoginController.AUTH_ERROR_KEY, Boolean.TRUE); } final String requestedProfile = request.getParameter(LoginController.REQUESTED_PROFILE_KEY); if (requestedProfile != null) { final ProfileSelectionEvent event = new ProfileSelectionEvent(this, requestedProfile, person, request); this.eventPublisher.publishEvent(event); } else if (swapperProfile != null) { final ProfileSelectionEvent event = new ProfileSelectionEvent(this, swapperProfile, person, request); this.eventPublisher.publishEvent(event); } else { if (logger.isTraceEnabled()) { logger.trace("No requested or swapper profile requested so no profile selection event."); } } }
public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException { setUpApplicationContext(getServletConfig().getServletContext(), (HttpServletRequest) request); JspController cont = null; boolean sessionKeepAlive = true; try { long time = System.currentTimeMillis(); request.setAttribute(SALMON_SERVLET_KEY, this); sessionKeepAlive = request.getParameter("sessionKeepAlive") != null; if (!_replaceFactoryInit) { Props p = Props.getSystemProps(); _replaceFactoryInit = true; _replaceFactory = p.getBooleanProperty(Props.SYS_REPLACE_JSP_FACTORY, true); _cacheControllers = p.getBooleanProperty(Props.SYS_CACHE_CONTROLLERS, false); MessageLog.writeInfoMessage( "***JspServlet initialized with properties: " + Props.SYS_REPLACE_JSP_FACTORY + "=" + _replaceFactory + ", " + Props.SYS_CACHE_CONTROLLERS + "=" + _cacheControllers + ". To reset, change the System.properties file and restart the server.***", this); } // if (_replaceFactory) { // JspFactory fact = JspFactory.getDefaultFactory(); // if (fact == null || // !fact.getClass().getName().equals("com.salmonllc.jsp.engine.JspFactoryImpl")) // JspFactory.setDefaultFactory(new com.salmonllc.jsp.engine.JspFactoryImpl(fact)); // } HttpServletRequest req = (HttpServletRequest) request; HttpServletResponse res = (HttpServletResponse) response; if (sessionKeepAlive) com.salmonllc.util.MessageLog.writeInfoMessage( "JspServlet.service() keepAlive - URI=" + req.getRequestURI(), Props.LOG_LEVEL_10, this); else { notifyListeners((HttpServletRequest) request, (HttpServletResponse) response, true); com.salmonllc.util.MessageLog.writeInfoMessage( "JspServlet.service() start - URI=" + req.getRequestURI(), Props.LOG_LEVEL_10, this); } String sessID = req.getParameter(PageTag.getSessionIdentifier()); HttpSession sess = PageTag.getSession(sessID); boolean sessValid = true; if (sess == null) { sessID = req.getRequestedSessionId(); sessValid = req.isRequestedSessionIdValid(); if (!sessValid && sessionKeepAlive) return; sess = req.getSession(true); } boolean onSession = false; boolean sessExp = false; if (sessID != null && !sessValid) sess.setAttribute("AppServer_SessExp", new Boolean(true)); boolean createPage = (req.getHeader(SALMON_CREATE_PAGE_HEADER) != null); if (_replaceFactory) { Object sessToken = sess.getAttribute("AppServer_SessionToken"); if (sessToken == null) { sess.setAttribute("AppServer_SessionToken", new String("tok")); sessToken = sess.getAttribute("AppServer_SessionToken"); } synchronized (sessToken) { String sessName = "$jsp$" + com.salmonllc.jsp.tags.PageTag.generateSessionName(req); loadCachedController(sessName, sess); onSession = sess.getAttribute(sessName) != null; if (!onSession) _jspService(req, new HttpServletResponseDummy(res, null)); cont = (JspController) sess.getAttribute(sessName); generateExpireResponseHeaders(res, cont.getAddExpireHeaders()); cacheController(sessName, cont); cont.setSessionExpired(sessExp); cont.setDoPostRedirected(false); _jspService(req, res); } } else { String sessName = "$jsp$" + com.salmonllc.jsp.tags.PageTag.generateSessionName(req); String token = sessName + "$pageToken$"; try { if (!createPage) { if (sess.getAttribute(token) != null) { /* * srufle : Jun 25, 2004 4 : 26 : 38 PM * This was put in to solve a thread deadlocking issue is was encountering * * Possible enhancements include * - making vars get their values from system parameters */ int index = 0; int indexLimit = 1024; int sleepCount = 0; int sleepCountLimit = 4096; int sleepTime = 10; while (sess.getAttribute(token) != null) { index++; Thread.yield(); if (index >= (indexLimit)) { Thread.sleep(sleepTime); index = 0; sleepCount++; if (sleepCount >= sleepCountLimit) { throw (new ServletException("Thread Locked:Throwing to unlock")); } } } } sess.setAttribute(token, token); } loadCachedController(sessName, sess); onSession = sess.getAttribute(sessName) != null; if (!onSession && !createPage) { createPage(req, res, sess, getPageURL(req, res), sess.getId()); cont = (JspController) sess.getAttribute(sessName); cacheController(sessName, cont); } else cont = (JspController) sess.getAttribute(sessName); if (cont != null) { generateExpireResponseHeaders(res, cont.getAddExpireHeaders()); cont.setSessionExpired(sessExp); cont.setDoPostRedirected(false); synchronized (cont) { _jspService(req, res); } } else { String contextToken = req.getHeader(SALMON_CONTEXT_TOKEN); _jspService(req, res); if (contextToken != null) { TagContext t = (TagContext) req.getAttribute(TagContext.TAG_CONTEXT_REQ_KEY); if (t != null) sess.setAttribute(contextToken, t); } } } catch (Exception e) { if (cont == null || cont.getPortletException() == null) { if (e instanceof SocketException) { // ignore java.net.SocketException MessageLog.writeInfoMessage("SocketException would have been thrown", this); } else { MessageLog.writeErrorMessage("service", e, this); throw (new ServletException(e.getMessage())); } } } finally { if (!createPage) sess.removeAttribute(token); } } if (!sessionKeepAlive) { time = (System.currentTimeMillis() - time); if (!createPage) addPageHit(time); if (Props.getSystemProps().getBooleanProperty(Props.SYS_RECORD_PAGE_TIMERS)) recordTimerActivity(req.getRequestURI(), time, this, false); com.salmonllc.util.MessageLog.writeInfoMessage( "JspServlet.service() end - URI=" + req.getRequestURI() + " Time=" + time + " Init=" + (!onSession), Props.LOG_LEVEL_10, this); } } catch (java.net.SocketException e) { // ignore java.net.SocketException MessageLog.writeInfoMessage("SocketException would have been thrown", this); } catch (ServletException e) { if (cont == null || cont.getPortletException() == null) { com.salmonllc.util.MessageLog.writeErrorMessage("JspServlet.service()", e, this); throw (e); } } catch (IOException e) { com.salmonllc.util.MessageLog.writeErrorMessage("JspServlet.service()", e, this); throw (e); } catch (Exception e) { com.salmonllc.util.MessageLog.writeErrorMessage("JspServlet.service()", e, this); throw (new ServletException(e)); } finally { try { if (!sessionKeepAlive) notifyListeners((HttpServletRequest) request, (HttpServletResponse) response, false); } catch (Exception e) { com.salmonllc.util.MessageLog.writeErrorMessage("JspServlet.service()", e, this); throw (new ServletException(e)); } } }
public TaskHttpServletRequest(HttpServletRequest wrapping, Task task) { this.session = wrapping.getSession(); String location = wrapping.getParameter("url"); cookies = wrapping.getCookies(); characterEncoding = wrapping.getCharacterEncoding(); authType = wrapping.getAuthType(); headerNames = new Vector<String>(); headers = new MultiMap(); for (Enumeration e = wrapping.getHeaderNames(); e.hasMoreElements(); ) { String headerName = (String) e.nextElement(); for (Enumeration f = wrapping.getHeaders(headerName); f.hasMoreElements(); ) { String headerValue = (String) f.nextElement(); headers.add(headerName, headerValue); } } contextPath = wrapping.getContextPath(); pathInfo = wrapping.getPathInfo(); pathTranslated = wrapping.getPathTranslated(); remoteUser = wrapping.getRemoteUser(); // TODO check if needed requestedSessionId = wrapping.getRequestedSessionId(); // TODO check if needed userPrincipal = wrapping.getUserPrincipal(); // TODO check if needed requestedSessionIdFromCookie = wrapping.isRequestedSessionIdFromCookie(); requestedSessionIdFromURL = wrapping.isRequestedSessionIdFromURL(); requestedSessionIdValid = wrapping.isRequestedSessionIdValid(); localAddr = wrapping.getLocalAddr(); localName = wrapping.getLocalName(); localPort = wrapping.getLocalPort(); locale = wrapping.getLocale(); locales = new Vector<Locale>(); for (Enumeration e = wrapping.getLocales(); e.hasMoreElements(); locales.add((Locale) e.nextElement())) ; protocol = wrapping.getProtocol(); remoteAddr = wrapping.getRemoteAddr(); remoteHost = wrapping.getRemoteHost(); remotePort = wrapping.getRemotePort(); scheme = wrapping.getScheme(); serverName = wrapping.getServerName(); serverPort = wrapping.getServerPort(); secure = wrapping.isSecure(); // Extract the query (everything after ?) int idx = location.indexOf('?'); query = null; if (idx != -1) { query = location.substring(idx + 1); } // Extract the URI (everything before ?) uri = location; if (idx != -1) { uri = uri.substring(0, idx); } // Servlet path (same as URI?) servletPath = uri; // Extract parameters params = new Hashtable<String, String[]>(); if (query != null) { StringTokenizer t = new StringTokenizer(query, "&"); while (t.hasMoreTokens()) { String token = t.nextToken(); idx = token.indexOf('='); String name = token; String val = null; if (idx != -1) { name = token.substring(0, idx); val = token.substring(idx + 1); } else { val = ""; } String[] vals = params.get(name); if (vals == null) { vals = new String[] {val}; } else { String[] nvals = new String[vals.length + 1]; System.arraycopy(vals, 0, nvals, 0, vals.length); nvals[vals.length] = val; vals = nvals; } params.put(name, vals); } } // Initialise attributes attributes = new Hashtable<String, Object>(); // Create the URL (the URL with protocol / host / post) try { URL u = new URL(new URL(wrapping.getRequestURL().toString()), uri); url = new StringBuffer(u.toExternalForm()); } catch (MalformedURLException e) { } setAttribute(ATTR_TASK, task); }
/** * Enforce any user data constraint required by the security constraint guarding this request URI. * Return <code>true</code> if this constraint was not violated and processing should continue, or * <code>false</code> if we have created a response already. * * @param request Request we are processing * @param response Response we are creating * @param constraint Security constraint being checked * @exception IOException if an input/output error occurs */ protected boolean checkUserData( HttpRequest request, HttpResponse response, SecurityConstraint constraint) throws IOException { // Is there a relevant user data constraint? if (constraint == null) { if (debug >= 2) log(" No applicable security constraint defined"); return (true); } String userConstraint = constraint.getUserConstraint(); if (userConstraint == null) { if (debug >= 2) log(" No applicable user data constraint defined"); return (true); } if (userConstraint.equals(Constants.NONE_TRANSPORT)) { if (debug >= 2) log(" User data constraint has no restrictions"); return (true); } // Validate the request against the user data constraint if (request.getRequest().isSecure()) { if (debug >= 2) log(" User data constraint already satisfied"); return (true); } // Initialize variables we need to determine the appropriate action HttpServletRequest hrequest = (HttpServletRequest) request.getRequest(); HttpServletResponse hresponse = (HttpServletResponse) response.getResponse(); int redirectPort = request.getConnector().getRedirectPort(); // Is redirecting disabled? if (redirectPort <= 0) { if (debug >= 2) log(" SSL redirect is disabled"); hresponse.sendError(HttpServletResponse.SC_FORBIDDEN, hrequest.getRequestURI()); return (false); } // Redirect to the corresponding SSL port String protocol = "https"; String host = hrequest.getServerName(); StringBuffer file = new StringBuffer(hrequest.getRequestURI()); String requestedSessionId = hrequest.getRequestedSessionId(); if ((requestedSessionId != null) && hrequest.isRequestedSessionIdFromURL()) { file.append(";jsessionid="); file.append(requestedSessionId); } String queryString = hrequest.getQueryString(); if (queryString != null) { file.append('?'); file.append(queryString); } URL url = null; try { url = new URL(protocol, host, redirectPort, file.toString()); if (debug >= 2) log(" Redirecting to " + url.toString()); hresponse.sendRedirect(url.toString()); return (false); } catch (MalformedURLException e) { if (debug >= 2) log(" Cannot create new URL", e); hresponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, hrequest.getRequestURI()); return (false); } }
@Override protected void doFilterOnce( final HttpServletRequest request, final HttpServletResponse response, final FilterChain chain) throws IOException, ServletException { if (log.isInfoEnabled()) { final StringBuilder b = new StringBuilder(128); b.append(request.getMethod()).append(sep); b.append(request.getScheme()).append(sep); b.append(request.getServerName()).append(sep); b.append(request.getServerPort()).append(sep); // b.append(request.getRequestURL()).append(sep); b.append(request.getRequestURI()).append(sep); b.append(request.getProtocol()).append(sep); b.append(request.getContextPath()).append(sep); b.append(request.getServletPath()).append(sep); b.append(request.getPathInfo()).append(sep); b.append(request.getQueryString()).append(sep); // b.append(request.getPathTranslated()).append(sep); b.append(request.getCharacterEncoding()).append(sep); b.append(request.getContentLength()).append(sep); b.append(request.getContentType()).append(sep); final Cookie[] c = request.getCookies(); if ((c != null) && (c.length > 0)) { for (int i = 0; i < c.length; i++) { final Cookie cookie = c[i]; if (i > 0) { b.append(";"); } if (cookie != null) { b.append(cookie.getName()).append("=").append(cookie.getValue()); } } } b.append(sep); b.append(request.getLocale()).append(sep); b.append(request.getRemoteAddr()).append(sep); b.append(request.getRemoteHost()).append(sep); b.append(request.getRemoteUser()).append(sep); b.append(request.getRequestedSessionId()).append(sep); final HttpSession s = request.getSession(false); if (s != null) { b.append(s.getId()); } b.append(sep); final Principal p = request.getUserPrincipal(); if (p != null) { b.append(p.getName()); } log.info(b.toString()); } chain.doFilter(request, response); }