use of org.springframework.security.config.annotation.web.configurers.CsrfConfigurer in project alf.io by alfio-event.
the class AbstractFormBasedWebSecurity method configure.
@Override
protected void configure(HttpSecurity http) throws Exception {
if (environment.acceptsProfiles(Profiles.of("!" + Initializer.PROFILE_DEV))) {
http.requiresChannel().antMatchers("/healthz").requiresInsecure().and().requiresChannel().mvcMatchers("/**").requiresSecure();
}
CsrfConfigurer<HttpSecurity> configurer = http.exceptionHandling().accessDeniedHandler((request, response, accessDeniedException) -> {
if (!response.isCommitted()) {
if ("XMLHttpRequest".equals(request.getHeader(AuthenticationConstants.X_REQUESTED_WITH))) {
response.setStatus(HttpServletResponse.SC_FORBIDDEN);
} else if (!response.isCommitted()) {
response.setStatus(HttpServletResponse.SC_FORBIDDEN);
RequestDispatcher dispatcher = request.getRequestDispatcher("/session-expired");
dispatcher.forward(request, response);
}
}
}).defaultAuthenticationEntryPointFor((request, response, ex) -> response.sendError(HttpServletResponse.SC_UNAUTHORIZED), new RequestHeaderRequestMatcher(AuthenticationConstants.X_REQUESTED_WITH, "XMLHttpRequest")).and().headers().cacheControl().disable().and().csrf();
Pattern pattern = Pattern.compile("^(GET|HEAD|TRACE|OPTIONS)$");
Predicate<HttpServletRequest> csrfWhitelistPredicate = r -> r.getRequestURI().startsWith("/api/webhook/") || r.getRequestURI().startsWith("/api/payment/webhook/") || pattern.matcher(r.getMethod()).matches();
csrfWhitelistPredicate = csrfWhitelistPredicate.or(r -> r.getRequestURI().equals("/report-csp-violation"));
configurer.requireCsrfProtectionMatcher(new NegatedRequestMatcher(csrfWhitelistPredicate::test));
String[] ownershipRequired = new String[] { ADMIN_API + "/overridable-template", ADMIN_API + "/additional-services", ADMIN_API + "/events/*/additional-field", ADMIN_API + "/event/*/additional-services/", ADMIN_API + "/overridable-template/", ADMIN_API + "/events/*/promo-code", ADMIN_API + "/reservation/event/*/reservations/list", ADMIN_API + "/event/*/email/", ADMIN_API + "/event/*/waiting-queue/load", ADMIN_API + "/events/*/pending-payments", ADMIN_API + "/events/*/export", ADMIN_API + "/events/*/sponsor-scan/export", ADMIN_API + "/events/*/invoices/**", ADMIN_API + "/reservation/*/*/*/audit", ADMIN_API + "/subscription/*/email/", ADMIN_API + "/organization/*/subscription/**", ADMIN_API + "/reservation/subscription/**" };
configurer.csrfTokenRepository(csrfTokenRepository).and().headers().frameOptions().disable().and().authorizeRequests().antMatchers(HttpMethod.GET, ADMIN_API + "/users/current").hasAnyRole(ADMIN, OWNER, SUPERVISOR).antMatchers(HttpMethod.POST, ADMIN_API + "/users/check", ADMIN_API + "/users/current/edit", ADMIN_API + "/users/current/update-password").hasAnyRole(ADMIN, OWNER, SUPERVISOR).antMatchers(ADMIN_API + "/configuration/**", ADMIN_API + "/users/**").hasAnyRole(ADMIN, OWNER).antMatchers(ADMIN_API + "/organizations/new").hasRole(ADMIN).antMatchers(ADMIN_API + "/check-in/**").hasAnyRole(ADMIN, OWNER, SUPERVISOR).antMatchers(HttpMethod.GET, ownershipRequired).hasAnyRole(ADMIN, OWNER).antMatchers(HttpMethod.GET, ADMIN_API + "/**").hasAnyRole(ADMIN, OWNER, SUPERVISOR).antMatchers(HttpMethod.POST, ADMIN_API + "/reservation/event/*/new", ADMIN_API + "/reservation/event/*/*").hasAnyRole(ADMIN, OWNER, SUPERVISOR).antMatchers(HttpMethod.PUT, ADMIN_API + "/reservation/event/*/*/notify", ADMIN_API + "/reservation/event/*/*/confirm").hasAnyRole(ADMIN, OWNER, SUPERVISOR).antMatchers(ADMIN_API + "/**").hasAnyRole(ADMIN, OWNER).antMatchers("/admin/**/export/**").hasAnyRole(ADMIN, OWNER).antMatchers("/admin/**").hasAnyRole(ADMIN, OWNER, SUPERVISOR).antMatchers("/api/attendees/**").denyAll().antMatchers("/callback").permitAll().antMatchers("/**").permitAll().and().formLogin().loginPage("/authentication").loginProcessingUrl("/authenticate").failureUrl("/authentication?failed").and().logout().permitAll();
http.addFilterBefore(openIdPublicCallbackLoginFilter(publicOpenIdAuthenticationManager), UsernamePasswordAuthenticationFilter.class).addFilterBefore(openIdPublicAuthenticationFilter(publicOpenIdAuthenticationManager), AnonymousAuthenticationFilter.class);
//
http.addFilterBefore(new RecaptchaLoginFilter(recaptchaService, "/authenticate", "/authentication?recaptchaFailed", configurationManager), UsernamePasswordAuthenticationFilter.class);
// call implementation-specific logic
addAdditionalFilters(http);
// FIXME create session and set csrf cookie if we are getting a v2 public api, an admin api call , will switch to pure cookie based
http.addFilterBefore((servletRequest, servletResponse, filterChain) -> {
HttpServletRequest req = (HttpServletRequest) servletRequest;
HttpServletResponse res = (HttpServletResponse) servletResponse;
var reqUri = req.getRequestURI();
if ((reqUri.startsWith("/api/v2/public/") || reqUri.startsWith("/admin/api/") || reqUri.startsWith("/api/v2/admin/")) && "GET".equalsIgnoreCase(req.getMethod())) {
CsrfToken csrf = csrfTokenRepository.loadToken(req);
if (csrf == null) {
csrf = csrfTokenRepository.generateToken(req);
}
Cookie cookie = new Cookie("XSRF-TOKEN", csrf.getToken());
cookie.setPath("/");
res.addCookie(cookie);
}
filterChain.doFilter(servletRequest, servletResponse);
}, RecaptchaLoginFilter.class);
if (environment.acceptsProfiles(Profiles.of(Initializer.PROFILE_DEMO))) {
http.addFilterAfter(new UserCreatorBeforeLoginFilter(userManager, "/authenticate"), RecaptchaLoginFilter.class);
}
}
use of org.springframework.security.config.annotation.web.configurers.CsrfConfigurer in project spring-security by spring-projects.
the class HttpSecurity method csrf.
/**
* Enables CSRF protection. This is activated by default when using
* {@link WebSecurityConfigurerAdapter}'s default constructor. You can disable it
* using:
*
* <pre>
* @Configuration
* @EnableWebSecurity
* public class CsrfSecurityConfig extends WebSecurityConfigurerAdapter {
*
* @Override
* protected void configure(HttpSecurity http) throws Exception {
* http
* .csrf((csrf) -> csrf.disable());
* }
* }
* </pre>
* @param csrfCustomizer the {@link Customizer} to provide more options for the
* {@link CsrfConfigurer}
* @return the {@link HttpSecurity} for further customizations
* @throws Exception
*/
public HttpSecurity csrf(Customizer<CsrfConfigurer<HttpSecurity>> csrfCustomizer) throws Exception {
ApplicationContext context = getContext();
csrfCustomizer.customize(getOrApply(new CsrfConfigurer<>(context)));
return HttpSecurity.this;
}
Aggregations