Example #1
0
 public static String getJenkinsUrl(HttpServletRequest req) {
   String jenkinsUrl = getJenkinsUrl();
   if (jenkinsUrl == null) {
     jenkinsUrl =
         UrlUtils.buildFullRequestUrl(
                 req.getScheme(),
                 req.getServerName(),
                 req.getServerPort(),
                 req.getContextPath(),
                 null)
             + "/";
   }
   return jenkinsUrl;
 }
  /*
   * (non-Javadoc)
   *
   * @see
   * org.springframework.web.filter.OncePerRequestFilter#doFilterInternal(javax.servlet
   * .http.HttpServletRequest, javax.servlet.http.HttpServletResponse,
   * javax.servlet.FilterChain)
   */
  @Override
  protected void doFilterInternal(
      HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
      throws ServletException, IOException {
    CsrfToken csrfToken = tokenRepository.loadToken(request);
    final boolean missingToken = csrfToken == null;
    if (missingToken) {
      CsrfToken generatedToken = tokenRepository.generateToken(request);
      csrfToken = new SaveOnAccessCsrfToken(tokenRepository, request, response, generatedToken);
    }
    request.setAttribute(CsrfToken.class.getName(), csrfToken);
    request.setAttribute(csrfToken.getParameterName(), csrfToken);

    if (!requireCsrfProtectionMatcher.matches(request)) {
      filterChain.doFilter(request, response);
      return;
    }

    String actualToken = request.getHeader(csrfToken.getHeaderName());
    if (actualToken == null) {
      actualToken = request.getParameter(csrfToken.getParameterName());
    }
    if (!csrfToken.getToken().equals(actualToken)) {
      if (logger.isDebugEnabled()) {
        logger.debug("Invalid CSRF token found for " + UrlUtils.buildFullRequestUrl(request));
      }
      if (missingToken) {
        accessDeniedHandler.handle(request, response, new MissingCsrfTokenException(actualToken));
      } else {
        accessDeniedHandler.handle(
            request, response, new InvalidCsrfTokenException(csrfToken, actualToken));
      }
      return;
    }

    filterChain.doFilter(request, response);
  }