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());
}
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());
}
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());
}
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);
}
}
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));
}
Aggregations