List of usage examples for javax.servlet ServletRequest setAttribute
public void setAttribute(String name, Object o);
From source file:filters.ActionValidationFilter.java
@Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest httpServletRequest = (HttpServletRequest) request; String requPath = httpServletRequest.getServletPath(); /*/* w w w . j a v a2s . com*/ * ignore resource files (CSS, JPEG/PNG, JavaScript) ... */ if (requPath.startsWith(STATIC_RESOURCES) || requPath.startsWith(API)) { chain.doFilter(request, response); return; } /* * This filter makes only sense, if user is logged in. */ User user = AuthenticationUtils.getUser(); if (user != null && user.getName() != null) { /* * get sessions credential storage variable */ String storedCredential = (String) request.getAttribute(REQUEST_ATTRIB_CREDENTIAL); /* * if null, create new one */ if (storedCredential == null) { storedCredential = getNewCredential(user, httpServletRequest.getSession()); request.setAttribute(REQUEST_ATTRIB_CREDENTIAL, storedCredential); } log.debug("credential for " + user.getName() + " = " + storedCredential); /* * get credential from request parameter * * FIXME: This does not work with multipart-requests! Thus, on such * requests we must otherwise send the ckey. */ String requestCredential = request.getParameter(REQUEST_PARAM_CREDENTIAL); /* * check and propagate correctness */ request.setAttribute(REQUEST_ATTRIB_VALID_CREDENTIAL, storedCredential.equals(requestCredential)); } // Pass control on to the next filter chain.doFilter(request, response); }
From source file:org.apache.atlas.web.filters.AtlasKnoxSSOAuthenticationFilter.java
@Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { HttpServletResponse httpResponse = (HttpServletResponse) servletResponse; AtlasResponseRequestWrapper responseWrapper = new AtlasResponseRequestWrapper(httpResponse); responseWrapper.setHeader("X-Frame-Options", "DENY"); if (!ssoEnabled) { filterChain.doFilter(servletRequest, servletResponse); return;/* w w w. ja v a 2 s.co m*/ } HttpServletRequest httpRequest = (HttpServletRequest) servletRequest; if (LOG.isDebugEnabled()) { LOG.debug("Knox doFilter {}", httpRequest.getRequestURI()); } if (httpRequest.getSession() != null && httpRequest.getSession().getAttribute("locallogin") != null) { servletRequest.setAttribute("ssoEnabled", false); filterChain.doFilter(servletRequest, servletResponse); return; } if (jwtProperties == null || isAuthenticated()) { filterChain.doFilter(servletRequest, servletResponse); return; } if (LOG.isDebugEnabled()) { LOG.debug("Knox ssoEnabled {} {}", ssoEnabled, httpRequest.getRequestURI()); } //if jwt properties are loaded and is current not authenticated then it will go for sso authentication //Note : Need to remove !isAuthenticated() after knoxsso solve the bug from cross-origin script HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse; String serializedJWT = getJWTFromCookie(httpRequest); // if we get the hadoop-jwt token from the cookies then will process it further if (serializedJWT != null) { SignedJWT jwtToken = null; try { jwtToken = SignedJWT.parse(serializedJWT); boolean valid = validateToken(jwtToken); //if the public key provide is correct and also token is not expired the process token if (valid) { String userName = jwtToken.getJWTClaimsSet().getSubject(); LOG.info("SSO login user : {} ", userName); //if we get the userName from the token then log into atlas using the same user if (userName != null && !userName.trim().isEmpty()) { List<GrantedAuthority> grantedAuths = AtlasAuthenticationProvider .getAuthoritiesFromUGI(userName); final UserDetails principal = new User(userName, "", grantedAuths); final Authentication finalAuthentication = new UsernamePasswordAuthenticationToken( principal, "", grantedAuths); WebAuthenticationDetails webDetails = new WebAuthenticationDetails(httpRequest); ((AbstractAuthenticationToken) finalAuthentication).setDetails(webDetails); AtlasAuthenticationProvider authenticationProvider = new AtlasAuthenticationProvider(); authenticationProvider.setSsoEnabled(ssoEnabled); Authentication authentication = authenticationProvider.authenticate(finalAuthentication); SecurityContextHolder.getContext().setAuthentication(authentication); } filterChain.doFilter(servletRequest, httpServletResponse); } else { // if the token is not valid then redirect to knox sso redirectToKnox(httpRequest, httpServletResponse, filterChain); } } catch (ParseException e) { LOG.warn("Unable to parse the JWT token", e); redirectToKnox(httpRequest, httpServletResponse, filterChain); } } else { redirectToKnox(httpRequest, httpServletResponse, filterChain); } }
From source file:com.wordpress.metaphorm.authProxy.hook.AuthProxyServletFilter.java
public void doFilter(ServletRequest servletReq, ServletResponse servletResp, FilterChain filterChain) throws IOException, ServletException { if (servletReq instanceof HttpServletRequest) { HttpServletResponse httpServletResp = (HttpServletResponse) servletResp; try {//from w w w .j a va 2 s . c o m // Handle potential request for HTTP resource via Social Apps Proxy if (filterHttpRequest((HttpServletRequest) servletReq, httpServletResp)) return; // Don't allow any more filters or servlets to process the request. // Consider a portal request, make userToken available to plug-ins String userToken = UserToken.constructFromHttpServletRequest((HttpServletRequest) servletReq) .toString(); servletReq.setAttribute("userToken", userToken); } catch (OAuthCommunicationException e) { throw new IOException(e); } catch (OAuthExpectationFailedException e) { throw new IOException(e); } catch (OAuthNotAuthorizedException e) { throw new IOException(e); } catch (OAuthMessageSignerException e) { throw new IOException(e); } catch (ExpiredStateException e) { throw new ServletException(e); } catch (NoSuchOAuthProviderException e) { throw new IOException(e); } catch (SystemException e) { throw new ServletException(e); } catch (OAuthProviderConfigurationException e) { _log.warn(e.getMessage()); httpServletResp.sendError(501, e.getMessage()); return; } catch (ProtocolNotSupportedException e) { _log.warn(e.getMessage()); httpServletResp.sendError(501, e.getMessage()); return; } catch (PortalException e) { // TODO Auto-generated catch block e.printStackTrace(); return; } } filterChain.doFilter(servletReq, servletResp); }
From source file:de.innovationgate.wgpublisher.WGPDeployer.java
public String locateTmlResource(WGTMLModule tmlLib, ServletRequest servletRequest) throws WGAPIException, DeployerException { DesignReference ref = WGADesignManager.createDesignReference(tmlLib); DeployedLayout layout = getDeployedLayout(tmlLib, ref); if (layout == null) { MultiLevelLock lock = _lockManager.atomicGetOrCreateLock(ref.toString()); try {// w w w. j ava 2 s . c o m try { lock.acquire(Thread.currentThread(), 1, true, true, Long.MAX_VALUE); } catch (InterruptedException e) { } layout = getDeployedLayout(tmlLib, ref); if (layout == null) { servletRequest.setAttribute(REQATTRIB_TML_DEPLOYED, true); layout = deployTML(tmlLib); } } finally { lock.release(Thread.currentThread()); } } return layout.getResourcePath(); }
From source file:com.kelson.keeku.security.MyFormAuthenticationFilter.java
@Override protected boolean executeLogin(ServletRequest request, ServletResponse response) throws Exception { String username = getUsername(request); String password = getPassword(request); boolean isAjaxLogin = StringUtils.equals(WebUtils.getCleanParam(request, "ajaxLogin"), "1"); boolean rememberMe = isRememberMe(request); String host = getHost(request); UsernamePasswordToken token = new UsernamePasswordToken(username, password, rememberMe, host); try {/*from ww w.j a va 2 s . c o m*/ Subject subject = getSubject(request, response); subject.login(token); Session session = subject.getSession(); Integer userId = (Integer) session.getAttribute("userId"); LoggerUtil.operation(Operation.Login, String.valueOf(userId) + "has logined", (HttpServletRequest) request); if (isAjaxLogin) { if (StringUtils.equals(WebUtils.getCleanParam(request, "needRedirect"), "1")) {//when login successfully by ajax login and redirect to backurl SavedRequest savedRequest = WebUtils.getAndClearSavedRequest(request); if (savedRequest != null && savedRequest.getMethod().equalsIgnoreCase(AccessControlFilter.GET_METHOD)) { request.setAttribute("backUrl", savedRequest.getRequestUrl()); } } return true; } else { return onLoginSuccess(token, subject, request, response); } } catch (AuthenticationException e) { if (SecurityUtils.getSubject().getSession(false) != null) { SecurityUtils.getSubject().getSession(false).removeAttribute("userId"); } return onLoginFailure(token, e, request, response); } }
From source file:org.nuxeo.ecm.platform.ui.web.auth.NuxeoAuthenticationFilter.java
protected boolean handleLogout(ServletRequest request, ServletResponse response, CachableUserIdentificationInfo cachedUserInfo) throws ServletException { logLogout(cachedUserInfo.getUserInfo()); // invalidate Session ! service.invalidateSession(request);//from ww w .j a v a2 s. co m request.setAttribute(DISABLE_REDIRECT_REQUEST_KEY, Boolean.TRUE); Map<String, String> parameters = new HashMap<String, String>(); String securityError = request.getParameter(SECURITY_ERROR); if (securityError != null) { parameters.put(SECURITY_ERROR, securityError); } if (cachedUserInfo.getPrincipal().getName().equals(getAnonymousId())) { parameters.put(FORCE_ANONYMOUS_LOGIN, "true"); } String requestedUrl = request.getParameter(REQUESTED_URL); if (requestedUrl != null) { parameters.put(REQUESTED_URL, requestedUrl); } // Reset JSESSIONID Cookie HttpServletResponse httpResponse = (HttpServletResponse) response; Cookie cookie = new Cookie("JSESSIONID", null); cookie.setMaxAge(0); cookie.setPath("/"); httpResponse.addCookie(cookie); String pluginName = cachedUserInfo.getUserInfo().getAuthPluginName(); NuxeoAuthenticationPlugin authPlugin = service.getPlugin(pluginName); NuxeoAuthenticationPluginLogoutExtension logoutPlugin = null; if (authPlugin instanceof NuxeoAuthenticationPluginLogoutExtension) { logoutPlugin = (NuxeoAuthenticationPluginLogoutExtension) authPlugin; } boolean redirected = false; if (logoutPlugin != null) { redirected = Boolean.TRUE.equals( logoutPlugin.handleLogout((HttpServletRequest) request, (HttpServletResponse) response)); } HttpServletRequest httpRequest = (HttpServletRequest) request; if (!redirected && !XMLHTTP_REQUEST_TYPE.equalsIgnoreCase(httpRequest.getHeader("X-Requested-With"))) { String baseURL = service.getBaseURL(request); try { String url = baseURL + LoginScreenHelper.getStartupPagePath(); url = URIUtils.addParametersToURIQuery(url, parameters); ((HttpServletResponse) response).sendRedirect(url); redirected = true; } catch (IOException e) { log.error("Unable to redirect to default start page after logout : " + e.getMessage()); } } try { cachedUserInfo.getLoginContext().logout(); } catch (LoginException e) { log.error("Unable to logout " + e.getMessage()); } return redirected; }
From source file:org.openmhealth.reference.filter.ExceptionFilter.java
/** * <p>// ww w.j av a2 s . c o m * If the request throws an exception, specifically a OmhException, * attempt to respond with that message from the exception. * </p> * * <p> * For example, HTTP responses have their status codes changed to * {@link HttpServletResponse#SC_BAD_REQUEST} and the body of the response * is the error message. * </p> */ @Override public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain) throws IOException, ServletException { // Get a handler for the correct exception type. Throwable exception = null; // Always let the request continue but setup to catch exceptions. try { chain.doFilter(request, response); } // The servlet container may wrap the exception, in which case we // must first unwrap it, then delegate it. catch (NestedServletException e) { // Get the underlying cause. Throwable cause = e.getCause(); // If the underlying exception is one of ours, then store the // underlying exception. if (cause instanceof OmhException) { exception = cause; } // Otherwise, store this exception. else { exception = e; } } // Otherwise, store the exception, catch (Exception e) { exception = e; } // If an exception was thrown, attempt to handle it. if (exception != null) { // Save the exception in the request. request.setAttribute(ATTRIBUTE_KEY_EXCEPTION, exception); // Handle the exception. if (exception instanceof NoSuchSchemaException) { LOGGER.log(Level.INFO, "An unknown schema was requested.", exception); // Respond to the user. sendResponse(response, HttpServletResponse.SC_NOT_FOUND, exception.getMessage()); } else if (exception instanceof InvalidAuthenticationException) { LOGGER.log(Level.INFO, "A user's authentication information was invalid.", exception); // Respond to the user. sendResponse(response, HttpServletResponse.SC_UNAUTHORIZED, exception.getMessage()); } else if (exception instanceof InvalidAuthorizationException) { LOGGER.log(Level.INFO, "A user's authorization information was invalid.", exception); // Respond to the user. sendResponse(response, HttpServletResponse.SC_UNAUTHORIZED, exception.getMessage()); } else if (exception instanceof OmhException) { LOGGER.log(Level.INFO, "An invalid request was made.", exception); // Respond to the user. sendResponse(response, HttpServletResponse.SC_BAD_REQUEST, exception.getMessage()); } // If the exception was not one of ours, the server must have // crashed. else { LOGGER.log(Level.SEVERE, "The server threw an unexpected exception.", exception); // Respond to the user. sendResponse(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, null); } } }
From source file:org.b3log.solo.filter.InitCheckFilter.java
/** * If Solo has not been initialized, so redirects to /init. * * @param request the specified request// ww w. j a v a2 s. co m * @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 HttpServletRequest httpServletRequest = (HttpServletRequest) request; final String requestURI = httpServletRequest.getRequestURI(); LOGGER.log(Level.FINEST, "Request[URI={0}]", requestURI); try { if (SoloServletListener.isInited()) { chain.doFilter(request, response); return; } if ("POST".equalsIgnoreCase(httpServletRequest.getMethod()) && (Latkes.getContextPath() + "/init").equals(requestURI)) { // Do initailization chain.doFilter(request, response); return; } LOGGER.finer("Try to get preference to confirm whether the preference exixts"); final JSONObject preference = preferenceQueryService.getPreference(); if (null == preference) { LOGGER.log(Level.WARNING, "B3log Solo has not been initialized, so redirects to /init"); final HTTPRequestContext context = new HTTPRequestContext(); context.setRequest((HttpServletRequest) request); context.setResponse((HttpServletResponse) response); request.setAttribute(Keys.HttpRequest.REQUEST_URI, Latkes.getContextPath() + "/init"); request.setAttribute(Keys.HttpRequest.REQUEST_METHOD, HTTPRequestMethod.GET.name()); HTTPRequestDispatcher.dispatch(context); } else { // XXX: Wrong state of SoloServletListener.isInited() chain.doFilter(request, response); } } catch (final ServiceException e) { ((HttpServletResponse) response).sendError(HttpServletResponse.SC_NOT_FOUND); } }
From source file:org.ajax4jsf.webapp.BaseFilter.java
/** * Execute the filter.//from w w w .j av a 2 s.c o m */ public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { long startTimeMills = 0; // Detect case of request - normal, AJAX, AJAX - JavaScript // TODO - detect first processing in filter. HttpServletRequest httpServletRequest = (HttpServletRequest) request; HttpServletResponse httpServletResponse = (HttpServletResponse) response; if (log.isDebugEnabled()) { startTimeMills = System.currentTimeMillis(); log.debug(Messages.getMessage(Messages.FILTER_START_INFO, new Date(startTimeMills), httpServletRequest.getRequestURI())); } if (request.getAttribute(FILTER_PERFORMED) != Boolean.TRUE) { // mark - and not processing same request twice. try { request.setAttribute(FILTER_PERFORMED, Boolean.TRUE); String ajaxPushHeader = httpServletRequest.getHeader(AJAX_PUSH_KEY_HEADER); // check for a push check request. if (httpServletRequest.getMethod().equals("HEAD") && null != ajaxPushHeader) { PushEventsCounter listener = eventsManager.getListener(ajaxPushHeader); // To avoid XmlHttpRequest parsing exceptions. httpServletResponse.setContentType("text/plain"); if (listener.isPerformed()) { listener.processed(); httpServletResponse.setStatus(HttpServletResponse.SC_OK); httpServletResponse.setHeader(AJAX_PUSH_STATUS_HEADER, AJAX_PUSH_READY); if (log.isDebugEnabled()) { log.debug("Occurs event for a id " + ajaxPushHeader); } } else { // Response code - 'No content' httpServletResponse.setStatus(HttpServletResponse.SC_ACCEPTED); if (log.isDebugEnabled()) { log.debug("No event for a id " + ajaxPushHeader); } } httpServletResponse.setContentLength(0); } else // check for resource request if (!getResourceService().serviceResource(httpServletRequest, httpServletResponse)) { // Not request to resource - perform filtering. // first stage - detect/set encoding of request. Same as in // Myfaces External Context. setupRequestEncoding(httpServletRequest); processUploadsAndHandleRequest(httpServletRequest, httpServletResponse, chain); } } finally { // Remove filter marker from response, to enable sequence calls ( for example, forward to error page ) request.removeAttribute(FILTER_PERFORMED); Object ajaxContext = request.getAttribute(AjaxContext.AJAX_CONTEXT_KEY); if (null != ajaxContext && ajaxContext instanceof AjaxContext) { ((AjaxContext) ajaxContext).release(); request.removeAttribute(AjaxContext.AJAX_CONTEXT_KEY); } } } else { if (log.isDebugEnabled()) { log.debug(Messages.getMessage(Messages.FILTER_NO_XML_CHAIN_2)); } chain.doFilter(request, response); } if (log.isDebugEnabled()) { startTimeMills = System.currentTimeMillis() - startTimeMills; log.debug(Messages.getMessage(Messages.FILTER_STOP_INFO, "" + startTimeMills, httpServletRequest.getRequestURI())); } }
From source file:org.mfr.web.PrivateContentAccessManager.java
@Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException { HttpServletRequest servletR = ((HttpServletRequest) request); RequestWrapper.httpRequest.set(servletR); try {// www .j a v a 2 s . c om String requestUri = servletR.getRequestURI(); Site site = (Site) request.getAttribute(SiteFilter.PORTFOLIOSITE); ; if (requestUri.length() == 1) { if (!SiteDao.isSitePasswordRequired(site) && !HttpHelper.isSiteGranted(site)) { request.getRequestDispatcher("/index.zul").forward(request, response); return; } else { if (SiteDao.isSitePasswordRequired(site) && !HttpHelper.isSiteGranted(site)) { request.getRequestDispatcher("/privateaccess.zul").forward(request, response); } else { request.getRequestDispatcher("/pindex.zul").forward(request, response); } return; } } int lastIndex = requestUri.lastIndexOf("/"); requestUri = requestUri.substring(lastIndex); logger.debug("pageActUri [" + requestUri + "]"); request.setAttribute(GlobalVariableResolver.PAGEACTURI, requestUri); User user = HttpHelper.getUser(((HttpServletRequest) request).getSession()); String threadName = Thread.currentThread().getName(); try { Thread.currentThread().setName( requestUri + "-" + ((HttpServletRequest) request).getSession().getId() + "-" + count++); List<String> actualAllowedPages = null; String redirectUrl = null; boolean hasPermission = hasPermission(requestUri); if (!SiteDao.isSitePasswordRequired(site) && SiteDao.notIsPublicOrOwner(site)) { actualAllowedPages = allowedPage; redirectUrl = LoginComposer.INDEXPAGE; } else { if (GlobalVariableResolver.isSiteOwner()) { redirectUrl = LoginComposer.PINDEXPAGE; } else if (SiteDao.isSitePasswordRequired(site) && !HttpHelper.isPasswordAccessGranted(site)) { redirectUrl = "/privateaccess.zul"; } else { redirectUrl = LoginComposer.PINDEXPAGE; } actualAllowedPages = portfolioAllowedPage; } if (!hasPermission && (!actualAllowedPages.contains(requestUri) && user == null) || (site != null && !redirectUrl.equals(requestUri) && (!actualAllowedPages.contains(requestUri) || !HttpHelper.isSiteGranted(site)))) { request.getRequestDispatcher(redirectUrl).forward(request, response); } else { filterChain.doFilter(request, response); } } catch (ServletException e) { logger.error("doFilter", e); throw e; } finally { Thread.currentThread().setName(threadName); } } catch (Exception e) { logger.error("filter", e); } finally { RequestWrapper.httpRequest.set(null); } }