Search in sources :

Example 1 with CsrfConfigurer

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);
    }
}
Also used : NegatedRequestMatcher(org.springframework.security.web.util.matcher.NegatedRequestMatcher) RecaptchaService(alfio.manager.RecaptchaService) ConfigurationManager(alfio.manager.system.ConfigurationManager) HttpSecurity(org.springframework.security.config.annotation.web.builders.HttpSecurity) StringUtils(org.apache.commons.lang3.StringUtils) CsrfConfigurer(org.springframework.security.config.annotation.web.configurers.CsrfConfigurer) WebSecurityConfigurerAdapter(org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter) AuthenticationManagerBuilder(org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder) HttpServletRequest(javax.servlet.http.HttpServletRequest) AccessLevel(lombok.AccessLevel) RequestHeaderRequestMatcher(org.springframework.security.web.util.matcher.RequestHeaderRequestMatcher) Profiles(org.springframework.core.env.Profiles) DataSource(javax.sql.DataSource) Cookie(javax.servlet.http.Cookie) AnonymousAuthenticationFilter(org.springframework.security.web.authentication.AnonymousAuthenticationFilter) OpenIdAuthenticationFilter(alfio.config.authentication.support.OpenIdAuthenticationFilter) Predicate(java.util.function.Predicate) RequestDispatcher(javax.servlet.RequestDispatcher) OpenIdAuthenticationManager(alfio.manager.openid.OpenIdAuthenticationManager) HttpMethod(org.springframework.http.HttpMethod) HttpServletResponse(javax.servlet.http.HttpServletResponse) Initializer(alfio.config.Initializer) PublicOpenIdAuthenticationManager(alfio.manager.openid.PublicOpenIdAuthenticationManager) PasswordEncoder(org.springframework.security.crypto.password.PasswordEncoder) alfio.config.authentication.support(alfio.config.authentication.support) UsernamePasswordAuthenticationFilter(org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter) Environment(org.springframework.core.env.Environment) AuthenticationConstants(alfio.config.authentication.AuthenticationConstants) UserManager(alfio.manager.user.UserManager) Pattern(java.util.regex.Pattern) AllArgsConstructor(lombok.AllArgsConstructor) CsrfToken(org.springframework.security.web.csrf.CsrfToken) CsrfTokenRepository(org.springframework.security.web.csrf.CsrfTokenRepository) AntPathRequestMatcher(org.springframework.security.web.util.matcher.AntPathRequestMatcher) NegatedRequestMatcher(org.springframework.security.web.util.matcher.NegatedRequestMatcher) Cookie(javax.servlet.http.Cookie) Pattern(java.util.regex.Pattern) UsernamePasswordAuthenticationFilter(org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter) HttpServletResponse(javax.servlet.http.HttpServletResponse) RequestHeaderRequestMatcher(org.springframework.security.web.util.matcher.RequestHeaderRequestMatcher) CsrfToken(org.springframework.security.web.csrf.CsrfToken) RequestDispatcher(javax.servlet.RequestDispatcher) HttpServletRequest(javax.servlet.http.HttpServletRequest) HttpSecurity(org.springframework.security.config.annotation.web.builders.HttpSecurity)

Example 2 with CsrfConfigurer

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>
 * &#064;Configuration
 * &#064;EnableWebSecurity
 * public class CsrfSecurityConfig extends WebSecurityConfigurerAdapter {
 *
 * 	&#064;Override
 *     protected void configure(HttpSecurity http) throws Exception {
 *         http
 *             .csrf((csrf) -&gt; 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;
}
Also used : ApplicationContext(org.springframework.context.ApplicationContext) CsrfConfigurer(org.springframework.security.config.annotation.web.configurers.CsrfConfigurer)

Aggregations

CsrfConfigurer (org.springframework.security.config.annotation.web.configurers.CsrfConfigurer)2 Initializer (alfio.config.Initializer)1 AuthenticationConstants (alfio.config.authentication.AuthenticationConstants)1 alfio.config.authentication.support (alfio.config.authentication.support)1 OpenIdAuthenticationFilter (alfio.config.authentication.support.OpenIdAuthenticationFilter)1 RecaptchaService (alfio.manager.RecaptchaService)1 OpenIdAuthenticationManager (alfio.manager.openid.OpenIdAuthenticationManager)1 PublicOpenIdAuthenticationManager (alfio.manager.openid.PublicOpenIdAuthenticationManager)1 ConfigurationManager (alfio.manager.system.ConfigurationManager)1 UserManager (alfio.manager.user.UserManager)1 Predicate (java.util.function.Predicate)1 Pattern (java.util.regex.Pattern)1 RequestDispatcher (javax.servlet.RequestDispatcher)1 Cookie (javax.servlet.http.Cookie)1 HttpServletRequest (javax.servlet.http.HttpServletRequest)1 HttpServletResponse (javax.servlet.http.HttpServletResponse)1 DataSource (javax.sql.DataSource)1 AccessLevel (lombok.AccessLevel)1 AllArgsConstructor (lombok.AllArgsConstructor)1 StringUtils (org.apache.commons.lang3.StringUtils)1