Skip to content

Commit

Permalink
added MultipartRequestMatcher to only require CSRF tokens on Multipar…
Browse files Browse the repository at this point in the history
…t CRSF'able requests
  • Loading branch information
rmmayo committed Jun 18, 2024
1 parent fa11d90 commit 7ae1f23
Showing 1 changed file with 21 additions and 0 deletions.
21 changes: 21 additions & 0 deletions service/src/main/java/skills/auth/PortalWebSecurityHelper.groovy
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,9 @@ import org.springframework.security.web.csrf.CsrfToken
import org.springframework.security.web.csrf.CsrfTokenRequestAttributeHandler
import org.springframework.security.web.csrf.CsrfTokenRequestHandler
import org.springframework.security.web.csrf.XorCsrfTokenRequestAttributeHandler
import org.springframework.security.web.util.matcher.AntPathRequestMatcher
import org.springframework.security.web.util.matcher.OrRequestMatcher
import org.springframework.security.web.util.matcher.RequestMatcher
import org.springframework.stereotype.Component
import org.springframework.util.StringUtils
import org.springframework.web.filter.OncePerRequestFilter
Expand Down Expand Up @@ -68,6 +71,7 @@ class PortalWebSecurityHelper {
HttpSecurity configureHttpSecurity(HttpSecurity http) {

http.csrf((csrf) -> csrf
.requireCsrfProtectionMatcher(new MultipartRequestMatcher())
.csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
.csrfTokenRequestHandler(new SpaCsrfTokenRequestHandler()))
.addFilterAfter(new CsrfCookieFilter(), BasicAuthenticationFilter.class)
Expand Down Expand Up @@ -155,4 +159,21 @@ final class CsrfCookieFilter extends OncePerRequestFilter {

filterChain.doFilter(request, response)
}
}

final class MultipartRequestMatcher implements RequestMatcher {

private final HashSet<String> allowedMethods = new HashSet<>(Arrays.asList("GET", "HEAD", "TRACE", "OPTIONS"))
private final OrRequestMatcher pathMatcher = new OrRequestMatcher(
new AntPathRequestMatcher("/api/upload"),
new AntPathRequestMatcher("/admin/projects/*/icons/upload"),
new AntPathRequestMatcher("/supervisor/icons/upload"),
new AntPathRequestMatcher("/admin/projects/*/skills/*/video"),
)

@Override
boolean matches(HttpServletRequest request) {
Boolean matches = (pathMatcher.matches(request) && !this.allowedMethods.contains(request.getMethod()))
return matches
}
}

0 comments on commit 7ae1f23

Please sign in to comment.