Search in sources :

Example 21 with CsrfToken

use of org.springframework.security.web.csrf.CsrfToken in project hub-alert by blackducksoftware.

the class HomeActionsTest method testVerifyAuthenticationInvalidAuthentication.

@Test
public void testVerifyAuthenticationInvalidAuthentication() {
    CsrfToken token = Mockito.mock(CsrfToken.class);
    GrantedAuthority grantedAuthority = Mockito.mock(GrantedAuthority.class);
    Collection<GrantedAuthority> grantedAuthorities = List.of(grantedAuthority);
    Authentication authentication = Mockito.mock(Authentication.class);
    SecurityContext securityContext = Mockito.mock(SecurityContext.class);
    SecurityContextHolder.setContext(securityContext);
    csrfTokenRepository.saveToken(token, servletRequest, servletResponse);
    Mockito.when(token.getHeaderName()).thenReturn("csrfHeaderName");
    Mockito.when(token.getToken()).thenReturn("csrftoken");
    Mockito.when(grantedAuthority.getAuthority()).thenReturn("ValidRole");
    Mockito.doReturn(grantedAuthorities).when(authentication).getAuthorities();
    Mockito.when(authentication.isAuthenticated()).thenReturn(Boolean.FALSE);
    Mockito.when(securityContext.getAuthentication()).thenReturn(authentication);
    HomeActions actions = new HomeActions(csrfTokenRepository, null);
    ActionResponse<Void> response = actions.verifyAuthentication(servletRequest, servletResponse);
    assertTrue(response.isError());
    assertFalse(response.hasContent());
    assertEquals(HttpStatus.UNAUTHORIZED, response.getHttpStatus());
}
Also used : Authentication(org.springframework.security.core.Authentication) GrantedAuthority(org.springframework.security.core.GrantedAuthority) SecurityContext(org.springframework.security.core.context.SecurityContext) CsrfToken(org.springframework.security.web.csrf.CsrfToken) Test(org.junit.jupiter.api.Test)

Example 22 with CsrfToken

use of org.springframework.security.web.csrf.CsrfToken in project hub-alert by blackducksoftware.

the class HomeActionsTest method testVerifyAuthenticationValid.

@Test
public void testVerifyAuthenticationValid() {
    CsrfToken token = Mockito.mock(CsrfToken.class);
    GrantedAuthority grantedAuthority = Mockito.mock(GrantedAuthority.class);
    Collection<GrantedAuthority> grantedAuthorities = List.of(grantedAuthority);
    Authentication authentication = Mockito.mock(Authentication.class);
    SecurityContext securityContext = Mockito.mock(SecurityContext.class);
    SecurityContextHolder.setContext(securityContext);
    csrfTokenRepository.saveToken(token, servletRequest, servletResponse);
    Mockito.when(token.getHeaderName()).thenReturn("csrfHeaderName");
    Mockito.when(token.getToken()).thenReturn("csrftoken");
    Mockito.when(grantedAuthority.getAuthority()).thenReturn("ValidRole");
    Mockito.doReturn(grantedAuthorities).when(authentication).getAuthorities();
    Mockito.when(authentication.isAuthenticated()).thenReturn(Boolean.TRUE);
    Mockito.when(securityContext.getAuthentication()).thenReturn(authentication);
    HomeActions actions = new HomeActions(csrfTokenRepository, null);
    ActionResponse<Void> response = actions.verifyAuthentication(servletRequest, servletResponse);
    assertTrue(response.isSuccessful());
    assertFalse(response.hasContent());
}
Also used : Authentication(org.springframework.security.core.Authentication) GrantedAuthority(org.springframework.security.core.GrantedAuthority) SecurityContext(org.springframework.security.core.context.SecurityContext) CsrfToken(org.springframework.security.web.csrf.CsrfToken) Test(org.junit.jupiter.api.Test)

Example 23 with CsrfToken

use of org.springframework.security.web.csrf.CsrfToken in project hub-alert by blackducksoftware.

the class HomeActionsTest method testVerifyAuthenticationInvalidAnonymousUser.

