@Test public void getWhenUsingCustomExpressionHandlerThenAuthorizesAccordingly() throws Exception { this.spring.configLocations(xml("ExpressionHandler")).autowire(); PermissionEvaluator permissionEvaluator = this.spring.getContext().getBean(PermissionEvaluator.class); when(permissionEvaluator.hasPermission(any(Authentication.class), any(Object.class), any(Object.class))) .thenReturn(false); this.mvc.perform(get("/") .with(httpBasic("user", "password"))) .andExpect(status().isForbidden()); verify(permissionEvaluator).hasPermission(any(Authentication.class), any(Object.class), any(Object.class)); }
@Test public void configureWhenRequestCacheProvidedAndClientAuthorizationRequiredExceptionThrownThenRequestCacheUsed() throws Exception { this.spring.register(OAuth2ClientConfig.class).autowire(); MvcResult mvcResult = this.mockMvc.perform(get("/resource1").with(user("user1"))) .andExpect(status().is3xxRedirection()) .andReturn(); assertThat(mvcResult.getResponse().getRedirectedUrl()).matches("https://provider.com/oauth2/authorize\\?" + "response_type=code&client_id=client-1&" + "scope=user&state=.{15,}&" + "redirect_uri=http://localhost/client-1"); verify(requestCache).saveRequest(any(HttpServletRequest.class), any(HttpServletResponse.class)); }
/** * SEC-1937 */ @Test public void requestWhenTargettingAuthenticationManagersToCorrespondingHttpElementsThenAuthenticationProceeds() throws Exception { this.spring.configLocations(this.xml("Sec1937")).autowire(); this.mvc.perform(get("/first") .with(httpBasic("first", "password")) .with(csrf())) .andExpect(status().isOk()); this.mvc.perform(post("/second/login") .param("username", "second") .param("password", "password") .with(csrf())) .andExpect(redirectedUrl("/")); }
@Test public void loginWhenUsingCustomAuthenticationDetailsSourceRefThenAuthenticationSourcesDetailsAccordingly() throws Exception { this.spring.configLocations(xml("CustomAuthenticationDetailsSourceRef")).autowire(); Object details = mock(Object.class); AuthenticationDetailsSource source = this.spring.getContext().getBean(AuthenticationDetailsSource.class); when(source.buildDetails(any(Object.class))).thenReturn(details); this.mvc.perform(get("/details") .with(httpBasic("user", "password"))) .andExpect(content().string(details.getClass().getName())); this.mvc.perform(get("/details") .with(x509("classpath:org/springframework/security/config/http/MiscHttpConfigTests-certificate.pem"))) .andExpect(content().string(details.getClass().getName())); MockHttpSession session = (MockHttpSession) this.mvc.perform(post("/login") .param("username", "user") .param("password", "password") .with(csrf())) .andReturn().getRequest().getSession(false); this.mvc.perform(get("/details") .session(session)) .andExpect(content().string(details.getClass().getName())); assertThat(getField(getFilter(OpenIDAuthenticationFilter.class), "authenticationDetailsSource")) .isEqualTo(source); }
@Test public void logoutWhenSpecifyingCookiesToDeleteThenSetCookieAdded() throws Exception { this.spring.configLocations(xml("DeleteCookies")).autowire(); MvcResult result = this.mvc.perform(post("/logout").with(csrf())).andReturn(); List<String> values = result.getResponse().getHeaders("Set-Cookie"); assertThat(values.size()).isEqualTo(2); assertThat(values).extracting(value -> value.split("=")[0]).contains("JSESSIONID", "mycookie"); }
@Test public void getWhenUsingX509AndPropertyPlaceholderThenSubjectPrincipalRegexIsConfigured() throws Exception { System.setProperty("subject_principal_regex", "OU=(.*?)(?:,|$)"); this.spring.configLocations(xml("X509")).autowire(); this.mvc.perform(get("/protected") .with(x509("classpath:org/springframework/security/config/http/MiscHttpConfigTests-certificate.pem"))) .andExpect(status().isOk()); }
@Override public RequestPostProcessor beforeMockMvcCreated( ConfigurableMockMvcBuilder<?> builder, WebApplicationContext context) { return SecurityMockMvcRequestPostProcessors.testSecurityContext(); }
/** * Creates a DigestRequestPostProcessor that enables easily adding digest based * authentication to a request. * * @param username the username to use * @return the DigestRequestPostProcessor to use */ public static DigestRequestPostProcessor digest(String username) { return digest().username(username); }
@Test public void t005_testCurationDelete() throws Exception { mvc.perform(delete(API_BASE + "/projects/1/documents/1/curation") .with(csrf().asHeader()) .with(user("admin").roles("ADMIN")) .param("projectId", "1") .param("documentId", "1")) .andExpect(status().isOk()) .andExpect(content().contentType("application/json;charset=UTF-8")); mvc.perform(get(API_BASE + "/projects/1/documents") .with(csrf().asHeader()) .with(user("admin").roles("ADMIN"))) .andExpect(status().isOk()) .andExpect(content().contentType("application/json;charset=UTF-8")) .andExpect(jsonPath("$.body[0].id").value("1")) .andExpect(jsonPath("$.body[0].name").value("test.txt")) .andExpect(jsonPath("$.body[0].state").value("ANNOTATION-IN-PROGRESS")); }
private static RequestBuilder formLogin(MockHttpSession session) { return post("/login") .param("username", "user") .param("password", "password") .session(session) .with(csrf()); } }
/** * Finds an X509Cetificate using a resoureName and populates it on the request. * * @param resourceName the name of the X509Certificate resource * @return the * {@link org.springframework.test.web.servlet.request.RequestPostProcessor} to use. * @throws IOException * @throws CertificateException */ public static RequestPostProcessor x509(String resourceName) throws IOException, CertificateException { ResourceLoader loader = new DefaultResourceLoader(); Resource resource = loader.getResource(resourceName); InputStream inputStream = resource.getInputStream(); CertificateFactory certFactory = CertificateFactory.getInstance("X.509"); X509Certificate certificate = (X509Certificate) certFactory .generateCertificate(inputStream); return x509(certificate); }
@Override public RequestPostProcessor beforeMockMvcCreated( ConfigurableMockMvcBuilder<?> builder, WebApplicationContext context) { String securityBeanId = BeanIds.SPRING_SECURITY_FILTER_CHAIN; if (this.springSecurityFilterChain == null && context.containsBean(securityBeanId)) { this.springSecurityFilterChain = context.getBean(securityBeanId, Filter.class); } if (this.springSecurityFilterChain == null) { throw new IllegalStateException( "springSecurityFilterChain cannot be null. Ensure a Bean with the name " + securityBeanId + " implementing Filter is present or inject the Filter to be used."); } builder.addFilters(this.springSecurityFilterChain); context.getServletContext().setAttribute(BeanIds.SPRING_SECURITY_FILTER_CHAIN, this.springSecurityFilterChain); return testSecurityContext(); } }
/** * Creates a DigestRequestPostProcessor that enables easily adding digest based * authentication to a request. * * @param username the username to use * @return the DigestRequestPostProcessor to use */ public static DigestRequestPostProcessor digest(String username) { return digest().username(username); }
@Test public void loginWhenUsingJaasApiProvisionThenJaasSubjectContainsUsername() throws Exception { this.spring.configLocations(xml("Jaas")).autowire(); AuthorityGranter granter = this.spring.getContext().getBean(AuthorityGranter.class); when(granter.grant(any(Principal.class))).thenReturn(new HashSet<>(Arrays.asList("USER"))); this.mvc.perform(get("/username") .with(httpBasic("user", "password"))) .andExpect(content().string("user")); }
@Test public void requestWhenInterceptUrlMatchesMethodAndRequiresHttpsThenSecuresAccordingly() throws Exception { this.spring.configLocations(xml("InterceptUrlMethodRequiresHttps")).autowire(); this.mvc.perform(post("/protected").with(csrf())) .andExpect(status().isOk()); this.mvc.perform(get("/protected") .secure(true) .with(httpBasic("user", "password"))) .andExpect(status().isForbidden()); this.mvc.perform(get("/protected") .secure(true) .with(httpBasic("admin", "password"))) .andExpect(status().isOk()); }
@Test public void saveAdminAuthority() throws Exception { // Arrange User user = User.builder().build(); when(userService.save(user)).thenReturn(user); mvc.perform(post("/addUser") .with(csrf()) .with(user(randomString()).password(randomString()).authorities(ADMIN)) .contentType(MediaType.APPLICATION_FORM_URLENCODED)) .andExpect(status().isFound()) .andExpect(view().name("redirect:/index")) .andExpect(model().attribute("user", equalTo(user))) .andExpect(model().attribute("user", hasProperty("username", isEmptyOrNullString()))) .andExpect(model().attribute("user", hasProperty("password", isEmptyOrNullString()))) .andExpect(model().attribute("user", hasProperty("role", isEmptyOrNullString()))); // Assert verify(userService).save(any(User.class)); } }
@Test public void requestWhenCreateSessionIsSetToNeverThenUsesExistingSession() throws Exception { this.spring.configLocations(this.xml("CreateSessionNever")).autowire(); MockHttpServletRequest request = post("/login") .param("username", "user") .param("password", "password") .buildRequest(this.servletContext()); request = csrf().postProcessRequest(request); MockHttpSession session = new MockHttpSession(); request.setSession(session); MockHttpServletResponse response = request(request, this.spring.getContext()); assertThat(response.getStatus()).isEqualTo(HttpStatus.SC_MOVED_TEMPORARILY); assertThat(request.getSession(false)).isNotNull(); assertThat(request.getSession(false).getAttribute(SPRING_SECURITY_CONTEXT_KEY)) .isNotNull(); }
@Test // http@access-denied-page public void configureWhenAccessDeniedPageSetAndRequestForbiddenThenForwardedToAccessDeniedPage() throws Exception { this.spring.register(AccessDeniedPageConfig.class).autowire(); this.mockMvc.perform(get("/admin").with(user(PasswordEncodedUser.user()))) .andExpect(status().isForbidden()) .andExpect(forwardedUrl("/AccessDeniedPage")); }
/** * Finds an X509Cetificate using a resoureName and populates it on the request. * * @param resourceName the name of the X509Certificate resource * @return the * {@link org.springframework.test.web.servlet.request.RequestPostProcessor} to use. * @throws IOException * @throws CertificateException */ public static RequestPostProcessor x509(String resourceName) throws IOException, CertificateException { ResourceLoader loader = new DefaultResourceLoader(); Resource resource = loader.getResource(resourceName); InputStream inputStream = resource.getInputStream(); CertificateFactory certFactory = CertificateFactory.getInstance("X.509"); X509Certificate certificate = (X509Certificate) certFactory .generateCertificate(inputStream); return x509(certificate); }