Java Code Examples for org.springframework.web.filter.OncePerRequestFilter

The following examples show how to use org.springframework.web.filter.OncePerRequestFilter. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
@Bean
public FilterRegistrationBean<OncePerRequestFilter> saveLoginOriginFilter() {
    OncePerRequestFilter filter = new OncePerRequestFilter() {
        @Override
        protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
                                        FilterChain filterChain)
            throws ServletException, IOException {
            if (request.getRemoteUser() == null && request.getRequestURI().endsWith("/login")) {
                String referrer = request.getHeader("referer");
                if (!StringUtils.isBlank(referrer) &&
                    request.getSession().getAttribute(SAVED_LOGIN_ORIGIN_URI) == null) {
                    log.debug("Saving login origin URI: {}", referrer);
                    request.getSession().setAttribute(SAVED_LOGIN_ORIGIN_URI, referrer);
                }
            }
            filterChain.doFilter(request, response);
        }
    };
    FilterRegistrationBean<OncePerRequestFilter> bean = new FilterRegistrationBean<>(filter);
    bean.setOrder(Ordered.HIGHEST_PRECEDENCE);
    return bean;
}
 
Example 2
Source Project: micrometer   Source File: HttpMetricsTagConfiguration.java    License: Apache License 2.0 6 votes vote down vote up
@Bean
OncePerRequestFilter extractCountry() {
    return new OncePerRequestFilter() {
        private final ObjectMapper mapper = new ObjectMapper();

        @Override
        protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
                                        FilterChain filterChain) throws ServletException, IOException {
            ContentCachingResponseWrapper cached = new ContentCachingResponseWrapper(response);
            filterChain.doFilter(request, cached);

            Object path = request.getAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE);
            if (path.equals("/api/person/{id}")) {
                // Prometheus requires the same tags on all `http.server.requests`. So we'll need to add
                // a `@Timed("person.requests") to the /api/person/{id} endpoint so it has a different name.
                Person person = mapper.readValue(cached.getContentAsByteArray(), Person.class);
                responseTags.put(response, Tags.of("country", person.getCountry()));
            }

            cached.copyBodyToResponse();
        }
    };
}
 
Example 3
Source Project: cerberus   Source File: ApplicationConfiguration.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * This filter is to duplicate what could be considered buggy behavior, but Highlander Cerberus
 * supports requests with repeating slashes such as `//v2/sts-auth` So we will just trim extra
 * slashes and do the chain with the sanitized uri.
 */
@Bean
public OncePerRequestFilter trimExtraSlashesFilter() {
  return new OncePerRequestFilter() {
    @Override
    protected void doFilterInternal(
        HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
        throws ServletException, IOException {
      var req = request.getRequestURI();
      if (req.contains("//")) {
        var sanitizedUri = StringUtils.replace(req, "//", "/");
        filterChain.doFilter(
            new HttpServletRequestWrapper(request) {
              @Override
              public String getRequestURI() {
                return sanitizedUri;
              }
            },
            response);
      } else {
        filterChain.doFilter(request, response);
      }
    }
  };
}
 
Example 4
@Bean
public FilterRegistrationBean<?> stickyCloudFoundryFilter() {
	FilterRegistrationBean<Filter> filter = new FilterRegistrationBean<Filter>();
	filter.setOrder(Ordered.LOWEST_PRECEDENCE);
	filter.setFilter(new OncePerRequestFilter() {
		@Override
		protected void doFilterInternal(HttpServletRequest request,
				HttpServletResponse response, FilterChain filterChain)
				throws ServletException, IOException {
			if (!response.containsHeader("Set-Cookie")) {
				response.addCookie(new Cookie("JSESSIONID",
						StickyFilterConfiguration.this.cookie));
			}
			filterChain.doFilter(request, response);
		}
	});
	return filter;
}
 
Example 5
private Filter csrfHeaderFilter() {
	return new OncePerRequestFilter() {
		@Override
		protected void doFilterInternal(HttpServletRequest request,
				HttpServletResponse response, FilterChain filterChain)
				throws ServletException, IOException {
			CsrfToken csrf = (CsrfToken) request
					.getAttribute(CsrfToken.class.getName());
			if (csrf != null) {
				Cookie cookie = new Cookie("XSRF-TOKEN",
						csrf.getToken());
				cookie.setPath("/");
				response.addCookie(cookie);
			}
			filterChain.doFilter(request, response);
		}
	};
}
 
Example 6
Source Project: cerberus   Source File: ApplicationConfiguration.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * This filter maps null responses for PUT and POST requests to 204's rather than 200's This is
 * done in order to maintain backwards compatibility from the pre-spring API.
 */
@Bean
public OncePerRequestFilter nullOkResponsesShouldReturnNoContentFilter() {
  return new LambdaFilter(
      true,
      (request, response) -> {
        var typeOptional =
            Optional.ofNullable(response.getContentType()).filter(Predicate.not(String::isBlank));
        if (typeOptional.isEmpty() && response.getStatus() == HttpStatus.OK.value()) {
          response.setStatus(HttpStatus.NO_CONTENT.value());
        }
      });
}
 
Example 7
Source Project: portal-de-servicos   Source File: FilterConfig.java    License: MIT License 5 votes vote down vote up
@Bean
public FilterRegistrationBean securityHeadersFilter(@Value("${pds.piwik.url}") String urlPiwik) {
    return filter(2, new OncePerRequestFilter() {
        @Override
        protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
            filterChain.doFilter(request, response);
            response.setHeader("X-XSS-Protection", "0");
            response.setHeader("X-Content-Type-Options", "nosniff");
            response.setHeader("Content-Security-Policy", "script-src: 'self' 'unsafe-inline' '" + urlPiwik + "' 'barra.brasil.gov.br'; default-src: 'self'");
        }
    });
}
 
Example 8
Source Project: modern-java-web-scaffold   Source File: WebConfig.java    License: MIT License 4 votes vote down vote up
@Bean
public OncePerRequestFilter statelessJwtFilter() {
    return new StatelessJwtFilter();
}
 
Example 9
Source Project: cerberus   Source File: ApplicationConfiguration.java    License: Apache License 2.0 4 votes vote down vote up
/** TODO, we can probably delete this, but the API tests from Highlander check for this. */
@Bean
public OncePerRequestFilter addXRefreshTokenHeaderFilter() {
  return new LambdaFilter(
      (request, response) -> response.addHeader("X-Refresh-Token", Boolean.FALSE.toString()));
}