List of usage examples for javax.servlet ServletRequest getRequestDispatcher
public RequestDispatcher getRequestDispatcher(String path);
From source file:org.wso2.carbon.identity.entitlement.filter.EntitlementFilter.java
private void completeAuthorization(String decision, ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws EntitlementFilterException { try {/*from w w w .j a v a 2s. c om*/ if (decision.equals(EntitlementConstants.PERMIT)) { if (((HttpServletRequest) servletRequest).getRequestURI().contains("/updateCacheAuth.do")) { pepProxy.clear(); log.info("PEP cache has been updated"); servletResponse.getWriter().print("PEP cache has been updated"); } else { filterChain.doFilter(servletRequest, servletResponse); } } else if (decision.equals(EntitlementConstants.DENY)) { log.debug("User not authorized to perform the action"); servletRequest.getRequestDispatcher(authRedirectURL).forward(servletRequest, servletResponse); } else if (decision.equals(EntitlementConstants.NOT_APPLICABLE)) { log.debug("No applicable policies found"); servletRequest.getRequestDispatcher(authRedirectURL).forward(servletRequest, servletResponse); } else if (decision.equals(EntitlementConstants.INDETERMINATE)) { log.debug("Indeterminate"); servletRequest.getRequestDispatcher(authRedirectURL).forward(servletRequest, servletResponse); } else { log.error("Unrecognized decision returned from PDP"); servletRequest.getRequestDispatcher(authRedirectURL).forward(servletRequest, servletResponse); } } catch (Exception e) { log.error("Error occurred while completing authorization", e); throw new EntitlementFilterException("Error occurred while completing authorization", e); } }
From source file:dk.itst.oiosaml.sp.service.SPFilter.java
/** * Check whether the user is authenticated i.e. having session with a valid * assertion. If the user is not authenticated an <AuthnRequest> is sent to * the Login Site.//w w w . j a v a 2 s . c om * * @param request * The servletRequest * @param response * The servletResponse */ public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { if (log.isDebugEnabled()) log.debug("OIOSAML-J SP Filter invoked"); if (!(request instanceof HttpServletRequest)) { throw new RuntimeException("Not supported operation..."); } HttpServletRequest servletRequest = ((HttpServletRequest) request); Audit.init(servletRequest); if (!isFilterInitialized()) { try { Configuration conf = SAMLConfiguration.getSystemConfiguration(); setRuntimeConfiguration(conf); } catch (IllegalStateException e) { request.getRequestDispatcher("/saml/configure").forward(request, response); return; } } if (conf.getBoolean(Constants.PROP_DEVEL_MODE, false)) { log.warn("Running in debug mode, skipping regular filter"); develMode.doFilter(servletRequest, (HttpServletResponse) response, chain, conf); return; } if (cleanerRunning.compareAndSet(false, true)) { SessionCleaner.startCleaner(sessionHandlerFactory.getHandler(), ((HttpServletRequest) request).getSession().getMaxInactiveInterval(), 30); } SessionHandler sessionHandler = sessionHandlerFactory.getHandler(); if (servletRequest.getServletPath().equals(conf.getProperty(Constants.PROP_SAML_SERVLET))) { log.debug("Request to SAML servlet, access granted"); chain.doFilter(new SAMLHttpServletRequest(servletRequest, hostname, null), response); return; } final HttpSession session = servletRequest.getSession(); if (log.isDebugEnabled()) log.debug("sessionId....:" + session.getId()); // Is the user logged in? if (sessionHandler.isLoggedIn(session.getId()) && session.getAttribute(Constants.SESSION_USER_ASSERTION) != null) { int actualAssuranceLevel = sessionHandler.getAssertion(session.getId()).getAssuranceLevel(); int assuranceLevel = conf.getInt(Constants.PROP_ASSURANCE_LEVEL); if (actualAssuranceLevel < assuranceLevel) { sessionHandler.logOut(session); log.warn("Assurance level too low: " + actualAssuranceLevel + ", required: " + assuranceLevel); throw new RuntimeException( "Assurance level too low: " + actualAssuranceLevel + ", required: " + assuranceLevel); } UserAssertion ua = (UserAssertion) session.getAttribute(Constants.SESSION_USER_ASSERTION); if (log.isDebugEnabled()) log.debug("Everything is ok... Assertion: " + ua); Audit.log(Operation.ACCESS, servletRequest.getRequestURI()); try { UserAssertionHolder.set(ua); HttpServletRequestWrapper requestWrap = new SAMLHttpServletRequest(servletRequest, ua, hostname); chain.doFilter(requestWrap, response); return; } finally { UserAssertionHolder.set(null); } } else { session.removeAttribute(Constants.SESSION_USER_ASSERTION); UserAssertionHolder.set(null); String relayState = sessionHandler.saveRequest(Request.fromHttpRequest(servletRequest)); String protocol = conf.getString(Constants.PROP_PROTOCOL, "saml20"); String loginUrl = conf.getString(Constants.PROP_SAML_SERVLET, "/saml"); String protocolUrl = conf.getString(Constants.PROP_PROTOCOL + "." + protocol); if (protocolUrl == null) { throw new RuntimeException( "No protocol url configured for " + Constants.PROP_PROTOCOL + "." + protocol); } loginUrl += protocolUrl; if (log.isDebugEnabled()) log.debug("Redirecting to " + protocol + " login handler at " + loginUrl); RequestDispatcher dispatch = servletRequest.getRequestDispatcher(loginUrl); dispatch.forward(new SAMLHttpServletRequest(servletRequest, hostname, relayState), response); } }
From source file:org.b3log.solo.filter.PageCacheFilter.java
/** * Try to write response from cache./*from ww w .ja va2s. c om*/ * * @param request the specified request * @param response the specified response * @param chain filter chain * @throws IOException io exception * @throws ServletException servlet exception */ @Override public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain) throws IOException, ServletException { final long startTimeMillis = System.currentTimeMillis(); request.setAttribute(Keys.HttpRequest.START_TIME_MILLIS, startTimeMillis); final HttpServletRequest httpServletRequest = (HttpServletRequest) request; final String requestURI = httpServletRequest.getRequestURI(); LOGGER.log(Level.FINER, "Request URI[{0}]", requestURI); if (StaticResources.isStatic(httpServletRequest)) { final String path = httpServletRequest.getServletPath() + httpServletRequest.getPathInfo(); LOGGER.log(Level.FINEST, "Requests a static resource, forwards to servlet[path={0}]", path); request.getRequestDispatcher(path).forward(request, response); return; } if (!Latkes.isPageCacheEnabled()) { LOGGER.log(Level.FINEST, "Page cache is disabled"); chain.doFilter(request, response); return; } final String skinDirName = (String) httpServletRequest.getAttribute(Keys.TEMAPLTE_DIR_NAME); if ("mobile".equals(skinDirName)) { // Mobile request, bypasses page caching chain.doFilter(request, response); return; } String pageCacheKey; final String queryString = httpServletRequest.getQueryString(); pageCacheKey = (String) request.getAttribute(Keys.PAGE_CACHE_KEY); if (Strings.isEmptyOrNull(pageCacheKey)) { pageCacheKey = PageCaches.getPageCacheKey(requestURI, queryString); request.setAttribute(Keys.PAGE_CACHE_KEY, pageCacheKey); } final JSONObject cachedPageContentObject = PageCaches.get(pageCacheKey, httpServletRequest, (HttpServletResponse) response); if (null == cachedPageContentObject) { LOGGER.log(Level.FINER, "Page cache miss for request URI[{0}]", requestURI); chain.doFilter(request, response); return; } final String cachedType = cachedPageContentObject.optString(PageCaches.CACHED_TYPE); try { // If cached an article that has view password, dispatches the password form if (langPropsService.get(PageTypes.ARTICLE.getLangeLabel()).equals(cachedType) && cachedPageContentObject.has(PageCaches.CACHED_PWD)) { JSONObject article = new JSONObject(); final String articleId = cachedPageContentObject.optString(PageCaches.CACHED_OID); article.put(Keys.OBJECT_ID, articleId); article.put(Article.ARTICLE_VIEW_PWD, cachedPageContentObject.optString(PageCaches.CACHED_PWD)); if (articles.needViewPwd(httpServletRequest, article)) { article = articleRepository.get(articleId); // Loads the article entity final HttpServletResponse httpServletResponse = (HttpServletResponse) response; try { httpServletResponse.sendRedirect(Latkes.getServePath() + "/console/article-pwd" + articles.buildArticleViewPwdFormParameters(article)); return; } catch (final Exception e) { httpServletResponse.sendError(HttpServletResponse.SC_NOT_FOUND); return; } } } } catch (final Exception e) { LOGGER.log(Level.SEVERE, e.getMessage(), e); chain.doFilter(request, response); } try { LOGGER.log(Level.FINEST, "Writes resposne for page[pageCacheKey={0}] from cache", pageCacheKey); response.setContentType("text/html"); response.setCharacterEncoding("UTF-8"); final PrintWriter writer = response.getWriter(); String cachedPageContent = cachedPageContentObject.getString(PageCaches.CACHED_CONTENT); final String topBarHTML = TopBars.getTopBarHTML((HttpServletRequest) request, (HttpServletResponse) response); cachedPageContent = cachedPageContent.replace(Common.TOP_BAR_REPLACEMENT_FLAG, topBarHTML); final String cachedTitle = cachedPageContentObject.getString(PageCaches.CACHED_TITLE); LOGGER.log(Level.FINEST, "Cached value[key={0}, type={1}, title={2}]", new Object[] { pageCacheKey, cachedType, cachedTitle }); statistics.incBlogViewCount((HttpServletRequest) request, (HttpServletResponse) response); final long endimeMillis = System.currentTimeMillis(); final String dateString = DateFormatUtils.format(endimeMillis, "yyyy/MM/dd HH:mm:ss"); final String msg = String.format("<!-- Cached by B3log Solo(%1$d ms), %2$s -->", endimeMillis - startTimeMillis, dateString); LOGGER.finer(msg); cachedPageContent += Strings.LINE_SEPARATOR + msg; writer.write(cachedPageContent); writer.flush(); writer.close(); } catch (final JSONException e) { LOGGER.log(Level.SEVERE, e.getMessage(), e); chain.doFilter(request, response); } catch (final RepositoryException e) { LOGGER.log(Level.SEVERE, e.getMessage(), e); chain.doFilter(request, response); } catch (final ServiceException e) { LOGGER.log(Level.SEVERE, e.getMessage(), e); chain.doFilter(request, response); } }
From source file:org.codelabor.system.security.web.filter.SessionValidationFilter.java
@Override public void preprocessFilterChain(ServletRequest request, ServletResponse response) throws IOException, ServletException { HttpServletRequest httpServletRequest = (HttpServletRequest) request; String requestURI = httpServletRequest.getRequestURI(); String requestedSessionId = httpServletRequest.getRequestedSessionId(); boolean isRequestedSessionIdValid = httpServletRequest.isRequestedSessionIdValid(); logger.debug("requestURI: {}", requestURI); logger.debug("requestedSessionId: {}", requestedSessionId); logger.debug("isRequestedSessionIdValid: {}", isRequestedSessionIdValid); if (StringUtils.isNotBlank(requestedSessionId) && isRequestedSessionIdValid && isSessionValid(request)) { logger.debug("session id is valid: {}", requestedSessionId); } else {//from w ww. j a v a 2 s. c o m logger.error("session id is invalid: {}", requestedSessionId); logger.error("forward to expiredURL: {}", expiredURL); RequestDispatcher dispatcher = request.getRequestDispatcher(expiredURL); HttpSession httpSession = httpServletRequest.getSession(); httpSession.setAttribute(RequestConstants.REQUEST_URI, requestURI); httpSession.setAttribute(RequestConstants.REQUEST_ATTRIBUTE_MAP, RequestUtils.getAttributeMap(httpServletRequest)); httpSession.setAttribute(RequestConstants.REQUEST_PARAMETER_MAP, RequestUtils.getParameterMap(httpServletRequest)); logger.debug("current session id: {}", httpSession.getId()); dispatcher.forward(request, response); } }
From source file:com.edgenius.wiki.security.acegi.CaptchaValidationProcessingFilter.java
private void processVerify(ServletRequest request, ServletResponse response, FilterChain chain, boolean valid) throws IOException, ServletException { if (valid) {/*from w w w . j a va 2s . co m*/ //success chain.doFilter(request, response); } else { //failed if (((HttpServletRequest) request).getRequestURI().endsWith("j_spring_security_check")) { //as user login using Form submit style authentication rather than RPC's so that I have to do special handling here //code ugly, it could be changed to RPC authentication in future. response.getWriter() .write(SharedConstants.FORM_RET_HEADER + SharedConstants.FORM_RET_HEADER_ERROR_CAPTCHA); } else { // Put exception into request scope (perhaps of use to a view) ((HttpServletRequest) request).setAttribute(ACEGI_SECURITY_CAPTCHA_VALID_FAILED, true); // Perform RequestDispatcher "forward" RequestDispatcher rd = request.getRequestDispatcher(errorPage); rd.forward(request, response); } } }
From source file:de.highbyte_le.weberknecht.security.filters.NameBasedLoginPageForwardFilter.java
@Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { if (logger.isDebugEnabled()) logger.debug("doFilter() - start"); boolean forward = true; if (!(request instanceof HttpServletRequest) || !(response instanceof HttpServletResponse)) { logger.error("servlet request is no HTTP servlet request"); } else {//from ww w . jav a2s . c o m HttpServletRequest httpRequest = (HttpServletRequest) request; HttpSession session = httpRequest.getSession(); UserAuthentication userAuthentication = (UserAuthentication) session.getAttribute("user_auth"); if (userAuthentication != null && userAuthentication.isAuthenticated()) //user is logged in forward = false; else if (!isUserServlet(httpRequest.getServletPath())) //servlet is not protected forward = false; } if (forward) { request.setAttribute("de.highbyte_le.weberknecht.login.status", "failed"); logger.debug("doFilter() - forward to login page"); RequestDispatcher rd = request.getRequestDispatcher(loginPage); rd.forward(request, response); } else { logger.debug("doFilter() - Continue with filter chain"); chain.doFilter(request, response); } }
From source file:com.flexive.war.filter.BackendAuthorizationFilter.java
@Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { // get URI without application context path final UserTicket ticket = FxContext.getUserTicket(); if (ticket.isGuest() && servletRequest instanceof FxRequest) { final FxRequest request = (FxRequest) servletRequest; if (request.isDynamicContent()) { // not logged in at all - forward to login page FilterUtils.sendRedirect(servletRequest, servletResponse, "/pub/login.jsf" // guess whether we got a session timeout (from within the backend) or a new request + (StringUtils.indexOf(((HttpServletRequest) servletRequest).getHeader("Referer"), "/adm/") != -1 ? "?sessionExpired=true" : "")); } else {//from ww w .j av a2s .co m // static content (e.g. images), forbid access ((HttpServletResponse) servletResponse).sendError(HttpServletResponse.SC_FORBIDDEN); } } else if (!ticket.isInRole(Role.BackendAccess)) { // logged in, but lacks role for backend access - show error page servletRequest.getRequestDispatcher("/pub/backendRestricted.jsf").forward(servletRequest, servletResponse); } else { // proceed filterChain.doFilter(servletRequest, servletResponse); } }
From source file:org.lockss.servlet.LockssOiosamlSpFilter.java
/** * Check whether the user is authenticated i.e. having session with a valid * assertion. If the user is not authenticated an <AuthnRequest> is sent * to the Login Site./* ww w .ja v a 2 s . co m*/ * * @param request * The servletRequest * @param response * The servletResponse */ public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { final String DEBUG_HEADER = "doFilter(): "; if (log.isDebug2()) log.debug2(DEBUG_HEADER + "Starting..."); if (!(request instanceof HttpServletRequest)) { throw new RuntimeException("Not supported operation..."); } HttpServletRequest servletRequest = ((HttpServletRequest) request); Audit.init(servletRequest); if (!isFilterInitialized()) { if (log.isDebug3()) log.debug3(DEBUG_HEADER + "isFilterInitialized() = false"); try { Configuration conf = SAMLConfigurationFactory.getConfiguration().getSystemConfiguration(); setRuntimeConfiguration(conf); } catch (IllegalStateException e) { request.getRequestDispatcher("/saml/configure").forward(request, response); if (log.isDebug2()) { log.debug2(DEBUG_HEADER + "Forwarded to /saml/configure."); log.debug2(DEBUG_HEADER + "Done."); } return; } } else { if (log.isDebug3()) log.debug3(DEBUG_HEADER + "isFilterInitialized() = true"); } if (conf.getSystemConfiguration().getBoolean(Constants.PROP_DEVEL_MODE, false)) { log.warning("Running in developer mode, skipped regular filter."); develMode.doFilter(servletRequest, (HttpServletResponse) response, chain, conf.getSystemConfiguration()); if (log.isDebug2()) log.debug2(DEBUG_HEADER + "Done."); return; } if (cleanerRunning.compareAndSet(false, true)) { int maxInactiveInterval = ((HttpServletRequest) request).getSession().getMaxInactiveInterval(); if (log.isDebug3()) log.debug3(DEBUG_HEADER + "maxInactiveInterval = " + maxInactiveInterval); if (maxInactiveInterval < 0) { maxInactiveInterval = 3600; } SessionCleaner.startCleaner(sessionHandlerFactory.getHandler(), maxInactiveInterval, 30); } SessionHandler sessionHandler = sessionHandlerFactory.getHandler(); if (servletRequest.getServletPath() .equals(conf.getSystemConfiguration().getProperty(Constants.PROP_SAML_SERVLET))) { if (log.isDebug()) log.debug(DEBUG_HEADER + "Request to SAML servlet, access granted"); chain.doFilter(new SAMLHttpServletRequest(servletRequest, hostname, null), response); if (log.isDebug2()) log.debug2(DEBUG_HEADER + "Done."); return; } final HttpSession session = servletRequest.getSession(); if (log.isDebug()) log.debug(DEBUG_HEADER + "session.getId() = " + session.getId()); Boolean forceAuthn = false; if (request.getParameterMap().containsKey(Constants.QUERY_STRING_FORCE_AUTHN)) { String forceAuthnAsString = request.getParameter(Constants.QUERY_STRING_FORCE_AUTHN); if (log.isDebug3()) log.debug3(DEBUG_HEADER + "forceAuthnAsString = " + forceAuthnAsString); forceAuthn = forceAuthnAsString.toLowerCase().equals("true"); } if (log.isDebug3()) log.debug3(DEBUG_HEADER + "forceAuthn = " + forceAuthn); // Is the user logged in? if (sessionHandler.isLoggedIn(session.getId()) && session.getAttribute(Constants.SESSION_USER_ASSERTION) != null && !forceAuthn) { int actualAssuranceLevel = sessionHandler.getAssertion(session.getId()).getAssuranceLevel(); if (log.isDebug3()) log.debug3(DEBUG_HEADER + "actualAssuranceLevel = " + actualAssuranceLevel); int assuranceLevel = conf.getSystemConfiguration().getInt(Constants.PROP_ASSURANCE_LEVEL); if (log.isDebug3()) log.debug3(DEBUG_HEADER + "assuranceLevel = " + assuranceLevel); if (actualAssuranceLevel > 0 && actualAssuranceLevel < assuranceLevel) { sessionHandler.logOut(session); log.warning("Assurance level too low: " + actualAssuranceLevel + ", required: " + assuranceLevel); throw new RuntimeException( "Assurance level too low: " + actualAssuranceLevel + ", required: " + assuranceLevel); } UserAssertion ua = (UserAssertion) session.getAttribute(Constants.SESSION_USER_ASSERTION); if (log.isDebug()) { log.debug(DEBUG_HEADER + "Everything is OK."); log.debug(DEBUG_HEADER + "Subject: " + ua.getSubject()); log.debug(DEBUG_HEADER + "NameID Format: " + ua.getNameIDFormat()); log.debug(DEBUG_HEADER + "Common Name: " + ua.getCommonName()); log.debug(DEBUG_HEADER + "UserId: " + ua.getUserId()); log.debug(DEBUG_HEADER + "Authenticated?: " + ua.isAuthenticated()); log.debug(DEBUG_HEADER + "Signed?: " + ua.isSigned()); } Audit.log(Operation.ACCESS, servletRequest.getRequestURI()); try { UserAssertionHolder.set(ua); HttpServletRequestWrapper requestWrap = new SAMLHttpServletRequest(servletRequest, ua, hostname); chain.doFilter(requestWrap, response); if (log.isDebug2()) log.debug2(DEBUG_HEADER + "Done."); return; } finally { UserAssertionHolder.set(null); } } else { session.removeAttribute(Constants.SESSION_USER_ASSERTION); UserAssertionHolder.set(null); saveRequestAndGotoLogin((HttpServletResponse) response, servletRequest); } if (log.isDebug2()) log.debug2(DEBUG_HEADER + "Done."); }
From source file:org.apache.pluto.driver.PortalDriverFilter.java
/** * Intercept requests in order to perform any actions. * * @param request the incoming ServletRequest. * @param response the incoming ServletResponse. * @throws javax.servlet.ServletException if an internal error occurs. * @throws java.io.IOException if an error occurs writing to the response. *///from w w w.ja v a 2s.co m public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException { if (request instanceof HttpServletRequest && response instanceof HttpServletResponse) { HttpServletRequest req = (HttpServletRequest) request; // Since we must support a 2.3 environment, we can't use // filter dispatchers. B/C of this, we make sure we haven't // allready processed this request. No infinite loops for us!!!! if (PortalRequestContext.getContext(req) == null) { boolean actionRequestProcessed = doPortletPrepare(req, (HttpServletResponse) response); if (actionRequestProcessed) { return; } } String path = req.getServletPath(); int idx = path.indexOf(".jsp"); if (!path.endsWith(".jsp") && idx > 0) { String realPath = path.substring(0, idx + ".jsp".length()); if (realPath.startsWith(req.getContextPath())) { realPath = realPath.substring(req.getContextPath().length()); } LOG.info("Forwarding to realPath: " + realPath); request.getRequestDispatcher(realPath).forward(request, response); return; } } filterChain.doFilter(request, response); }
From source file:filter.ConexaoHibernateFilter.java
@Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws ServletException, IOException { try {/*from w ww. ja va 2 s .c o m*/ this.sf.getCurrentSession().beginTransaction(); chain.doFilter(servletRequest, servletResponse); this.sf.getCurrentSession().getTransaction().commit(); this.sf.getCurrentSession().close(); } catch (Throwable ex) { try { if (this.sf.getCurrentSession().getTransaction().isActive()) { this.sf.getCurrentSession().getTransaction().rollback(); } } catch (Throwable t) { t.printStackTrace(); } throw new ServletException(ex); } HttpServletRequest request = (HttpServletRequest) servletRequest; HttpSession session = request.getSession(); // recupera o usuario adm logado da sesso Object login = session.getAttribute("UsuarioAtual"); RequestDispatcher dispatcher = null; if (!(request.getRequestURI().equals(paginaLogin) || request.getRequestURI().equals(paginaPrimeiroAcesso) || request.getRequestURI().equals(paginaRecuperarSenha))) { if (login == null) { // ento envia para a pagina de acesso invalido dispatcher = servletRequest.getRequestDispatcher("loginEntrar.xhtml"); dispatcher.forward(servletRequest, servletResponse); } } }