@Test
public void testVerifyAuthenticationInvalidAnonymousUser() {
    CsrfToken token = Mockito.mock(CsrfToken.class);
    GrantedAuthority grantedAuthority = Mockito.mock(GrantedAuthority.class);
    Collection<GrantedAuthority> grantedAuthorities = List.of(grantedAuthority);
    Authentication authentication = Mockito.mock(Authentication.class);
    SecurityContext securityContext = Mockito.mock(SecurityContext.class);
    SecurityContextHolder.setContext(securityContext);
    csrfTokenRepository.saveToken(token, servletRequest, servletResponse);
    Mockito.when(token.getHeaderName()).thenReturn("csrfHeaderName");
    Mockito.when(token.getToken()).thenReturn("csrftoken");
    Mockito.when(grantedAuthority.getAuthority()).thenReturn(HomeActions.ROLE_ANONYMOUS);
    Mockito.doReturn(grantedAuthorities).when(authentication).getAuthorities();
    Mockito.when(authentication.isAuthenticated()).thenReturn(Boolean.TRUE);
    Mockito.when(securityContext.getAuthentication()).thenReturn(authentication);
    HomeActions actions = new HomeActions(csrfTokenRepository, null);
    ActionResponse<Void> response = actions.verifyAuthentication(servletRequest, servletResponse);
    assertTrue(response.isError());
    assertFalse(response.hasContent());
    assertEquals(HttpStatus.UNAUTHORIZED, response.getHttpStatus());
}
Also used : Authentication(org.springframework.security.core.Authentication) GrantedAuthority(org.springframework.security.core.GrantedAuthority) SecurityContext(org.springframework.security.core.context.SecurityContext) CsrfToken(org.springframework.security.web.csrf.CsrfToken) Test(org.junit.jupiter.api.Test)

Example 24 with CsrfToken

use of org.springframework.security.web.csrf.CsrfToken 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 25 with CsrfToken

use of org.springframework.security.web.csrf.CsrfToken in project spring-security by spring-projects.

the class SessionManagementConfigurerServlet31Tests method changeSessionIdDefaultsInServlet31Plus.

@Test
public void changeSessionIdDefaultsInServlet31Plus() throws Exception {
    spy(ReflectionUtils.class);
    Method method = mock(Method.class);
    MockHttpServletRequest request = new MockHttpServletRequest();
    request.getSession();
    request.setServletPath("/login");
    request.setMethod("POST");
    request.setParameter("username", "user");
    request.setParameter("password", "password");
    HttpSessionCsrfTokenRepository repository = new HttpSessionCsrfTokenRepository();
    CsrfToken token = repository.generateToken(request);
    repository.saveToken(token, request, response);
    request.setParameter(token.getParameterName(), token.getToken());
    when(ReflectionUtils.findMethod(HttpServletRequest.class, "changeSessionId")).thenReturn(method);
    loadConfig(SessionManagementDefaultSessionFixationServlet31Config.class);
    springSecurityFilterChain.doFilter(request, response, chain);
    verifyStatic();
    ReflectionUtils.invokeMethod(same(method), any(HttpServletRequest.class));
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) MockHttpServletRequest(org.springframework.mock.web.MockHttpServletRequest) MockHttpServletRequest(org.springframework.mock.web.MockHttpServletRequest) Method(java.lang.reflect.Method) HttpSessionCsrfTokenRepository(org.springframework.security.web.csrf.HttpSessionCsrfTokenRepository) CsrfToken(org.springframework.security.web.csrf.CsrfToken) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest) Test(org.junit.Test)

Aggregations

CsrfToken (org.springframework.security.web.csrf.CsrfToken)48 Test (org.junit.jupiter.api.Test)28 DefaultCsrfToken (org.springframework.security.web.csrf.DefaultCsrfToken)17 MockHttpServletRequest (org.springframework.mock.web.MockHttpServletRequest)11 HttpServletRequest (javax.servlet.http.HttpServletRequest)8 HttpSessionCsrfTokenRepository (org.springframework.security.web.csrf.HttpSessionCsrfTokenRepository)8 Authentication (org.springframework.security.core.Authentication)6 Cookie (javax.servlet.http.Cookie)5 HashMap (java.util.HashMap)3 ServletContext (javax.servlet.ServletContext)3 HttpServletResponse (javax.servlet.http.HttpServletResponse)3 MockHttpServletResponse (org.springframework.mock.web.MockHttpServletResponse)3 GrantedAuthority (org.springframework.security.core.GrantedAuthority)3 SecurityContext (org.springframework.security.core.context.SecurityContext)3 MockHttpServletRequestBuilder (org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder)3 ActionResponse (com.synopsys.integration.alert.common.action.ActionResponse)2 FilterChain (javax.servlet.FilterChain)2 HttpHeaders (org.springframework.http.HttpHeaders)2 MockFilterChain (org.springframework.mock.web.MockFilterChain)2 MockHttpSession (org.springframework.mock.web.MockHttpSession)2