repo stringlengths 1 191 ⌀ | file stringlengths 23 351 | code stringlengths 0 5.32M | file_length int64 0 5.32M | avg_line_length float64 0 2.9k | max_line_length int64 0 288k | extension_type stringclasses 1 value |
|---|---|---|---|---|---|---|
null | spring-security-main/test/src/test/java/org/springframework/security/test/web/servlet/request/SecurityMockMvcRequestBuildersFormLogoutTests.java | /*
* Copyright 2002-2014 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.test.web.servlet.request;
import java.util.Arrays;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockServletContext;
import org.springframework.security.web.csrf.CsrfToken;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.request.RequestPostProcessor;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestBuilders.logout;
public class SecurityMockMvcRequestBuildersFormLogoutTests {
private MockServletContext servletContext;
@BeforeEach
public void setup() {
this.servletContext = new MockServletContext();
}
@Test
public void defaults() {
MockHttpServletRequest request = logout().buildRequest(this.servletContext);
CsrfToken token = (CsrfToken) request.getAttribute(CsrfToken.class.getName());
assertThat(request.getMethod()).isEqualTo("POST");
assertThat(request.getParameter(token.getParameterName())).isEqualTo(token.getToken());
assertThat(request.getRequestURI()).isEqualTo("/logout");
}
@Test
public void custom() {
MockHttpServletRequest request = logout("/admin/logout").buildRequest(this.servletContext);
CsrfToken token = (CsrfToken) request.getAttribute(CsrfToken.class.getName());
assertThat(request.getMethod()).isEqualTo("POST");
assertThat(request.getParameter(token.getParameterName())).isEqualTo(token.getToken());
assertThat(request.getRequestURI()).isEqualTo("/admin/logout");
}
@Test
public void customWithUriVars() {
MockHttpServletRequest request = logout().logoutUrl("/uri-logout/{var1}/{var2}", "val1", "val2")
.buildRequest(this.servletContext);
CsrfToken token = (CsrfToken) request.getAttribute(CsrfToken.class.getName());
assertThat(request.getMethod()).isEqualTo("POST");
assertThat(request.getParameter(token.getParameterName())).isEqualTo(token.getToken());
assertThat(request.getRequestURI()).isEqualTo("/uri-logout/val1/val2");
}
/**
* spring-restdocs uses postprocessors to do its trick. It will work only if these are
* merged together with our request builders. (gh-7572)
* @throws Exception
*/
@Test
public void postProcessorsAreMergedDuringMockMvcPerform() throws Exception {
RequestPostProcessor postProcessor = mock(RequestPostProcessor.class);
given(postProcessor.postProcessRequest(any())).willAnswer((i) -> i.getArgument(0));
MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new Object())
.defaultRequest(MockMvcRequestBuilders.get("/").with(postProcessor)).build();
MvcResult mvcResult = mockMvc.perform(logout()).andReturn();
assertThat(mvcResult.getRequest().getMethod()).isEqualTo(HttpMethod.POST.name());
assertThat(mvcResult.getRequest().getHeader("Accept"))
.isEqualTo(MediaType.toString(Arrays.asList(MediaType.TEXT_HTML, MediaType.ALL)));
assertThat(mvcResult.getRequest().getRequestURI()).isEqualTo("/logout");
assertThat(mvcResult.getRequest().getParameter("_csrf")).isNotEmpty();
verify(postProcessor).postProcessRequest(any());
}
}
| 4,279 | 41.8 | 106 | java |
null | spring-security-main/test/src/test/java/org/springframework/security/test/web/servlet/request/SecurityMockMvcRequestBuildersFormLoginTests.java | /*
* Copyright 2002-2014 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.test.web.servlet.request;
import java.util.Arrays;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockServletContext;
import org.springframework.security.web.csrf.CsrfToken;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.request.RequestPostProcessor;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestBuilders.formLogin;
public class SecurityMockMvcRequestBuildersFormLoginTests {
private MockServletContext servletContext;
@BeforeEach
public void setup() {
this.servletContext = new MockServletContext();
}
@Test
public void defaults() {
MockHttpServletRequest request = formLogin().buildRequest(this.servletContext);
CsrfToken token = (CsrfToken) request.getAttribute(CsrfToken.class.getName());
assertThat(request.getParameter("username")).isEqualTo("user");
assertThat(request.getParameter("password")).isEqualTo("password");
assertThat(request.getMethod()).isEqualTo("POST");
assertThat(request.getParameter(token.getParameterName())).isEqualTo(token.getToken());
assertThat(request.getRequestURI()).isEqualTo("/login");
assertThat(request.getParameter("_csrf")).isNotNull();
}
@Test
public void custom() {
MockHttpServletRequest request = formLogin("/login").user("username", "admin").password("password", "secret")
.buildRequest(this.servletContext);
CsrfToken token = (CsrfToken) request.getAttribute(CsrfToken.class.getName());
assertThat(request.getParameter("username")).isEqualTo("admin");
assertThat(request.getParameter("password")).isEqualTo("secret");
assertThat(request.getMethod()).isEqualTo("POST");
assertThat(request.getParameter(token.getParameterName())).isEqualTo(token.getToken());
assertThat(request.getRequestURI()).isEqualTo("/login");
}
@Test
public void customWithUriVars() {
MockHttpServletRequest request = formLogin().loginProcessingUrl("/uri-login/{var1}/{var2}", "val1", "val2")
.user("username", "admin").password("password", "secret").buildRequest(this.servletContext);
CsrfToken token = (CsrfToken) request.getAttribute(CsrfToken.class.getName());
assertThat(request.getParameter("username")).isEqualTo("admin");
assertThat(request.getParameter("password")).isEqualTo("secret");
assertThat(request.getMethod()).isEqualTo("POST");
assertThat(request.getParameter(token.getParameterName())).isEqualTo(token.getToken());
assertThat(request.getRequestURI()).isEqualTo("/uri-login/val1/val2");
}
/**
* spring-restdocs uses postprocessors to do its trick. It will work only if these are
* merged together with our request builders. (gh-7572)
* @throws Exception
*/
@Test
public void postProcessorsAreMergedDuringMockMvcPerform() throws Exception {
RequestPostProcessor postProcessor = mock(RequestPostProcessor.class);
given(postProcessor.postProcessRequest(any())).willAnswer((i) -> i.getArgument(0));
MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new Object())
.defaultRequest(MockMvcRequestBuilders.get("/").with(postProcessor)).build();
MvcResult mvcResult = mockMvc.perform(formLogin()).andReturn();
assertThat(mvcResult.getRequest().getMethod()).isEqualTo(HttpMethod.POST.name());
assertThat(mvcResult.getRequest().getHeader("Accept"))
.isEqualTo(MediaType.toString(Arrays.asList(MediaType.APPLICATION_FORM_URLENCODED)));
assertThat(mvcResult.getRequest().getParameter("username")).isEqualTo("user");
assertThat(mvcResult.getRequest().getParameter("password")).isEqualTo("password");
assertThat(mvcResult.getRequest().getRequestURI()).isEqualTo("/login");
assertThat(mvcResult.getRequest().getParameter("_csrf")).isNotEmpty();
verify(postProcessor).postProcessRequest(any());
}
// gh-3920
@Test
public void usesAcceptMediaForContentNegotiation() {
MockHttpServletRequest request = formLogin("/login").user("username", "admin").password("password", "secret")
.buildRequest(this.servletContext);
assertThat(request.getHeader("Accept")).isEqualTo(MediaType.APPLICATION_FORM_URLENCODED_VALUE);
}
}
| 5,362 | 44.449153 | 111 | java |
null | spring-security-main/test/src/test/java/org/springframework/security/test/web/servlet/request/SecurityMockMvcRequestPostProcessorsTestSecurityContextStatelessTests.java | /*
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.test.web.servlet.request;
import jakarta.servlet.Filter;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.test.context.support.WithMockUser;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.testSecurityContext;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@ExtendWith(SpringExtension.class)
@ContextConfiguration(classes = SecurityMockMvcRequestPostProcessorsTestSecurityContextStatelessTests.Config.class)
@WebAppConfiguration
public class SecurityMockMvcRequestPostProcessorsTestSecurityContextStatelessTests {
@Autowired
private WebApplicationContext context;
@Autowired
private Filter springSecurityFilterChain;
private MockMvc mvc;
@BeforeEach
public void setup() {
this.mvc = MockMvcBuilders.webAppContextSetup(this.context).addFilters(this.springSecurityFilterChain)
.defaultRequest(get("/").with(testSecurityContext())).build();
}
@Test
@WithMockUser
public void testSecurityContextWithMockUserWorksWithStateless() throws Exception {
this.mvc.perform(get("/")).andExpect(status().is2xxSuccessful());
}
@Configuration
@EnableWebSecurity
@EnableWebMvc
static class Config {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS);
return http.build();
// @formatter:on
}
@Autowired
void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication();
}
@RestController
static class Controller {
@RequestMapping("/")
String hello() {
return "Hello";
}
}
}
}
| 3,742 | 34.647619 | 125 | java |
null | spring-security-main/test/src/test/java/org/springframework/security/test/web/servlet/request/SecurityMockMvcRequestPostProcessorsCsrfTests.java | /*
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.test.web.servlet.request;
import java.io.IOException;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletRequestWrapper;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.mock.web.MockHttpSession;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessorsCsrfTests.Config.TheController;
import org.springframework.security.web.FilterChainProxy;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.csrf.CsrfToken;
import org.springframework.security.web.csrf.CsrfTokenRequestHandler;
import org.springframework.security.web.csrf.DeferredCsrfToken;
import org.springframework.security.web.csrf.HttpSessionCsrfTokenRepository;
import org.springframework.security.web.csrf.XorCsrfTokenRequestAttributeHandler;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.ResultMatcher;
import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.filter.OncePerRequestFilter;
import static org.assertj.core.api.Assertions.assertThat;
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf;
import static org.springframework.security.test.web.servlet.setup.SecurityMockMvcConfigurers.springSecurity;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@ExtendWith(SpringExtension.class)
@ContextConfiguration
@WebAppConfiguration
public class SecurityMockMvcRequestPostProcessorsCsrfTests {
@Autowired
WebApplicationContext wac;
@Autowired
TheController controller;
@Autowired
FilterChainProxy springSecurityFilterChain;
MockMvc mockMvc;
@BeforeEach
public void setup() {
// @formatter:off
this.mockMvc = MockMvcBuilders
.webAppContextSetup(this.wac)
.apply(springSecurity())
.build();
// @formatter:on
}
// gh-3881
@Test
public void csrfWithStandalone() throws Exception {
// @formatter:off
this.mockMvc = MockMvcBuilders
.standaloneSetup(this.controller)
.apply(springSecurity(this.springSecurityFilterChain))
.build();
this.mockMvc.perform(post("/").with(csrf()))
.andExpect(status().is2xxSuccessful())
.andExpect(csrfAsParam());
// @formatter:on
}
@Test
public void csrfWithParam() throws Exception {
// @formatter:off
this.mockMvc.perform(post("/").with(csrf()))
.andExpect(status().is2xxSuccessful())
.andExpect(csrfAsParam());
// @formatter:on
}
@Test
public void csrfWithHeader() throws Exception {
// @formatter:off
this.mockMvc.perform(post("/").with(csrf().asHeader()))
.andExpect(status().is2xxSuccessful())
.andExpect(csrfAsHeader());
// @formatter:on
}
@Test
public void csrfWithInvalidParam() throws Exception {
// @formatter:off
this.mockMvc.perform(post("/").with(csrf().useInvalidToken()))
.andExpect(status().isForbidden())
.andExpect(csrfAsParam());
// @formatter:on
}
@Test
public void csrfWithInvalidHeader() throws Exception {
// @formatter:off
this.mockMvc.perform(post("/").with(csrf().asHeader().useInvalidToken()))
.andExpect(status().isForbidden())
.andExpect(csrfAsHeader());
// @formatter:on
}
// SEC-3097
@Test
public void csrfWithWrappedRequest() throws Exception {
// @formatter:off
this.mockMvc = MockMvcBuilders
.webAppContextSetup(this.wac)
.addFilter(new SessionRepositoryFilter())
.apply(springSecurity())
.build();
this.mockMvc.perform(post("/").with(csrf()))
.andExpect(status().is2xxSuccessful())
.andExpect(csrfAsParam());
// @formatter:on
}
// gh-4016
@Test
public void csrfWhenUsedThenDoesNotImpactOriginalRepository() throws Exception {
// @formatter:off
this.mockMvc.perform(post("/").with(csrf()));
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
HttpSessionCsrfTokenRepository repo = new HttpSessionCsrfTokenRepository();
CsrfTokenRequestHandler handler = new XorCsrfTokenRequestAttributeHandler();
DeferredCsrfToken deferredCsrfToken = repo.loadDeferredToken(request, response);
handler.handle(request, response, deferredCsrfToken::get);
CsrfToken token = (CsrfToken) request.getAttribute(CsrfToken.class.getName());
MockHttpServletRequestBuilder requestWithCsrf = post("/")
.param(token.getParameterName(), token.getToken())
.session((MockHttpSession) request.getSession());
this.mockMvc.perform(requestWithCsrf)
.andExpect(status().isOk());
// @formatter:on
}
public static ResultMatcher csrfAsParam() {
return new CsrfParamResultMatcher();
}
public static ResultMatcher csrfAsHeader() {
return new CsrfHeaderResultMatcher();
}
static class CsrfParamResultMatcher implements ResultMatcher {
@Override
public void match(MvcResult result) {
MockHttpServletRequest request = result.getRequest();
assertThat(request.getParameter("_csrf")).isNotNull();
assertThat(request.getHeader("X-CSRF-TOKEN")).isNull();
}
}
static class CsrfHeaderResultMatcher implements ResultMatcher {
@Override
public void match(MvcResult result) {
MockHttpServletRequest request = result.getRequest();
assertThat(request.getParameter("_csrf")).isNull();
assertThat(request.getHeader("X-CSRF-TOKEN")).isNotNull();
}
}
static class SessionRepositoryFilter extends OncePerRequestFilter {
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
FilterChain filterChain) throws ServletException, IOException {
filterChain.doFilter(new SessionRequestWrapper(request), response);
}
static class SessionRequestWrapper extends HttpServletRequestWrapper {
HttpSession session = new MockHttpSession();
SessionRequestWrapper(HttpServletRequest request) {
super(request);
}
@Override
public HttpSession getSession(boolean create) {
return this.session;
}
@Override
public HttpSession getSession() {
return this.session;
}
}
}
@Configuration
@EnableWebSecurity
static class Config {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
return http.build();
}
@RestController
static class TheController {
@RequestMapping("/")
String index() {
return "Hi";
}
}
}
}
| 8,376 | 31.343629 | 128 | java |
null | spring-security-main/test/src/test/java/org/springframework/security/test/web/servlet/request/SecurityMockMvcRequestPostProcessorsDigestTests.java | /*
* Copyright 2002-2014 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.test.web.servlet.request;
import java.io.IOException;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.mock.web.MockFilterChain;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.web.authentication.www.DigestAuthenticationEntryPoint;
import org.springframework.security.web.authentication.www.DigestAuthenticationFilter;
import static org.assertj.core.api.Assertions.assertThat;
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.digest;
public class SecurityMockMvcRequestPostProcessorsDigestTests {
private DigestAuthenticationFilter filter;
private MockHttpServletRequest request;
private String username;
private String password;
private DigestAuthenticationEntryPoint entryPoint;
@BeforeEach
public void setup() {
this.password = "password";
this.request = new MockHttpServletRequest();
this.entryPoint = new DigestAuthenticationEntryPoint();
this.entryPoint.setKey("key");
this.entryPoint.setRealmName("Spring Security");
this.filter = new DigestAuthenticationFilter();
this.filter.setUserDetailsService(
(username) -> new User(username, this.password, AuthorityUtils.createAuthorityList("ROLE_USER")));
this.filter.setAuthenticationEntryPoint(this.entryPoint);
this.filter.afterPropertiesSet();
}
@AfterEach
public void cleanup() {
SecurityContextHolder.clearContext();
}
@Test
public void digestWithFilter() throws Exception {
MockHttpServletRequest postProcessedRequest = digest().postProcessRequest(this.request);
assertThat(extractUser()).isEqualTo("user");
}
@Test
public void digestWithFilterCustomUsername() throws Exception {
String username = "admin";
MockHttpServletRequest postProcessedRequest = digest(username).postProcessRequest(this.request);
assertThat(extractUser()).isEqualTo(username);
}
@Test
public void digestWithFilterCustomPassword() throws Exception {
String username = "custom";
this.password = "secret";
MockHttpServletRequest postProcessedRequest = digest(username).password(this.password)
.postProcessRequest(this.request);
assertThat(extractUser()).isEqualTo(username);
}
@Test
public void digestWithFilterCustomRealm() throws Exception {
String username = "admin";
this.entryPoint.setRealmName("Custom");
MockHttpServletRequest postProcessedRequest = digest(username).realm(this.entryPoint.getRealmName())
.postProcessRequest(this.request);
assertThat(extractUser()).isEqualTo(username);
}
@Test
public void digestWithFilterFails() throws Exception {
String username = "admin";
MockHttpServletRequest postProcessedRequest = digest(username).realm("Invalid")
.postProcessRequest(this.request);
assertThat(extractUser()).isNull();
}
private String extractUser() throws IOException, ServletException {
this.filter.doFilter(this.request, new MockHttpServletResponse(), new MockFilterChain() {
@Override
public void doFilter(ServletRequest request, ServletResponse response) {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
SecurityMockMvcRequestPostProcessorsDigestTests.this.username = (authentication != null)
? authentication.getName() : null;
}
});
return this.username;
}
}
| 4,488 | 35.201613 | 112 | java |
null | spring-security-main/test/src/test/java/org/springframework/security/test/web/servlet/request/SecurityMockMvcRequestPostProcessorsCsrfDebugFilterTests.java | /*
* Copyright 2002-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.test.web.servlet.request;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityCustomizer;
import org.springframework.security.test.web.support.WebTestUtils;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.csrf.CookieCsrfTokenRepository;
import org.springframework.security.web.csrf.CsrfTokenRepository;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.web.context.WebApplicationContext;
import static org.assertj.core.api.Assertions.assertThat;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
@ExtendWith(SpringExtension.class)
@ContextConfiguration
@WebAppConfiguration
public class SecurityMockMvcRequestPostProcessorsCsrfDebugFilterTests {
@Autowired
private WebApplicationContext wac;
// SEC-3836
@Test
public void findCookieCsrfTokenRepository() {
MockHttpServletRequest request = post("/").buildRequest(this.wac.getServletContext());
CsrfTokenRepository csrfTokenRepository = WebTestUtils.getCsrfTokenRepository(request);
assertThat(csrfTokenRepository).isNotNull();
assertThat(csrfTokenRepository).isEqualTo(Config.cookieCsrfTokenRepository);
}
@Configuration
@EnableWebSecurity
static class Config {
static CsrfTokenRepository cookieCsrfTokenRepository = new CookieCsrfTokenRepository();
@Bean
SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http.csrf().csrfTokenRepository(cookieCsrfTokenRepository);
return http.build();
}
@Bean
WebSecurityCustomizer webSecurityCustomizer() {
// Enable the DebugFilter
return (web) -> web.debug(true);
}
}
}
| 2,992 | 36.886076 | 94 | java |
null | spring-security-main/test/src/test/java/org/springframework/security/test/web/servlet/request/SecurityMockMvcRequestPostProcessorsTestSecurityContextTests.java | /*
* Copyright 2002-2014 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.test.web.servlet.request;
import jakarta.servlet.http.HttpServletResponse;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.MockedStatic;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.test.context.TestSecurityContextHolder;
import org.springframework.security.test.web.support.WebTestUtils;
import org.springframework.security.web.context.SecurityContextRepository;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.testSecurityContext;
@ExtendWith(MockitoExtension.class)
public class SecurityMockMvcRequestPostProcessorsTestSecurityContextTests {
@Mock
private SecurityContext context;
@Mock
private SecurityContextRepository repository;
@Mock
private MockedStatic<WebTestUtils> webTestUtils;
private MockHttpServletRequest request;
@BeforeEach
public void setup() {
this.request = new MockHttpServletRequest();
this.webTestUtils.when(() -> WebTestUtils.getSecurityContextRepository(this.request))
.thenReturn(this.repository);
}
@AfterEach
public void cleanup() {
TestSecurityContextHolder.clearContext();
}
@Test
public void testSecurityContextSaves() {
TestSecurityContextHolder.setContext(this.context);
testSecurityContext().postProcessRequest(this.request);
verify(this.repository).saveContext(eq(this.context), eq(this.request), any(HttpServletResponse.class));
}
// Ensure it does not fail if TestSecurityContextHolder is not initialized
@Test
public void testSecurityContextNoContext() {
testSecurityContext().postProcessRequest(this.request);
verify(this.repository, never()).saveContext(any(SecurityContext.class), eq(this.request),
any(HttpServletResponse.class));
}
}
| 2,862 | 33.914634 | 125 | java |
null | spring-security-main/test/src/test/java/org/springframework/security/test/web/servlet/request/SecurityMockMvcRequestPostProcessorsUserDetailsTests.java | /*
* Copyright 2002-2014 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.test.web.servlet.request;
import jakarta.servlet.http.HttpServletResponse;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Captor;
import org.mockito.Mock;
import org.mockito.MockedStatic;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.test.context.TestSecurityContextHolder;
import org.springframework.security.test.web.support.WebTestUtils;
import org.springframework.security.web.context.SecurityContextRepository;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.verify;
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.user;
@ExtendWith(MockitoExtension.class)
public class SecurityMockMvcRequestPostProcessorsUserDetailsTests {
@Captor
private ArgumentCaptor<SecurityContext> contextCaptor;
@Mock
private SecurityContextRepository repository;
private MockHttpServletRequest request;
@Mock
private UserDetails userDetails;
@Mock
private MockedStatic<WebTestUtils> webTestUtils;
@BeforeEach
public void setup() {
this.request = new MockHttpServletRequest();
this.webTestUtils.when(() -> WebTestUtils.getSecurityContextRepository(this.request))
.thenReturn(this.repository);
}
@AfterEach
public void cleanup() {
TestSecurityContextHolder.clearContext();
}
@Test
public void userDetails() {
user(this.userDetails).postProcessRequest(this.request);
verify(this.repository).saveContext(this.contextCaptor.capture(), eq(this.request),
any(HttpServletResponse.class));
SecurityContext context = this.contextCaptor.getValue();
assertThat(context.getAuthentication()).isInstanceOf(UsernamePasswordAuthenticationToken.class);
assertThat(context.getAuthentication().getPrincipal()).isSameAs(this.userDetails);
}
}
| 3,010 | 34.845238 | 110 | java |
null | spring-security-main/test/src/test/java/org/springframework/security/test/web/servlet/request/SecurityMockMvcRequestPostProcessorsAuthenticationTests.java | /*
* Copyright 2002-2014 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.test.web.servlet.request;
import jakarta.servlet.http.HttpServletResponse;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Captor;
import org.mockito.Mock;
import org.mockito.MockedStatic;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.test.context.TestSecurityContextHolder;
import org.springframework.security.test.web.support.WebTestUtils;
import org.springframework.security.web.context.SecurityContextRepository;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.verify;
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.authentication;
@ExtendWith(MockitoExtension.class)
public class SecurityMockMvcRequestPostProcessorsAuthenticationTests {
@Captor
private ArgumentCaptor<SecurityContext> contextCaptor;
@Mock
private SecurityContextRepository repository;
private MockHttpServletRequest request;
@Mock
private Authentication authentication;
@Mock
private MockedStatic<WebTestUtils> webTestUtils;
@BeforeEach
public void setup() {
this.request = new MockHttpServletRequest();
this.webTestUtils.when(() -> WebTestUtils.getSecurityContextRepository(this.request))
.thenReturn(this.repository);
}
@AfterEach
public void cleanup() {
TestSecurityContextHolder.clearContext();
}
@Test
public void userDetails() {
authentication(this.authentication).postProcessRequest(this.request);
verify(this.repository).saveContext(this.contextCaptor.capture(), eq(this.request),
any(HttpServletResponse.class));
SecurityContext context = this.contextCaptor.getValue();
assertThat(context.getAuthentication()).isSameAs(this.authentication);
}
}
| 2,834 | 33.573171 | 120 | java |
null | spring-security-main/test/src/test/java/org/springframework/security/test/web/servlet/request/SecurityMockMvcRequestPostProcessorsSecurityContextTests.java | /*
* Copyright 2002-2014 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.test.web.servlet.request;
import jakarta.servlet.http.HttpServletResponse;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Captor;
import org.mockito.Mock;
import org.mockito.MockedStatic;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.test.context.TestSecurityContextHolder;
import org.springframework.security.test.web.support.WebTestUtils;
import org.springframework.security.web.context.SecurityContextRepository;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.verify;
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.securityContext;
@ExtendWith(MockitoExtension.class)
public class SecurityMockMvcRequestPostProcessorsSecurityContextTests {
@Captor
private ArgumentCaptor<SecurityContext> contextCaptor;
@Mock
private SecurityContextRepository repository;
private MockHttpServletRequest request;
@Mock
private SecurityContext expectedContext;
@Mock
private MockedStatic<WebTestUtils> webTestUtils;
@BeforeEach
public void setup() {
this.request = new MockHttpServletRequest();
this.webTestUtils.when(() -> WebTestUtils.getSecurityContextRepository(this.request))
.thenReturn(this.repository);
}
@AfterEach
public void cleanup() {
TestSecurityContextHolder.clearContext();
}
@Test
public void userDetails() {
securityContext(this.expectedContext).postProcessRequest(this.request);
verify(this.repository).saveContext(this.contextCaptor.capture(), eq(this.request),
any(HttpServletResponse.class));
SecurityContext context = this.contextCaptor.getValue();
assertThat(context).isSameAs(this.expectedContext);
}
}
| 2,764 | 33.135802 | 121 | java |
null | spring-security-main/test/src/test/java/org/springframework/security/test/web/servlet/request/SecurityMockMvcRequestPostProcessorsCertificateTests.java | /*
* Copyright 2002-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.test.web.servlet.request;
import java.security.cert.X509Certificate;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.mock.web.MockHttpServletRequest;
import static org.assertj.core.api.Assertions.assertThat;
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.x509;
@ExtendWith(MockitoExtension.class)
public class SecurityMockMvcRequestPostProcessorsCertificateTests {
@Mock
private X509Certificate certificate;
private MockHttpServletRequest request;
@BeforeEach
public void setup() {
this.request = new MockHttpServletRequest();
}
@Test
public void x509SingleCertificate() {
MockHttpServletRequest postProcessedRequest = x509(this.certificate).postProcessRequest(this.request);
X509Certificate[] certificates = (X509Certificate[]) postProcessedRequest
.getAttribute("jakarta.servlet.request.X509Certificate");
assertThat(certificates).containsOnly(this.certificate);
}
@Test
public void x509ResourceName() throws Exception {
MockHttpServletRequest postProcessedRequest = x509("rod.cer").postProcessRequest(this.request);
X509Certificate[] certificates = (X509Certificate[]) postProcessedRequest
.getAttribute("jakarta.servlet.request.X509Certificate");
assertThat(certificates).hasSize(1);
assertThat(certificates[0].getSubjectDN().getName())
.isEqualTo("CN=rod, OU=Spring Security, O=Spring Framework");
}
}
| 2,258 | 34.296875 | 110 | java |
null | spring-security-main/test/src/test/java/org/springframework/security/test/web/servlet/request/SecurityMockMvcRequestPostProcessorsOpaqueTokenTests.java | /*
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.test.web.servlet.request;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.oauth2.core.OAuth2AuthenticatedPrincipal;
import org.springframework.security.oauth2.core.TestOAuth2AuthenticatedPrincipals;
import org.springframework.security.oauth2.server.resource.introspection.OpaqueTokenIntrospector;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.opaqueToken;
import static org.springframework.security.test.web.servlet.setup.SecurityMockMvcConfigurers.springSecurity;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
/**
* Tests for {@link SecurityMockMvcRequestPostProcessors#opaqueToken()}
*
* @author Josh Cummings
* @since 5.3
*/
@ExtendWith(SpringExtension.class)
@ContextConfiguration
@WebAppConfiguration
public class SecurityMockMvcRequestPostProcessorsOpaqueTokenTests {
@Autowired
WebApplicationContext context;
MockMvc mvc;
@BeforeEach
public void setup() {
// @formatter:off
this.mvc = MockMvcBuilders
.webAppContextSetup(this.context)
.apply(springSecurity())
.build();
// @formatter:on
}
@Test
public void opaqueTokenWhenUsingDefaultsThenProducesDefaultAuthentication() throws Exception {
this.mvc.perform(get("/name").with(opaqueToken())).andExpect(content().string("user"));
this.mvc.perform(get("/admin/scopes").with(opaqueToken())).andExpect(status().isForbidden());
}
@Test
public void opaqueTokenWhenAttributeSpecifiedThenUserHasAttribute() throws Exception {
this.mvc.perform(
get("/opaque-token/iss").with(opaqueToken().attributes((a) -> a.put("iss", "https://idp.example.org"))))
.andExpect(content().string("https://idp.example.org"));
}
@Test
public void opaqueTokenWhenPrincipalSpecifiedThenAuthenticationHasPrincipal() throws Exception {
Collection authorities = Collections.singleton(new SimpleGrantedAuthority("SCOPE_read"));
OAuth2AuthenticatedPrincipal principal = mock(OAuth2AuthenticatedPrincipal.class);
given(principal.getName()).willReturn("ben");
given(principal.getAuthorities()).willReturn(authorities);
this.mvc.perform(get("/name").with(opaqueToken().principal(principal))).andExpect(content().string("ben"));
}
// gh-7800
@Test
public void opaqueTokenWhenPrincipalSpecifiedThenLastCalledTakesPrecedence() throws Exception {
OAuth2AuthenticatedPrincipal principal = TestOAuth2AuthenticatedPrincipals
.active((a) -> a.put("scope", "user"));
this.mvc.perform(get("/opaque-token/sub")
.with(opaqueToken().attributes((a) -> a.put("sub", "foo")).principal(principal)))
.andExpect(status().isOk()).andExpect(content().string((String) principal.getAttribute("sub")));
this.mvc.perform(get("/opaque-token/sub")
.with(opaqueToken().principal(principal).attributes((a) -> a.put("sub", "bar"))))
.andExpect(content().string("bar"));
}
@Configuration
@EnableWebSecurity
@EnableWebMvc
static class OAuth2LoginConfig {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests()
.requestMatchers("/admin/**").hasAuthority("SCOPE_admin")
.anyRequest().hasAuthority("SCOPE_read")
.and()
.oauth2ResourceServer()
.opaqueToken()
.introspector(mock(OpaqueTokenIntrospector.class));
return http.build();
// @formatter:on
}
@RestController
static class PrincipalController {
@GetMapping("/name")
String name(@AuthenticationPrincipal OAuth2AuthenticatedPrincipal principal) {
return principal.getName();
}
@GetMapping("/opaque-token/{attribute}")
String tokenAttribute(@AuthenticationPrincipal OAuth2AuthenticatedPrincipal principal,
@PathVariable("attribute") String attribute) {
return principal.getAttribute(attribute);
}
@GetMapping("/admin/scopes")
List<String> scopes(
@AuthenticationPrincipal(expression = "authorities") Collection<GrantedAuthority> authorities) {
return authorities.stream().map(GrantedAuthority::getAuthority).collect(Collectors.toList());
}
}
}
}
| 6,476 | 38.254545 | 117 | java |
null | spring-security-main/test/src/test/java/org/springframework/security/test/web/servlet/request/SecurityMockMvcRequestPostProcessorsOAuth2ClientTests.java | /*
* Copyright 2002-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.test.web.servlet.request;
import jakarta.servlet.http.HttpServletRequest;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.client.OAuth2AuthorizedClient;
import org.springframework.security.oauth2.client.OAuth2AuthorizedClientManager;
import org.springframework.security.oauth2.client.annotation.RegisteredOAuth2AuthorizedClient;
import org.springframework.security.oauth2.client.registration.ClientRegistration;
import org.springframework.security.oauth2.client.registration.ClientRegistrationRepository;
import org.springframework.security.oauth2.client.registration.TestClientRegistrations;
import org.springframework.security.oauth2.client.web.DefaultOAuth2AuthorizedClientManager;
import org.springframework.security.oauth2.client.web.OAuth2AuthorizedClientRepository;
import org.springframework.security.oauth2.core.OAuth2AccessToken;
import org.springframework.security.oauth2.core.TestOAuth2AccessTokens;
import org.springframework.security.test.context.TestSecurityContextHolder;
import org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.OAuth2ClientRequestPostProcessor.TestOAuth2AuthorizedClientRepository;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.util.ReflectionTestUtils;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.oauth2Client;
import static org.springframework.security.test.web.servlet.setup.SecurityMockMvcConfigurers.springSecurity;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
/**
* Tests for {@link SecurityMockMvcRequestPostProcessors#oidcLogin()}
*
* @author Josh Cummings
* @since 5.3
*/
@ExtendWith(SpringExtension.class)
@ContextConfiguration
@WebAppConfiguration
public class SecurityMockMvcRequestPostProcessorsOAuth2ClientTests {
@Autowired
WebApplicationContext context;
MockMvc mvc;
@BeforeEach
public void setup() {
// @formatter:off
this.mvc = MockMvcBuilders
.webAppContextSetup(this.context)
.apply(springSecurity())
.build();
// @formatter:on
}
@AfterEach
public void cleanup() {
TestSecurityContextHolder.clearContext();
}
@Test
public void oauth2ClientWhenUsingDefaultsThenException() throws Exception {
assertThatIllegalArgumentException()
.isThrownBy(() -> oauth2Client().postProcessRequest(new MockHttpServletRequest()))
.withMessageContaining("ClientRegistration");
}
@Test
public void oauth2ClientWhenUsingDefaultsThenProducesDefaultAuthorizedClient() throws Exception {
this.mvc.perform(get("/access-token").with(oauth2Client("registration-id")))
.andExpect(content().string("access-token"));
this.mvc.perform(get("/client-id").with(oauth2Client("registration-id")))
.andExpect(content().string("test-client"));
}
@Test
public void oauth2ClientWhenClientRegistrationThenUses() throws Exception {
ClientRegistration clientRegistration = TestClientRegistrations.clientRegistration()
.registrationId("registration-id").clientId("client-id").build();
this.mvc.perform(get("/client-id").with(oauth2Client().clientRegistration(clientRegistration)))
.andExpect(content().string("client-id"));
}
@Test
public void oauth2ClientWhenClientRegistrationConsumerThenUses() throws Exception {
this.mvc.perform(get("/client-id")
.with(oauth2Client("registration-id").clientRegistration((c) -> c.clientId("client-id"))))
.andExpect(content().string("client-id"));
}
@Test
public void oauth2ClientWhenPrincipalNameThenUses() throws Exception {
this.mvc.perform(get("/principal-name").with(oauth2Client("registration-id").principalName("test-subject")))
.andExpect(content().string("test-subject"));
}
@Test
public void oauth2ClientWhenAccessTokenThenUses() throws Exception {
OAuth2AccessToken accessToken = TestOAuth2AccessTokens.noScopes();
this.mvc.perform(get("/access-token").with(oauth2Client("registration-id").accessToken(accessToken)))
.andExpect(content().string("no-scopes"));
}
@Test
public void oauth2ClientWhenUsedOnceThenDoesNotAffectRemainingTests() throws Exception {
this.mvc.perform(get("/client-id").with(oauth2Client("registration-id")))
.andExpect(content().string("test-client"));
OAuth2AuthorizedClient client = new OAuth2AuthorizedClient(TestClientRegistrations.clientRegistration().build(),
"sub", TestOAuth2AccessTokens.noScopes());
OAuth2AuthorizedClientRepository repository = this.context.getBean(OAuth2AuthorizedClientRepository.class);
given(repository.loadAuthorizedClient(eq("registration-id"), any(Authentication.class),
any(HttpServletRequest.class))).willReturn(client);
this.mvc.perform(get("/client-id")).andExpect(content().string("client-id"));
verify(repository).loadAuthorizedClient(eq("registration-id"), any(Authentication.class),
any(HttpServletRequest.class));
}
// gh-13113
@Test
public void oauth2ClientWhenUsedThenSetsClientToRepository() throws Exception {
HttpServletRequest request = this.mvc.perform(get("/client-id").with(oauth2Client("registration-id")))
.andExpect(content().string("test-client")).andReturn().getRequest();
OAuth2AuthorizedClientManager manager = this.context.getBean(OAuth2AuthorizedClientManager.class);
OAuth2AuthorizedClientRepository repository = (OAuth2AuthorizedClientRepository) ReflectionTestUtils
.getField(manager, "authorizedClientRepository");
assertThat(repository).isInstanceOf(TestOAuth2AuthorizedClientRepository.class);
assertThat((OAuth2AuthorizedClient) repository.loadAuthorizedClient("id", null, request)).isNotNull();
}
@Configuration
@EnableWebSecurity
@EnableWebMvc
static class OAuth2ClientConfig {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests((authz) -> authz
.anyRequest().permitAll()
)
.oauth2Client();
return http.build();
// @formatter:on
}
@Bean
OAuth2AuthorizedClientManager authorizedClientManager(ClientRegistrationRepository clients,
OAuth2AuthorizedClientRepository authorizedClients) {
return new DefaultOAuth2AuthorizedClientManager(clients, authorizedClients);
}
@Bean
ClientRegistrationRepository clientRegistrationRepository() {
return mock(ClientRegistrationRepository.class);
}
@Bean
OAuth2AuthorizedClientRepository authorizedClientRepository() {
return mock(OAuth2AuthorizedClientRepository.class);
}
@RestController
static class PrincipalController {
@GetMapping("/access-token")
String accessToken(
@RegisteredOAuth2AuthorizedClient("registration-id") OAuth2AuthorizedClient authorizedClient) {
return authorizedClient.getAccessToken().getTokenValue();
}
@GetMapping("/principal-name")
String principalName(
@RegisteredOAuth2AuthorizedClient("registration-id") OAuth2AuthorizedClient authorizedClient) {
return authorizedClient.getPrincipalName();
}
@GetMapping("/client-id")
String clientId(
@RegisteredOAuth2AuthorizedClient("registration-id") OAuth2AuthorizedClient authorizedClient) {
return authorizedClient.getClientRegistration().getClientId();
}
}
}
}
| 9,504 | 40.872247 | 168 | java |
null | spring-security-main/test/src/test/java/org/springframework/security/test/web/servlet/request/SecurityMockMvcRequestPostProcessorsUserTests.java | /*
* Copyright 2002-2014 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.test.web.servlet.request;
import java.util.Arrays;
import java.util.List;
import jakarta.servlet.http.HttpServletResponse;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Captor;
import org.mockito.Mock;
import org.mockito.MockedStatic;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.test.context.TestSecurityContextHolder;
import org.springframework.security.test.web.support.WebTestUtils;
import org.springframework.security.web.context.SecurityContextRepository;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.verify;
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.user;
@ExtendWith(MockitoExtension.class)
public class SecurityMockMvcRequestPostProcessorsUserTests {
@Captor
private ArgumentCaptor<SecurityContext> contextCaptor;
@Mock
private SecurityContextRepository repository;
private MockHttpServletRequest request;
@Mock
private GrantedAuthority authority1;
@Mock
private GrantedAuthority authority2;
@Mock
private MockedStatic<WebTestUtils> webTestUtils;
@BeforeEach
public void setup() {
this.request = new MockHttpServletRequest();
this.webTestUtils.when(() -> WebTestUtils.getSecurityContextRepository(this.request))
.thenReturn(this.repository);
}
@AfterEach
public void cleanup() {
TestSecurityContextHolder.clearContext();
}
@Test
public void userWithDefaults() {
String username = "userabc";
user(username).postProcessRequest(this.request);
verify(this.repository).saveContext(this.contextCaptor.capture(), eq(this.request),
any(HttpServletResponse.class));
SecurityContext context = this.contextCaptor.getValue();
assertThat(context.getAuthentication()).isInstanceOf(UsernamePasswordAuthenticationToken.class);
assertThat(context.getAuthentication().getName()).isEqualTo(username);
assertThat(context.getAuthentication().getCredentials()).isEqualTo("password");
assertThat(context.getAuthentication().getAuthorities()).extracting("authority").containsOnly("ROLE_USER");
}
@Test
public void userWithCustom() {
String username = "customuser";
user(username).roles("CUSTOM", "ADMIN").password("newpass").postProcessRequest(this.request);
verify(this.repository).saveContext(this.contextCaptor.capture(), eq(this.request),
any(HttpServletResponse.class));
SecurityContext context = this.contextCaptor.getValue();
assertThat(context.getAuthentication()).isInstanceOf(UsernamePasswordAuthenticationToken.class);
assertThat(context.getAuthentication().getName()).isEqualTo(username);
assertThat(context.getAuthentication().getCredentials()).isEqualTo("newpass");
assertThat(context.getAuthentication().getAuthorities()).extracting("authority").containsOnly("ROLE_CUSTOM",
"ROLE_ADMIN");
}
@Test
public void userCustomAuthoritiesVarargs() {
String username = "customuser";
user(username).authorities(this.authority1, this.authority2).postProcessRequest(this.request);
verify(this.repository).saveContext(this.contextCaptor.capture(), eq(this.request),
any(HttpServletResponse.class));
SecurityContext context = this.contextCaptor.getValue();
assertThat((List<GrantedAuthority>) context.getAuthentication().getAuthorities()).containsOnly(this.authority1,
this.authority2);
}
@Test
public void userRolesWithRolePrefixErrors() {
assertThatIllegalArgumentException()
.isThrownBy(() -> user("user").roles("ROLE_INVALID").postProcessRequest(this.request));
}
@Test
public void userCustomAuthoritiesList() {
String username = "customuser";
user(username).authorities(Arrays.asList(this.authority1, this.authority2)).postProcessRequest(this.request);
verify(this.repository).saveContext(this.contextCaptor.capture(), eq(this.request),
any(HttpServletResponse.class));
SecurityContext context = this.contextCaptor.getValue();
assertThat((List<GrantedAuthority>) context.getAuthentication().getAuthorities()).containsOnly(this.authority1,
this.authority2);
}
}
| 5,336 | 38.242647 | 113 | java |
null | spring-security-main/test/src/test/java/org/springframework/security/test/web/servlet/request/SecurityMockMvcRequestPostProcessorsOidcLoginTests.java | /*
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.test.web.servlet.request;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.oauth2.client.OAuth2AuthorizedClient;
import org.springframework.security.oauth2.client.annotation.RegisteredOAuth2AuthorizedClient;
import org.springframework.security.oauth2.client.registration.ClientRegistrationRepository;
import org.springframework.security.oauth2.client.web.OAuth2AuthorizedClientRepository;
import org.springframework.security.oauth2.core.oidc.OidcIdToken;
import org.springframework.security.oauth2.core.oidc.TestOidcIdTokens;
import org.springframework.security.oauth2.core.oidc.user.DefaultOidcUser;
import org.springframework.security.oauth2.core.oidc.user.OidcUser;
import org.springframework.security.test.context.TestSecurityContextHolder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import static org.mockito.Mockito.mock;
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.oidcLogin;
import static org.springframework.security.test.web.servlet.setup.SecurityMockMvcConfigurers.springSecurity;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
/**
* Tests for {@link SecurityMockMvcRequestPostProcessors#oidcLogin()}
*
* @author Josh Cummings
* @since 5.3
*/
@ExtendWith(SpringExtension.class)
@ContextConfiguration
@WebAppConfiguration
public class SecurityMockMvcRequestPostProcessorsOidcLoginTests {
@Autowired
WebApplicationContext context;
MockMvc mvc;
@BeforeEach
public void setup() {
// @formatter:off
this.mvc = MockMvcBuilders
.webAppContextSetup(this.context)
.apply(springSecurity())
.build();
// @formatter:on
}
@AfterEach
public void cleanup() {
TestSecurityContextHolder.clearContext();
}
@Test
public void oidcLoginWhenUsingDefaultsThenProducesDefaultAuthentication() throws Exception {
this.mvc.perform(get("/name").with(oidcLogin())).andExpect(content().string("user"));
this.mvc.perform(get("/admin/id-token/name").with(oidcLogin())).andExpect(status().isForbidden());
}
@Test
public void oidcLoginWhenUsingDefaultsThenProducesDefaultAuthorizedClient() throws Exception {
this.mvc.perform(get("/access-token").with(oidcLogin())).andExpect(content().string("access-token"));
}
@Test
public void oidcLoginWhenAuthoritiesSpecifiedThenGrantsAccess() throws Exception {
this.mvc.perform(get("/admin/scopes").with(oidcLogin().authorities(new SimpleGrantedAuthority("SCOPE_admin"))))
.andExpect(content().string("[\"SCOPE_admin\"]"));
}
@Test
public void oidcLoginWhenIdTokenSpecifiedThenUserHasClaims() throws Exception {
this.mvc.perform(get("/id-token/iss").with(oidcLogin().idToken((i) -> i.issuer("https://idp.example.org"))))
.andExpect(content().string("https://idp.example.org"));
}
@Test
public void oidcLoginWhenUserInfoSpecifiedThenUserHasClaims() throws Exception {
this.mvc.perform(get("/user-info/email").with(oidcLogin().userInfoToken((u) -> u.email("email@email"))))
.andExpect(content().string("email@email"));
}
@Test
public void oidcLoginWhenNameSpecifiedThenUserHasName() throws Exception {
OidcUser oidcUser = new DefaultOidcUser(AuthorityUtils.commaSeparatedStringToAuthorityList("SCOPE_read"),
OidcIdToken.withTokenValue("id-token").claim("custom-attribute", "test-subject").build(),
"custom-attribute");
this.mvc.perform(get("/id-token/custom-attribute").with(oidcLogin().oidcUser(oidcUser)))
.andExpect(content().string("test-subject"));
this.mvc.perform(get("/name").with(oidcLogin().oidcUser(oidcUser))).andExpect(content().string("test-subject"));
this.mvc.perform(get("/client-name").with(oidcLogin().oidcUser(oidcUser)))
.andExpect(content().string("test-subject"));
}
// gh-7794
@Test
public void oidcLoginWhenOidcUserSpecifiedThenLastCalledTakesPrecedence() throws Exception {
OidcUser oidcUser = new DefaultOidcUser(AuthorityUtils.createAuthorityList("SCOPE_read"),
TestOidcIdTokens.idToken().build());
this.mvc.perform(get("/id-token/sub").with(oidcLogin().idToken((i) -> i.subject("foo")).oidcUser(oidcUser)))
.andExpect(status().isOk()).andExpect(content().string("subject"));
this.mvc.perform(get("/id-token/sub").with(oidcLogin().oidcUser(oidcUser).idToken((i) -> i.subject("bar"))))
.andExpect(content().string("bar"));
}
@Configuration
@EnableWebSecurity
@EnableWebMvc
static class OAuth2LoginConfig {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests()
.requestMatchers("/admin/**").hasAuthority("SCOPE_admin")
.anyRequest().hasAuthority("SCOPE_read")
.and()
.oauth2Login();
return http.build();
// @formatter:on
}
@Bean
ClientRegistrationRepository clientRegistrationRepository() {
return mock(ClientRegistrationRepository.class);
}
@Bean
OAuth2AuthorizedClientRepository oAuth2AuthorizedClientRepository() {
return mock(OAuth2AuthorizedClientRepository.class);
}
@RestController
static class PrincipalController {
@GetMapping("/name")
String name(@AuthenticationPrincipal OidcUser oidcUser) {
return oidcUser.getName();
}
@GetMapping("/client-name")
String clientName(@RegisteredOAuth2AuthorizedClient OAuth2AuthorizedClient authorizedClient) {
return authorizedClient.getPrincipalName();
}
@GetMapping("/access-token")
String authorizedClient(@RegisteredOAuth2AuthorizedClient OAuth2AuthorizedClient authorizedClient) {
return authorizedClient.getAccessToken().getTokenValue();
}
@GetMapping("/id-token/{claim}")
String idTokenClaim(@AuthenticationPrincipal OidcUser oidcUser, @PathVariable("claim") String claim) {
return oidcUser.getIdToken().getClaim(claim);
}
@GetMapping("/user-info/{claim}")
String userInfoClaim(@AuthenticationPrincipal OidcUser oidcUser, @PathVariable("claim") String claim) {
return oidcUser.getUserInfo().getClaim(claim);
}
@GetMapping("/admin/scopes")
List<String> scopes(
@AuthenticationPrincipal(expression = "authorities") Collection<GrantedAuthority> authorities) {
return authorities.stream().map(GrantedAuthority::getAuthority).collect(Collectors.toList());
}
}
}
}
| 8,579 | 38.906977 | 115 | java |
null | spring-security-main/test/src/test/java/org/springframework/security/test/web/servlet/setup/SecurityMockMvcConfigurerTests.java | /*
* Copyright 2002-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.test.web.servlet.setup;
import jakarta.servlet.Filter;
import jakarta.servlet.ServletContext;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.security.config.BeanIds;
import org.springframework.test.web.servlet.setup.ConfigurableMockMvcBuilder;
import org.springframework.web.context.WebApplicationContext;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalStateException;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.verify;
@ExtendWith(MockitoExtension.class)
public class SecurityMockMvcConfigurerTests {
@Mock
private Filter filter;
@Mock
private Filter beanFilter;
@Mock
private ConfigurableMockMvcBuilder<?> builder;
@Mock
private WebApplicationContext context;
@Mock
private ServletContext servletContext;
@Test
public void beforeMockMvcCreatedOverrideBean() throws Exception {
given(this.context.getServletContext()).willReturn(this.servletContext);
SecurityMockMvcConfigurer configurer = new SecurityMockMvcConfigurer(this.filter);
configurer.afterConfigurerAdded(this.builder);
configurer.beforeMockMvcCreated(this.builder, this.context);
assertFilterAdded(this.filter);
verify(this.servletContext).setAttribute(BeanIds.SPRING_SECURITY_FILTER_CHAIN, this.filter);
}
@Test
public void beforeMockMvcCreatedBean() throws Exception {
given(this.context.getServletContext()).willReturn(this.servletContext);
returnFilterBean();
SecurityMockMvcConfigurer configurer = new SecurityMockMvcConfigurer();
configurer.afterConfigurerAdded(this.builder);
configurer.beforeMockMvcCreated(this.builder, this.context);
assertFilterAdded(this.beanFilter);
}
@Test
public void beforeMockMvcCreatedNoBean() throws Exception {
given(this.context.getServletContext()).willReturn(this.servletContext);
SecurityMockMvcConfigurer configurer = new SecurityMockMvcConfigurer(this.filter);
configurer.afterConfigurerAdded(this.builder);
configurer.beforeMockMvcCreated(this.builder, this.context);
assertFilterAdded(this.filter);
}
@Test
public void beforeMockMvcCreatedNoFilter() {
SecurityMockMvcConfigurer configurer = new SecurityMockMvcConfigurer();
configurer.afterConfigurerAdded(this.builder);
assertThatIllegalStateException().isThrownBy(() -> configurer.beforeMockMvcCreated(this.builder, this.context));
}
private void assertFilterAdded(Filter filter) {
ArgumentCaptor<SecurityMockMvcConfigurer.DelegateFilter> filterArg = ArgumentCaptor
.forClass(SecurityMockMvcConfigurer.DelegateFilter.class);
verify(this.builder).addFilters(filterArg.capture());
assertThat(filterArg.getValue().getDelegate()).isEqualTo(filter);
}
private void returnFilterBean() {
given(this.context.containsBean(anyString())).willReturn(true);
given(this.context.getBean(anyString(), eq(Filter.class))).willReturn(this.beanFilter);
}
}
| 3,840 | 35.580952 | 114 | java |
null | spring-security-main/test/src/test/java/org/springframework/security/test/web/servlet/setup/SecurityMockMvcConfigurersTests.java | /*
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.test.web.servlet.setup;
import jakarta.servlet.Filter;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.users.AuthenticationTestConfiguration;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import static org.mockito.Mockito.mock;
import static org.springframework.security.test.web.servlet.setup.SecurityMockMvcConfigurers.springSecurity;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
/**
* @author Rob Winch
*/
@ExtendWith(SpringExtension.class)
@WebAppConfiguration
public class SecurityMockMvcConfigurersTests {
@Autowired
WebApplicationContext wac;
Filter noOpFilter = mock(Filter.class);
/**
* Since noOpFilter is first does not continue the chain, security will not be invoked
* and the status should be OK
* @throws Exception
*/
@Test
public void applySpringSecurityWhenAddFilterFirstThenFilterFirst() throws Exception {
MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).addFilters(this.noOpFilter)
.apply(springSecurity()).build();
mockMvc.perform(get("/")).andExpect(status().isOk());
}
/**
* Since noOpFilter is second security will be invoked and the status will be not OK.
* We know this because if noOpFilter were first security would not be invoked sincet
* noOpFilter does not continue the FilterChain
* @throws Exception
*/
@Test
public void applySpringSecurityWhenAddFilterSecondThenSecurityFirst() throws Exception {
MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).apply(springSecurity())
.addFilters(this.noOpFilter).build();
mockMvc.perform(get("/")).andExpect(status().is4xxClientError());
}
@Configuration
@EnableWebMvc
@EnableWebSecurity
@Import(AuthenticationTestConfiguration.class)
static class Config {
}
}
| 3,206 | 36.290698 | 108 | java |
null | spring-security-main/test/src/test/java/org/springframework/security/test/web/servlet/showcase/login/AuthenticationTests.java | /*
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.test.web.servlet.showcase.login;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.DefaultSecurityFilterChain;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import static org.springframework.security.config.Customizer.withDefaults;
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestBuilders.formLogin;
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.httpBasic;
import static org.springframework.security.test.web.servlet.response.SecurityMockMvcResultMatchers.authenticated;
import static org.springframework.security.test.web.servlet.response.SecurityMockMvcResultMatchers.unauthenticated;
import static org.springframework.security.test.web.servlet.setup.SecurityMockMvcConfigurers.springSecurity;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.redirectedUrl;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@ExtendWith(SpringExtension.class)
@ContextConfiguration(classes = AuthenticationTests.Config.class)
@WebAppConfiguration
public class AuthenticationTests {
@Autowired
private WebApplicationContext context;
private MockMvc mvc;
@BeforeEach
public void setup() {
this.mvc = MockMvcBuilders.webAppContextSetup(this.context).apply(springSecurity())
.defaultRequest(get("/").accept(MediaType.TEXT_HTML)).build();
}
@Test
public void requiresAuthentication() throws Exception {
this.mvc.perform(get("/")).andExpect(status().isFound());
}
@Test
public void httpBasicAuthenticationSuccess() throws Exception {
this.mvc.perform(get("/secured/butnotfound").with(httpBasic("user", "password")))
.andExpect(status().isNotFound()).andExpect(authenticated().withUsername("user"));
}
@Test
public void authenticationSuccess() throws Exception {
this.mvc.perform(formLogin()).andExpect(status().isFound()).andExpect(redirectedUrl("/"))
.andExpect(authenticated().withUsername("user"));
}
@Test
public void authenticationFailed() throws Exception {
this.mvc.perform(formLogin().user("user").password("invalid")).andExpect(status().isFound())
.andExpect(redirectedUrl("/login?error")).andExpect(unauthenticated());
}
@Configuration
@EnableWebSecurity
@EnableWebMvc
static class Config {
@Bean
DefaultSecurityFilterChain springSecurity(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeHttpRequests((requests) -> requests
.anyRequest().authenticated()
)
.sessionManagement((sessions) -> sessions
.requireExplicitAuthenticationStrategy(false)
)
.httpBasic(withDefaults())
.formLogin(withDefaults());
// @formatter:on
return http.build();
}
@Bean
UserDetailsService userDetailsService() {
// @formatter:off
UserDetails user = User.withDefaultPasswordEncoder().username("user").password("password").roles("USER").build();
return new InMemoryUserDetailsManager(user);
// @formatter:on
}
}
}
| 4,940 | 39.170732 | 116 | java |
null | spring-security-main/test/src/test/java/org/springframework/security/test/web/servlet/showcase/login/CustomConfigAuthenticationTests.java | /*
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.test.web.servlet.showcase.login;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.context.HttpSessionSecurityContextRepository;
import org.springframework.security.web.context.SecurityContextRepository;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestBuilders.formLogin;
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.user;
import static org.springframework.security.test.web.servlet.response.SecurityMockMvcResultMatchers.authenticated;
import static org.springframework.security.test.web.servlet.response.SecurityMockMvcResultMatchers.unauthenticated;
import static org.springframework.security.test.web.servlet.setup.SecurityMockMvcConfigurers.springSecurity;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.redirectedUrl;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@ExtendWith(SpringExtension.class)
@ContextConfiguration(classes = CustomConfigAuthenticationTests.Config.class)
@WebAppConfiguration
public class CustomConfigAuthenticationTests {
@Autowired
private WebApplicationContext context;
@Autowired
private SecurityContextRepository securityContextRepository;
private MockMvc mvc;
@BeforeEach
public void setup() {
this.mvc = MockMvcBuilders.webAppContextSetup(this.context).apply(springSecurity()).build();
}
@Test
public void authenticationSuccess() throws Exception {
this.mvc.perform(formLogin("/authenticate").user("user", "user").password("pass", "password"))
.andExpect(status().isFound()).andExpect(redirectedUrl("/"))
.andExpect(authenticated().withUsername("user"));
}
@Test
public void withUserSuccess() throws Exception {
this.mvc.perform(get("/").with(user("user"))).andExpect(status().isNotFound())
.andExpect(authenticated().withUsername("user"));
}
@Test
public void authenticationFailed() throws Exception {
this.mvc.perform(formLogin("/authenticate").user("user", "notfound").password("pass", "invalid"))
.andExpect(status().isFound()).andExpect(redirectedUrl("/authenticate?error"))
.andExpect(unauthenticated());
}
@Configuration
@EnableWebSecurity
@EnableWebMvc
static class Config {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests()
.anyRequest().authenticated()
.and()
.securityContext()
.securityContextRepository(securityContextRepository())
.and()
.formLogin()
.usernameParameter("user")
.passwordParameter("pass")
.loginPage("/authenticate");
return http.build();
// @formatter:on
}
// @formatter:off
@Bean
UserDetailsService userDetailsService() {
UserDetails user = User.withDefaultPasswordEncoder().username("user").password("password").roles("USER").build();
return new InMemoryUserDetailsManager(user);
}
// @formatter:on
@Bean
SecurityContextRepository securityContextRepository() {
HttpSessionSecurityContextRepository repo = new HttpSessionSecurityContextRepository();
repo.setSpringSecurityContextKey("CUSTOM");
return repo;
}
}
}
| 5,188 | 38.915385 | 116 | java |
null | spring-security-main/test/src/test/java/org/springframework/security/test/web/servlet/showcase/login/CustomLoginRequestBuilderAuthenticationTests.java | /*
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.test.web.servlet.showcase.login;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestBuilders.FormLoginRequestBuilder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestBuilders.formLogin;
import static org.springframework.security.test.web.servlet.response.SecurityMockMvcResultMatchers.authenticated;
import static org.springframework.security.test.web.servlet.response.SecurityMockMvcResultMatchers.unauthenticated;
import static org.springframework.security.test.web.servlet.setup.SecurityMockMvcConfigurers.springSecurity;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.redirectedUrl;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@ExtendWith(SpringExtension.class)
@ContextConfiguration(classes = CustomLoginRequestBuilderAuthenticationTests.Config.class)
@WebAppConfiguration
public class CustomLoginRequestBuilderAuthenticationTests {
@Autowired
private WebApplicationContext context;
private MockMvc mvc;
@BeforeEach
public void setup() {
this.mvc = MockMvcBuilders.webAppContextSetup(this.context).apply(springSecurity()).build();
}
@Test
public void authenticationSuccess() throws Exception {
this.mvc.perform(login()).andExpect(status().isFound()).andExpect(redirectedUrl("/"))
.andExpect(authenticated().withUsername("user"));
}
@Test
public void authenticationFailed() throws Exception {
this.mvc.perform(login().user("notfound").password("invalid")).andExpect(status().isFound())
.andExpect(redirectedUrl("/authenticate?error")).andExpect(unauthenticated());
}
static FormLoginRequestBuilder login() {
return formLogin("/authenticate").userParameter("user").passwordParam("pass");
}
@Configuration
@EnableWebSecurity
@EnableWebMvc
static class Config {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests()
.anyRequest().authenticated()
.and()
.formLogin()
.usernameParameter("user")
.passwordParameter("pass")
.loginPage("/authenticate");
return http.build();
// @formatter:on
}
// @formatter:off
@Bean
UserDetailsService userDetailsService() {
UserDetails user = User.withDefaultPasswordEncoder().username("user").password("password").roles("USER").build();
return new InMemoryUserDetailsManager(user);
}
// @formatter:on
}
}
| 4,394 | 38.594595 | 116 | java |
null | spring-security-main/test/src/test/java/org/springframework/security/test/web/servlet/showcase/csrf/CustomCsrfShowcaseTests.java | /*
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.test.web.servlet.showcase.csrf;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.csrf.CsrfTokenRepository;
import org.springframework.security.web.csrf.HttpSessionCsrfTokenRepository;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf;
import static org.springframework.security.test.web.servlet.setup.SecurityMockMvcConfigurers.springSecurity;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@ExtendWith(SpringExtension.class)
@ContextConfiguration(classes = CustomCsrfShowcaseTests.Config.class)
@WebAppConfiguration
public class CustomCsrfShowcaseTests {
@Autowired
private WebApplicationContext context;
@Autowired
private CsrfTokenRepository repository;
private MockMvc mvc;
@BeforeEach
public void setup() {
this.mvc = MockMvcBuilders.webAppContextSetup(this.context).defaultRequest(get("/").with(csrf()))
.apply(springSecurity()).build();
}
@Test
public void postWithCsrfWorks() throws Exception {
this.mvc.perform(post("/").with(csrf())).andExpect(status().isNotFound());
}
@Test
public void postWithCsrfWorksWithPut() throws Exception {
this.mvc.perform(put("/").with(csrf())).andExpect(status().isNotFound());
}
@Configuration
@EnableWebSecurity
@EnableWebMvc
static class Config {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.csrf()
.csrfTokenRepository(repo());
return http.build();
// @formatter:on
}
@Autowired
void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
// @formatter:off
auth
.inMemoryAuthentication()
.withUser("user").password("password").roles("USER");
// @formatter:on
}
@Bean
CsrfTokenRepository repo() {
HttpSessionCsrfTokenRepository repo = new HttpSessionCsrfTokenRepository();
repo.setParameterName("custom_csrf");
return repo;
}
}
}
| 3,963 | 35.036364 | 110 | java |
null | spring-security-main/test/src/test/java/org/springframework/security/test/web/servlet/showcase/csrf/CsrfShowcaseTests.java | /*
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.test.web.servlet.showcase.csrf;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf;
import static org.springframework.security.test.web.servlet.setup.SecurityMockMvcConfigurers.springSecurity;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@ExtendWith(SpringExtension.class)
@ContextConfiguration(classes = CsrfShowcaseTests.Config.class)
@WebAppConfiguration
public class CsrfShowcaseTests {
@Autowired
private WebApplicationContext context;
private MockMvc mvc;
@BeforeEach
public void setup() {
this.mvc = MockMvcBuilders.webAppContextSetup(this.context).apply(springSecurity()).build();
}
@Test
public void postWithCsrfWorks() throws Exception {
this.mvc.perform(post("/").with(csrf())).andExpect(status().isNotFound());
}
@Test
public void postWithCsrfWorksWithPut() throws Exception {
this.mvc.perform(put("/").with(csrf())).andExpect(status().isNotFound());
}
@Test
public void postWithNoCsrfForbidden() throws Exception {
this.mvc.perform(post("/")).andExpect(status().isForbidden());
}
@Configuration
@EnableWebSecurity
@EnableWebMvc
static class Config {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
return http.build();
}
@Autowired
void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
// @formatter:off
auth
.inMemoryAuthentication()
.withUser("user").password("password").roles("USER");
// @formatter:on
}
}
}
| 3,482 | 35.28125 | 110 | java |
null | spring-security-main/test/src/test/java/org/springframework/security/test/web/servlet/showcase/csrf/DefaultCsrfShowcaseTests.java | /*
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.test.web.servlet.showcase.csrf;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf;
import static org.springframework.security.test.web.servlet.setup.SecurityMockMvcConfigurers.springSecurity;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@ExtendWith(SpringExtension.class)
@ContextConfiguration(classes = DefaultCsrfShowcaseTests.Config.class)
@WebAppConfiguration
public class DefaultCsrfShowcaseTests {
@Autowired
private WebApplicationContext context;
private MockMvc mvc;
@BeforeEach
public void setup() {
this.mvc = MockMvcBuilders.webAppContextSetup(this.context).defaultRequest(get("/").with(csrf()))
.apply(springSecurity()).build();
}
@Test
public void postWithCsrfWorks() throws Exception {
this.mvc.perform(post("/")).andExpect(status().isNotFound());
}
@Test
public void postWithCsrfWorksWithPut() throws Exception {
this.mvc.perform(put("/")).andExpect(status().isNotFound());
}
@Configuration
@EnableWebSecurity
@EnableWebMvc
static class Config {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
return http.build();
}
@Autowired
void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
// @formatter:off
auth
.inMemoryAuthentication()
.withUser("user").password("password").roles("USER");
// @formatter:on
}
}
}
| 3,466 | 36.27957 | 110 | java |
null | spring-security-main/test/src/test/java/org/springframework/security/test/web/servlet/showcase/secured/WithUserDetailsClassLevelAuthenticationTests.java | /*
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.test.web.servlet.showcase.secured;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.core.userdetails.PasswordEncodedUser;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.test.context.support.WithUserDetails;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import static org.springframework.security.test.web.servlet.response.SecurityMockMvcResultMatchers.authenticated;
import static org.springframework.security.test.web.servlet.setup.SecurityMockMvcConfigurers.springSecurity;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@ExtendWith(SpringExtension.class)
@ContextConfiguration(classes = WithUserDetailsClassLevelAuthenticationTests.Config.class)
@WebAppConfiguration
@WithUserDetails("admin")
public class WithUserDetailsClassLevelAuthenticationTests {
@Autowired
private WebApplicationContext context;
private MockMvc mvc;
@BeforeEach
public void setup() {
this.mvc = MockMvcBuilders.webAppContextSetup(this.context).apply(springSecurity()).build();
}
@Test
public void requestRootUrlWithAdmin() throws Exception {
this.mvc.perform(get("/"))
// Ensure we got past Security
.andExpect(status().isNotFound())
// Ensure it appears we are authenticated with user
.andExpect(authenticated().withUsername("admin").withRoles("ADMIN", "USER"));
}
@Test
public void requestProtectedUrlWithAdmin() throws Exception {
this.mvc.perform(get("/admin"))
// Ensure we got past Security
.andExpect(status().isNotFound())
// Ensure it appears we are authenticated with user
.andExpect(authenticated().withUsername("admin").withRoles("ADMIN", "USER"));
}
@Configuration
@EnableWebSecurity
@EnableWebMvc
static class Config {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests()
.requestMatchers("/admin/**").hasRole("ADMIN")
.anyRequest().authenticated()
.and()
.formLogin();
// @formatter:on
return http.build();
}
@Bean
UserDetailsService userDetailsService() {
return new InMemoryUserDetailsManager(PasswordEncodedUser.user(), PasswordEncodedUser.admin());
}
}
}
| 3,992 | 36.669811 | 113 | java |
null | spring-security-main/test/src/test/java/org/springframework/security/test/web/servlet/showcase/secured/WithUserDetailsAuthenticationTests.java | /*
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.test.web.servlet.showcase.secured;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.core.userdetails.PasswordEncodedUser;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.test.context.support.WithUserDetails;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import static org.springframework.security.test.web.servlet.response.SecurityMockMvcResultMatchers.authenticated;
import static org.springframework.security.test.web.servlet.setup.SecurityMockMvcConfigurers.springSecurity;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@ExtendWith(SpringExtension.class)
@ContextConfiguration(classes = WithUserDetailsAuthenticationTests.Config.class)
@WebAppConfiguration
public class WithUserDetailsAuthenticationTests {
@Autowired
private WebApplicationContext context;
private MockMvc mvc;
@BeforeEach
public void setup() {
this.mvc = MockMvcBuilders.webAppContextSetup(this.context).apply(springSecurity()).build();
}
@Test
@WithUserDetails
public void requestProtectedUrlWithUser() throws Exception {
this.mvc.perform(get("/"))
// Ensure we got past Security
.andExpect(status().isNotFound())
// Ensure it appears we are authenticated with user
.andExpect(authenticated().withUsername("user"));
}
@Test
@WithUserDetails("admin")
public void requestProtectedUrlWithAdmin() throws Exception {
this.mvc.perform(get("/admin"))
// Ensure we got past Security
.andExpect(status().isNotFound())
// Ensure it appears we are authenticated with user
.andExpect(authenticated().withUsername("admin").withRoles("ADMIN", "USER"));
}
@Configuration
@EnableWebSecurity
@EnableWebMvc
static class Config {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests()
.requestMatchers("/admin/**").hasRole("ADMIN")
.anyRequest().authenticated()
.and()
.formLogin();
// @formatter:on
return http.build();
}
@Bean
UserDetailsService userDetailsService() {
return new InMemoryUserDetailsManager(PasswordEncodedUser.user(), PasswordEncodedUser.admin());
}
}
}
| 3,967 | 36.084112 | 113 | java |
null | spring-security-main/test/src/test/java/org/springframework/security/test/web/servlet/showcase/secured/SecurityRequestsTests.java | /*
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.test.web.servlet.showcase.secured;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.TestingAuthenticationToken;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.PasswordEncodedUser;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.authentication;
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.user;
import static org.springframework.security.test.web.servlet.response.SecurityMockMvcResultMatchers.authenticated;
import static org.springframework.security.test.web.servlet.setup.SecurityMockMvcConfigurers.springSecurity;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@ExtendWith(SpringExtension.class)
@ContextConfiguration(classes = SecurityRequestsTests.Config.class)
@WebAppConfiguration
public class SecurityRequestsTests {
@Autowired
private WebApplicationContext context;
@Autowired
private UserDetailsService userDetailsService;
private MockMvc mvc;
@BeforeEach
public void setup() {
this.mvc = MockMvcBuilders.webAppContextSetup(this.context).apply(springSecurity()).build();
}
@Test
public void requestProtectedUrlWithUser() throws Exception {
this.mvc.perform(get("/").with(user("user")))
// Ensure we got past Security
.andExpect(status().isNotFound())
// Ensure it appears we are authenticated with user
.andExpect(authenticated().withUsername("user"));
}
@Test
public void requestProtectedUrlWithAdmin() throws Exception {
this.mvc.perform(get("/admin").with(user("admin").roles("ADMIN")))
// Ensure we got past Security
.andExpect(status().isNotFound())
// Ensure it appears we are authenticated with admin
.andExpect(authenticated().withUsername("admin"));
}
@Test
public void requestProtectedUrlWithUserDetails() throws Exception {
UserDetails user = this.userDetailsService.loadUserByUsername("user");
this.mvc.perform(get("/").with(user(user)))
// Ensure we got past Security
.andExpect(status().isNotFound())
// Ensure it appears we are authenticated with user
.andExpect(authenticated().withAuthenticationPrincipal(user));
}
@Test
public void requestProtectedUrlWithAuthentication() throws Exception {
Authentication authentication = new TestingAuthenticationToken("test", "notused", "ROLE_USER");
this.mvc.perform(get("/").with(authentication(authentication)))
// Ensure we got past Security
.andExpect(status().isNotFound())
// Ensure it appears we are authenticated with user
.andExpect(authenticated().withAuthentication(authentication));
}
@Configuration
@EnableWebSecurity
@EnableWebMvc
static class Config {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests()
.requestMatchers("/admin/**").hasRole("ADMIN")
.anyRequest().authenticated()
.and()
.formLogin();
// @formatter:on
return http.build();
}
@Bean
UserDetailsService userDetailsService() {
return new InMemoryUserDetailsManager(PasswordEncodedUser.user());
}
}
}
| 5,155 | 38.060606 | 120 | java |
null | spring-security-main/test/src/test/java/org/springframework/security/test/web/servlet/showcase/secured/WithUserClassLevelAuthenticationTests.java | /*
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.test.web.servlet.showcase.secured;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.test.context.support.WithAnonymousUser;
import org.springframework.security.test.context.support.WithMockUser;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import static org.springframework.security.test.web.servlet.response.SecurityMockMvcResultMatchers.authenticated;
import static org.springframework.security.test.web.servlet.response.SecurityMockMvcResultMatchers.unauthenticated;
import static org.springframework.security.test.web.servlet.setup.SecurityMockMvcConfigurers.springSecurity;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@ExtendWith(SpringExtension.class)
@ContextConfiguration(classes = WithUserClassLevelAuthenticationTests.Config.class)
@WebAppConfiguration
@WithMockUser(roles = "ADMIN")
public class WithUserClassLevelAuthenticationTests {
@Autowired
private WebApplicationContext context;
private MockMvc mvc;
@BeforeEach
public void setup() {
this.mvc = MockMvcBuilders.webAppContextSetup(this.context).apply(springSecurity()).build();
}
@Test
public void requestProtectedUrlWithUser() throws Exception {
this.mvc.perform(get("/"))
// Ensure we got past Security
.andExpect(status().isNotFound())
// Ensure it appears we are authenticated with user
.andExpect(authenticated().withUsername("user"));
}
@Test
public void requestProtectedUrlWithAdmin() throws Exception {
this.mvc.perform(get("/admin"))
// Ensure we got past Security
.andExpect(status().isNotFound())
// Ensure it appears we are authenticated with user
.andExpect(authenticated().withUsername("user").withRoles("ADMIN"));
}
@Test
@WithAnonymousUser
public void requestProtectedUrlWithAnonymous() throws Exception {
this.mvc.perform(get("/"))
// Ensure did not get past security
.andExpect(status().isUnauthorized())
// Ensure not authenticated
.andExpect(unauthenticated());
}
@Configuration
@EnableWebSecurity
@EnableWebMvc
static class Config {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests()
.requestMatchers("/admin/**").hasRole("ADMIN")
.anyRequest().authenticated()
.and()
.httpBasic();
return http.build();
// @formatter:on
}
@Autowired
void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
// @formatter:off
auth
.inMemoryAuthentication()
.withUser("user").password("password").roles("USER");
// @formatter:on
}
}
}
| 4,376 | 35.475 | 115 | java |
null | spring-security-main/test/src/test/java/org/springframework/security/test/web/servlet/showcase/secured/WithUserAuthenticationTests.java | /*
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.test.web.servlet.showcase.secured;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.test.context.support.WithMockUser;
import org.springframework.security.test.web.servlet.setup.SecurityMockMvcConfigurers;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import static org.springframework.security.test.web.servlet.response.SecurityMockMvcResultMatchers.authenticated;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@ExtendWith(SpringExtension.class)
@ContextConfiguration(classes = WithUserAuthenticationTests.Config.class)
@WebAppConfiguration
public class WithUserAuthenticationTests {
@Autowired
private WebApplicationContext context;
private MockMvc mvc;
@BeforeEach
public void setup() {
this.mvc = MockMvcBuilders.webAppContextSetup(this.context).apply(SecurityMockMvcConfigurers.springSecurity())
.build();
}
@Test
@WithMockUser
public void requestProtectedUrlWithUser() throws Exception {
this.mvc.perform(get("/"))
// Ensure we got past Security
.andExpect(status().isNotFound())
// Ensure it appears we are authenticated with user
.andExpect(authenticated().withUsername("user"));
}
@Test
@WithAdminRob
public void requestProtectedUrlWithAdminRob() throws Exception {
this.mvc.perform(get("/"))
// Ensure we got past Security
.andExpect(status().isNotFound())
// Ensure it appears we are authenticated with user
.andExpect(authenticated().withUsername("rob").withRoles("ADMIN"));
}
@Test
@WithMockUser(roles = "ADMIN")
public void requestProtectedUrlWithAdmin() throws Exception {
this.mvc.perform(get("/admin"))
// Ensure we got past Security
.andExpect(status().isNotFound())
// Ensure it appears we are authenticated with user
.andExpect(authenticated().withUsername("user").withRoles("ADMIN"));
}
@Configuration
@EnableWebSecurity
@EnableWebMvc
static class Config {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests()
.requestMatchers("/admin/**").hasRole("ADMIN")
.anyRequest().authenticated()
.and()
.formLogin();
return http.build();
// @formatter:on
}
@Autowired
void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
// @formatter:off
auth
.inMemoryAuthentication()
.withUser("user").password("password").roles("USER");
// @formatter:on
}
}
}
| 4,236 | 34.308333 | 113 | java |
null | spring-security-main/test/src/test/java/org/springframework/security/test/web/servlet/showcase/secured/DefaultfSecurityRequestsTests.java | /*
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.test.web.servlet.showcase.secured;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.anonymous;
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.user;
import static org.springframework.security.test.web.servlet.response.SecurityMockMvcResultMatchers.authenticated;
import static org.springframework.security.test.web.servlet.response.SecurityMockMvcResultMatchers.unauthenticated;
import static org.springframework.security.test.web.servlet.setup.SecurityMockMvcConfigurers.springSecurity;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@ExtendWith(SpringExtension.class)
@ContextConfiguration(classes = DefaultfSecurityRequestsTests.Config.class)
@WebAppConfiguration
public class DefaultfSecurityRequestsTests {
@Autowired
private WebApplicationContext context;
private MockMvc mvc;
@BeforeEach
public void setup() {
this.mvc = MockMvcBuilders.webAppContextSetup(this.context)
.defaultRequest(get("/").with(user("user").roles("ADMIN"))).apply(springSecurity()).build();
}
@Test
public void requestProtectedUrlWithUser() throws Exception {
this.mvc.perform(get("/"))
// Ensure we got past Security
.andExpect(status().isNotFound())
// Ensure it appears we are authenticated with user
.andExpect(authenticated().withUsername("user"));
}
@Test
public void requestProtectedUrlWithAdmin() throws Exception {
this.mvc.perform(get("/admin"))
// Ensure we got past Security
.andExpect(status().isNotFound())
// Ensure it appears we are authenticated with user
.andExpect(authenticated().withUsername("user"));
}
@Test
public void requestProtectedUrlWithAnonymous() throws Exception {
this.mvc.perform(get("/admin").with(anonymous()))
// Ensure we got past Security
.andExpect(status().isUnauthorized())
// Ensure it appears we are authenticated with user
.andExpect(unauthenticated());
}
@Configuration
@EnableWebSecurity
@EnableWebMvc
static class Config {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests()
.requestMatchers("/admin/**").hasRole("ADMIN")
.anyRequest().authenticated()
.and()
.httpBasic();
return http.build();
// @formatter:on
}
@Autowired
void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
// @formatter:off
auth
.inMemoryAuthentication()
.withUser("user").password("password").roles("USER");
// @formatter:on
}
}
}
| 4,476 | 36.621849 | 115 | java |
null | spring-security-main/test/src/test/java/org/springframework/security/test/web/servlet/showcase/secured/WithAdminRob.java | /*
* Copyright 2002-2015 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.test.web.servlet.showcase.secured;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.springframework.security.test.context.support.WithMockUser;
@Target({ ElementType.METHOD, ElementType.TYPE })
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Documented
@WithMockUser(value = "rob", roles = "ADMIN")
public @interface WithAdminRob {
}
| 1,200 | 32.361111 | 75 | java |
null | spring-security-main/test/src/test/java/org/springframework/security/test/web/servlet/response/SecurityMockMvcResultHandlersTests.java | /*
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.test.web.servlet.response;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.test.context.support.WithMockUser;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import static org.assertj.core.api.Assertions.assertThat;
import static org.springframework.security.test.web.servlet.response.SecurityMockMvcResultHandlers.exportTestSecurityContext;
import static org.springframework.security.test.web.servlet.setup.SecurityMockMvcConfigurers.springSecurity;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
@ExtendWith(SpringExtension.class)
@ContextConfiguration(classes = SecurityMockMvcResultHandlersTests.Config.class)
@WebAppConfiguration
public class SecurityMockMvcResultHandlersTests {
@Autowired
private WebApplicationContext context;
private MockMvc mockMvc;
@BeforeEach
public void setup() {
// @formatter:off
this.mockMvc = MockMvcBuilders
.webAppContextSetup(this.context)
.apply(springSecurity())
.build();
// @formatter:on
}
@AfterEach
public void tearDown() {
SecurityContextHolder.clearContext();
}
@Test
@WithMockUser
public void withTestSecurityContextCopiedToSecurityContextHolder() throws Exception {
this.mockMvc.perform(get("/")).andDo(exportTestSecurityContext());
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
assertThat(authentication.getName()).isEqualTo("user");
assertThat(authentication.getAuthorities()).hasSize(1).first().hasToString("ROLE_USER");
}
@Test
@WithMockUser
public void withTestSecurityContextNotCopiedToSecurityContextHolder() throws Exception {
this.mockMvc.perform(get("/"));
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
assertThat(authentication).isNull();
}
@Configuration
@EnableWebSecurity
@EnableWebMvc
static class Config {
@RestController
static class Controller {
@RequestMapping("/")
String ok() {
return "ok";
}
}
}
}
| 3,674 | 32.715596 | 125 | java |
null | spring-security-main/test/src/test/java/org/springframework/security/test/web/servlet/response/Gh3409Tests.java | /*
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.test.web.servlet.response;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.core.context.SecurityContextImpl;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.securityContext;
import static org.springframework.security.test.web.servlet.response.SecurityMockMvcResultMatchers.unauthenticated;
import static org.springframework.security.test.web.servlet.setup.SecurityMockMvcConfigurers.springSecurity;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
/**
* @author Rob Winch
* @since 4.1
*/
@ExtendWith(SpringExtension.class)
@ContextConfiguration
@WebAppConfiguration
public class Gh3409Tests {
@Autowired
private WebApplicationContext context;
private MockMvc mockMvc;
@BeforeEach
public void setup() {
// @formatter:off
this.mockMvc = MockMvcBuilders
.webAppContextSetup(this.context)
.apply(springSecurity())
.build();
// @formatter:on
}
// gh-3409
@Test
public void unauthenticatedAnonymousUser() throws Exception {
// @formatter:off
this.mockMvc
.perform(get("/public/")
.with(securityContext(new SecurityContextImpl())));
this.mockMvc
.perform(get("/public/"))
.andExpect(unauthenticated());
// @formatter:on
}
@Test
public void unauthenticatedNullAuthenitcation() throws Exception {
// @formatter:off
this.mockMvc
.perform(get("/")
.with(securityContext(new SecurityContextImpl())));
this.mockMvc
.perform(get("/"))
.andExpect(unauthenticated());
// @formatter:on
}
@Configuration
@EnableWebSecurity
@EnableWebMvc
static class Config {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests()
.requestMatchers("/public/**").permitAll()
.anyRequest().authenticated()
.and()
.formLogin().and()
.httpBasic();
return http.build();
// @formatter:on
}
}
}
| 3,582 | 30.429825 | 121 | java |
null | spring-security-main/test/src/test/java/org/springframework/security/test/web/servlet/response/SecurityMockWithAuthoritiesMvcResultMatchersTests.java | /*
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.test.web.servlet.response;
import java.util.ArrayList;
import java.util.List;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestBuilders.formLogin;
import static org.springframework.security.test.web.servlet.response.SecurityMockMvcResultMatchers.authenticated;
import static org.springframework.security.test.web.servlet.setup.SecurityMockMvcConfigurers.springSecurity;
@ExtendWith(SpringExtension.class)
@ContextConfiguration(classes = SecurityMockWithAuthoritiesMvcResultMatchersTests.Config.class)
@WebAppConfiguration
public class SecurityMockWithAuthoritiesMvcResultMatchersTests {
@Autowired
private WebApplicationContext context;
private MockMvc mockMvc;
@BeforeEach
public void setup() {
this.mockMvc = MockMvcBuilders.webAppContextSetup(this.context).apply(springSecurity()).build();
}
@Test
public void withAuthoritiesNotOrderSensitive() throws Exception {
List<SimpleGrantedAuthority> grantedAuthorities = new ArrayList<>();
grantedAuthorities.add(new SimpleGrantedAuthority("ROLE_ADMIN"));
grantedAuthorities.add(new SimpleGrantedAuthority("ROLE_SELLER"));
this.mockMvc.perform(formLogin()).andExpect(authenticated().withAuthorities(grantedAuthorities));
}
@Test
public void withAuthoritiesFailsIfNotAllRoles() throws Exception {
List<SimpleGrantedAuthority> grantedAuthorities = new ArrayList<>();
grantedAuthorities.add(new SimpleGrantedAuthority("ROLE_ADMIN"));
assertThatExceptionOfType(AssertionError.class).isThrownBy(
() -> this.mockMvc.perform(formLogin()).andExpect(authenticated().withAuthorities(grantedAuthorities)));
}
@Configuration
@EnableWebSecurity
@EnableWebMvc
static class Config {
@Bean
UserDetailsService userDetailsService() {
// @formatter:off
UserDetails user = User.withDefaultPasswordEncoder().username("user").password("password").roles("ADMIN", "SELLER").build();
return new InMemoryUserDetailsManager(user);
// @formatter:on
}
@RestController
static class Controller {
@RequestMapping("/")
String ok() {
return "ok";
}
}
}
}
| 4,153 | 37.82243 | 127 | java |
null | spring-security-main/test/src/test/java/org/springframework/security/test/web/servlet/response/SecurityMockMvcResultMatchersTests.java | /*
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.test.web.servlet.response;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestBuilders.formLogin;
import static org.springframework.security.test.web.servlet.response.SecurityMockMvcResultMatchers.authenticated;
import static org.springframework.security.test.web.servlet.setup.SecurityMockMvcConfigurers.springSecurity;
@ExtendWith(SpringExtension.class)
@ContextConfiguration(classes = SecurityMockMvcResultMatchersTests.Config.class)
@WebAppConfiguration
public class SecurityMockMvcResultMatchersTests {
@Autowired
private WebApplicationContext context;
private MockMvc mockMvc;
@BeforeEach
public void setup() {
// @formatter:off
this.mockMvc = MockMvcBuilders
.webAppContextSetup(this.context)
.apply(springSecurity())
.build();
// @formatter:on
}
@Test
public void withAuthenticationWhenMatchesThenSuccess() throws Exception {
this.mockMvc.perform(formLogin()).andExpect(authenticated().withAuthentication(
(auth) -> assertThat(auth).isInstanceOf(UsernamePasswordAuthenticationToken.class)));
}
@Test
public void withAuthenticationWhenNotMatchesThenFails() throws Exception {
assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> this.mockMvc.perform(formLogin()).andExpect(
authenticated().withAuthentication((auth) -> assertThat(auth.getName()).isEqualTo("notmatch"))));
}
// SEC-2719
@Test
public void withRolesNotOrderSensitive() throws Exception {
// @formatter:off
this.mockMvc
.perform(formLogin())
.andExpect(authenticated().withRoles("USER", "SELLER"))
.andExpect(authenticated().withRoles("SELLER", "USER"));
// @formatter:on
}
@Test
public void withRolesFailsIfNotAllRoles() throws Exception {
assertThatExceptionOfType(AssertionError.class).isThrownBy(() ->
// @formatter:off
this.mockMvc
.perform(formLogin())
.andExpect(authenticated().withRoles("USER"))
// @formatter:on
);
}
@Configuration
@EnableWebSecurity
@EnableWebMvc
static class Config {
@Bean
UserDetailsService userDetailsService() {
// @formatter:off
UserDetails user = User.withDefaultPasswordEncoder().username("user").password("password").roles("USER", "SELLER").build();
// @formatter:on
return new InMemoryUserDetailsManager(user);
}
@RestController
static class Controller {
@RequestMapping("/")
String ok() {
return "ok";
}
}
}
}
| 4,535 | 34.4375 | 126 | java |
null | spring-security-main/test/src/test/java/org/springframework/security/test/context/TestSecurityContextHolderTests.java | /*
* Copyright 2002-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.test.context;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
public class TestSecurityContextHolderTests {
private SecurityContext context;
@BeforeEach
public void setup() {
this.context = SecurityContextHolder.createEmptyContext();
}
@AfterEach
public void cleanup() {
TestSecurityContextHolder.clearContext();
}
@Test
public void clearContextClearsBoth() {
SecurityContextHolder.setContext(this.context);
TestSecurityContextHolder.setContext(this.context);
TestSecurityContextHolder.clearContext();
assertThat(SecurityContextHolder.getContext()).isNotSameAs(this.context);
assertThat(TestSecurityContextHolder.getContext()).isNotSameAs(this.context);
}
@Test
public void getContextDefaultsNonNull() {
assertThat(TestSecurityContextHolder.getContext()).isNotNull();
assertThat(SecurityContextHolder.getContext()).isNotNull();
}
@Test
public void setContextSetsBoth() {
TestSecurityContextHolder.setContext(this.context);
assertThat(TestSecurityContextHolder.getContext()).isSameAs(this.context);
assertThat(SecurityContextHolder.getContext()).isSameAs(this.context);
}
@Test
public void setContextWithAuthentication() {
Authentication authentication = mock(Authentication.class);
TestSecurityContextHolder.setAuthentication(authentication);
assertThat(TestSecurityContextHolder.getContext().getAuthentication()).isSameAs(authentication);
}
}
| 2,426 | 31.797297 | 98 | java |
null | spring-security-main/test/src/test/java/org/springframework/security/test/context/showcase/CustomUserDetails.java | /*
* Copyright 2002-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.test.context.showcase;
import java.util.Collection;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
/**
* @author Rob Winch
*/
public class CustomUserDetails implements UserDetails {
private final String name;
private final String username;
private final Collection<? extends GrantedAuthority> authorities;
public CustomUserDetails(String name, String username) {
this.name = name;
this.username = username;
this.authorities = AuthorityUtils.createAuthorityList("ROLE_USER");
}
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return this.authorities;
}
@Override
public String getPassword() {
return null;
}
@Override
public String getUsername() {
return this.username;
}
@Override
public boolean isAccountNonExpired() {
return true;
}
@Override
public boolean isAccountNonLocked() {
return true;
}
@Override
public boolean isCredentialsNonExpired() {
return true;
}
@Override
public boolean isEnabled() {
return true;
}
@Override
public String toString() {
return "CustomUserDetails{" + "username='" + this.username + '\'' + '}';
}
}
| 1,935 | 22.325301 | 75 | java |
null | spring-security-main/test/src/test/java/org/springframework/security/test/context/showcase/WithMockUserParentTests.java | /*
* Copyright 2002-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.test.context.showcase;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.test.context.showcase.service.HelloMessageService;
import org.springframework.security.test.context.showcase.service.MessageService;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import static org.assertj.core.api.Assertions.assertThat;
/**
* @author Eddú Meléndez
*/
@ExtendWith(SpringExtension.class)
@ContextConfiguration(classes = WithMockUserParentTests.Config.class)
public class WithMockUserParentTests extends WithMockUserParent {
@Autowired
private MessageService messageService;
@Test
public void getMessageWithMockUser() {
String message = this.messageService.getMessage();
assertThat(message).contains("user");
}
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
@ComponentScan(basePackageClasses = HelloMessageService.class)
static class Config {
@Autowired
void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
// @formatter:off
auth
.inMemoryAuthentication()
.withUser("user").password("password").roles("USER");
// @formatter:on
}
}
}
| 2,326 | 33.731343 | 107 | java |
null | spring-security-main/test/src/test/java/org/springframework/security/test/context/showcase/WithMockUserTests.java | /*
* Copyright 2002-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.test.context.showcase;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.AliasFor;
import org.springframework.security.authentication.AuthenticationCredentialsNotFoundException;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.test.context.showcase.service.HelloMessageService;
import org.springframework.security.test.context.showcase.service.MessageService;
import org.springframework.security.test.context.support.WithMockUser;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
/**
* @author Rob Winch
*/
@ExtendWith(SpringExtension.class)
@ContextConfiguration(classes = WithMockUserTests.Config.class)
public class WithMockUserTests {
@Autowired
private MessageService messageService;
@Test
public void getMessageUnauthenticated() {
assertThatExceptionOfType(AuthenticationCredentialsNotFoundException.class)
.isThrownBy(() -> this.messageService.getMessage());
}
@Test
@WithMockUser
public void getMessageWithMockUser() {
String message = this.messageService.getMessage();
assertThat(message).contains("user");
}
@Test
@WithMockUser("customUsername")
public void getMessageWithMockUserCustomUsername() {
String message = this.messageService.getMessage();
assertThat(message).contains("customUsername");
}
@Test
@WithMockUser(username = "admin", roles = { "USER", "ADMIN" })
public void getMessageWithMockUserCustomUser() {
String message = this.messageService.getMessage();
assertThat(message).contains("admin").contains("ROLE_USER").contains("ROLE_ADMIN");
}
@Test
@WithMockUser(username = "admin", authorities = { "ADMIN", "USER" })
public void getMessageWithMockUserCustomAuthorities() {
String message = this.messageService.getMessage();
assertThat(message).contains("admin").contains("ADMIN").contains("USER").doesNotContain("ROLE_");
}
@Configuration
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@Inherited
@WithMockUser(roles = "ADMIN")
public @interface WithAdminUser {
@AliasFor(annotation = WithMockUser.class, attribute = "value")
String value();
}
@Test
@WithAdminUser("admin")
public void getMessageWithMetaAnnotationAdminUser() {
String message = this.messageService.getMessage();
assertThat(message).contains("admin").contains("ADMIN").contains("ROLE_ADMIN");
}
@EnableGlobalMethodSecurity(prePostEnabled = true)
@ComponentScan(basePackageClasses = HelloMessageService.class)
static class Config {
@Autowired
void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
// @formatter:off
auth
.inMemoryAuthentication()
.withUser("user").password("password").roles("USER");
// @formatter:on
}
}
}
| 4,197 | 33.130081 | 107 | java |
null | spring-security-main/test/src/test/java/org/springframework/security/test/context/showcase/WithMockCustomUserSecurityContextFactory.java | /*
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.test.context.showcase;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.test.context.support.WithSecurityContextFactory;
/**
* @author Rob Winch
*/
public class WithMockCustomUserSecurityContextFactory implements WithSecurityContextFactory<WithMockCustomUser> {
@Override
public SecurityContext createSecurityContext(WithMockCustomUser customUser) {
SecurityContext context = SecurityContextHolder.createEmptyContext();
CustomUserDetails principal = new CustomUserDetails(customUser.name(), customUser.username());
Authentication auth = UsernamePasswordAuthenticationToken.authenticated(principal, "password",
principal.getAuthorities());
context.setAuthentication(auth);
return context;
}
}
| 1,645 | 39.146341 | 113 | java |
null | spring-security-main/test/src/test/java/org/springframework/security/test/context/showcase/WithMockUserParent.java | /*
* Copyright 2002-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.test.context.showcase;
import org.springframework.security.test.context.support.WithMockUser;
/**
* @author Eddú Meléndez
*/
@WithMockUser
public class WithMockUserParent {
}
| 840 | 29.035714 | 75 | java |
null | spring-security-main/test/src/test/java/org/springframework/security/test/context/showcase/WithUserDetailsTests.java | /*
* Copyright 2002-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.test.context.showcase;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationCredentialsNotFoundException;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.test.context.showcase.service.HelloMessageService;
import org.springframework.security.test.context.showcase.service.MessageService;
import org.springframework.security.test.context.support.WithUserDetails;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
/**
* @author Rob Winch
*/
@ExtendWith(SpringExtension.class)
@ContextConfiguration(classes = WithUserDetailsTests.Config.class)
public class WithUserDetailsTests {
@Autowired
private MessageService messageService;
@Test
public void getMessageUnauthenticated() {
assertThatExceptionOfType(AuthenticationCredentialsNotFoundException.class)
.isThrownBy(() -> this.messageService.getMessage());
}
@Test
@WithUserDetails
public void getMessageWithUserDetails() {
String message = this.messageService.getMessage();
assertThat(message).contains("user");
assertThat(getPrincipal()).isInstanceOf(CustomUserDetails.class);
}
@Test
@WithUserDetails("customUsername")
public void getMessageWithUserDetailsCustomUsername() {
String message = this.messageService.getMessage();
assertThat(message).contains("customUsername");
assertThat(getPrincipal()).isInstanceOf(CustomUserDetails.class);
}
@Test
@WithUserDetails(value = "customUsername", userDetailsServiceBeanName = "myUserDetailsService")
public void getMessageWithUserDetailsServiceBeanName() {
String message = this.messageService.getMessage();
assertThat(message).contains("customUsername");
assertThat(getPrincipal()).isInstanceOf(CustomUserDetails.class);
}
private Object getPrincipal() {
return SecurityContextHolder.getContext().getAuthentication().getPrincipal();
}
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
@ComponentScan(basePackageClasses = HelloMessageService.class)
static class Config {
@Autowired
void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(myUserDetailsService());
}
@Bean
UserDetailsService myUserDetailsService() {
return new CustomUserDetailsService();
}
}
static class CustomUserDetailsService implements UserDetailsService {
@Override
public UserDetails loadUserByUsername(final String username) throws UsernameNotFoundException {
return new CustomUserDetails("name", username);
}
}
}
| 4,138 | 35.628319 | 107 | java |
null | spring-security-main/test/src/test/java/org/springframework/security/test/context/showcase/WithMockCustomUser.java | /*
* Copyright 2002-2014 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.test.context.showcase;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import org.springframework.security.test.context.support.WithSecurityContext;
/**
* @author Rob Winch
*/
@Retention(RetentionPolicy.RUNTIME)
@WithSecurityContext(factory = WithMockCustomUserSecurityContextFactory.class)
public @interface WithMockCustomUser {
/**
* The username to be used. The default is rob
* @return
*/
String username() default "rob";
/**
* The roles to use. The default is "USER". A
* {@link org.springframework.security.core.GrantedAuthority} will be created for each
* value within roles. Each value in roles will automatically be prefixed with
* "ROLE_". For example, the default will result in "ROLE_USER" being used.
* @return
*/
String[] roles() default { "USER" };
/**
* The name of the user
* @return
*/
String name() default "Rob Winch";
}
| 1,576 | 28.754717 | 87 | java |
null | spring-security-main/test/src/test/java/org/springframework/security/test/context/showcase/service/HelloMessageService.java | /*
* Copyright 2002-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.test.context.showcase.service;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
/**
* @author Rob Winch
*/
@Component
public class HelloMessageService implements MessageService {
@Override
@PreAuthorize("authenticated")
public String getMessage() {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
return "Hello " + authentication;
}
}
| 1,243 | 31.736842 | 89 | java |
null | spring-security-main/test/src/test/java/org/springframework/security/test/context/showcase/service/MessageService.java | /*
* Copyright 2002-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.test.context.showcase.service;
/**
* @author Rob Winch
*/
public interface MessageService {
String getMessage();
}
| 781 | 27.962963 | 75 | java |
null | spring-security-main/test/src/test/java/org/springframework/security/test/context/support/WithSecurityContextTestExecutionListenerTests.java | /*
* Copyright 2002-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.test.context.support;
import java.lang.reflect.Method;
import java.util.function.Supplier;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.ArgumentCaptor;
import org.mockito.ArgumentMatchers;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.TestingAuthenticationToken;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextImpl;
import org.springframework.security.test.context.TestSecurityContextHolder;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.TestContext;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
/**
* @author Rob Winch
* @since 5.0
*/
@ExtendWith({ MockitoExtension.class, SpringExtension.class })
@ContextConfiguration(classes = WithSecurityContextTestExecutionListenerTests.NoOpConfiguration.class)
public class WithSecurityContextTestExecutionListenerTests {
@Autowired
private ApplicationContext applicationContext;
@Mock
private TestContext testContext;
private WithSecurityContextTestExecutionListener listener = new WithSecurityContextTestExecutionListener();
@AfterEach
public void cleanup() {
TestSecurityContextHolder.clearContext();
}
@Test
public void beforeTestMethodWhenWithMockUserTestExecutionDefaultThenSecurityContextSet() throws Exception {
Method testMethod = TheTest.class.getMethod("withMockUserDefault");
given(this.testContext.getApplicationContext()).willReturn(this.applicationContext);
given(this.testContext.getTestMethod()).willReturn(testMethod);
this.listener.beforeTestMethod(this.testContext);
assertThat(TestSecurityContextHolder.getContext().getAuthentication()).isNotNull();
verify(this.testContext, never()).setAttribute(
eq(WithSecurityContextTestExecutionListener.SECURITY_CONTEXT_ATTR_NAME), any(SecurityContext.class));
}
@Test
public void beforeTestMethodWhenWithMockUserTestMethodThenSecurityContextSet() throws Exception {
Method testMethod = TheTest.class.getMethod("withMockUserTestMethod");
given(this.testContext.getApplicationContext()).willReturn(this.applicationContext);
given(this.testContext.getTestMethod()).willReturn(testMethod);
this.listener.beforeTestMethod(this.testContext);
assertThat(TestSecurityContextHolder.getContext().getAuthentication()).isNotNull();
verify(this.testContext, never()).setAttribute(
eq(WithSecurityContextTestExecutionListener.SECURITY_CONTEXT_ATTR_NAME), any(SecurityContext.class));
}
@Test
public void beforeTestMethodWhenWithMockUserTestExecutionThenTestContextSet() throws Exception {
Method testMethod = TheTest.class.getMethod("withMockUserTestExecution");
given(this.testContext.getApplicationContext()).willReturn(this.applicationContext);
given(this.testContext.getTestMethod()).willReturn(testMethod);
this.listener.beforeTestMethod(this.testContext);
assertThat(TestSecurityContextHolder.getContext().getAuthentication()).isNull();
verify(this.testContext).setAttribute(eq(WithSecurityContextTestExecutionListener.SECURITY_CONTEXT_ATTR_NAME),
ArgumentMatchers.<Supplier<SecurityContext>>any());
}
@Test
@SuppressWarnings("unchecked")
public void beforeTestMethodWhenWithMockUserTestExecutionThenTestContextSupplierOk() throws Exception {
Method testMethod = TheTest.class.getMethod("withMockUserTestExecution");
given(this.testContext.getApplicationContext()).willReturn(this.applicationContext);
given(this.testContext.getTestMethod()).willReturn(testMethod);
this.listener.beforeTestMethod(this.testContext);
ArgumentCaptor<Supplier<SecurityContext>> supplierCaptor = ArgumentCaptor.forClass(Supplier.class);
verify(this.testContext).setAttribute(eq(WithSecurityContextTestExecutionListener.SECURITY_CONTEXT_ATTR_NAME),
supplierCaptor.capture());
assertThat(supplierCaptor.getValue().get().getAuthentication()).isNotNull();
}
@Test
// gh-6591
public void beforeTestMethodWhenTestExecutionThenDelayFactoryCreate() throws Exception {
Method testMethod = TheTest.class.getMethod("withUserDetails");
given(this.testContext.getApplicationContext()).willReturn(this.applicationContext);
// do not set a UserDetailsService Bean so it would fail if looked up
given(this.testContext.getTestMethod()).willReturn(testMethod);
this.listener.beforeTestMethod(this.testContext);
// bean lookup of UserDetailsService would fail if it has already been looked up
}
@Test
public void beforeTestExecutionWhenTestContextNullThenSecurityContextNotSet() {
this.listener.beforeTestExecution(this.testContext);
assertThat(TestSecurityContextHolder.getContext().getAuthentication()).isNull();
}
@Test
public void beforeTestExecutionWhenTestContextNotNullThenSecurityContextSet() {
SecurityContextImpl securityContext = new SecurityContextImpl();
securityContext.setAuthentication(new TestingAuthenticationToken("user", "passsword", "ROLE_USER"));
Supplier<SecurityContext> supplier = () -> securityContext;
given(this.testContext.removeAttribute(WithSecurityContextTestExecutionListener.SECURITY_CONTEXT_ATTR_NAME))
.willReturn(supplier);
this.listener.beforeTestExecution(this.testContext);
assertThat(TestSecurityContextHolder.getContext().getAuthentication())
.isEqualTo(securityContext.getAuthentication());
}
@Configuration
static class NoOpConfiguration {
}
static class TheTest {
@WithMockUser(setupBefore = TestExecutionEvent.TEST_EXECUTION)
public void withMockUserTestExecution() {
}
@WithMockUser(setupBefore = TestExecutionEvent.TEST_METHOD)
public void withMockUserTestMethod() {
}
@WithMockUser
public void withMockUserDefault() {
}
@WithUserDetails(setupBefore = TestExecutionEvent.TEST_EXECUTION)
public void withUserDetails() {
}
}
}
| 7,084 | 40.676471 | 112 | java |
null | spring-security-main/test/src/test/java/org/springframework/security/test/context/support/WithUserDetailsSecurityContextFactoryTests.java | /*
* Copyright 2002-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.test.context.support;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import reactor.core.publisher.Mono;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanNotOfRequiredTypeException;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.userdetails.ReactiveUserDetailsService;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.verify;
@ExtendWith(MockitoExtension.class)
public class WithUserDetailsSecurityContextFactoryTests {
@Mock
private ReactiveUserDetailsService reactiveUserDetailsService;
@Mock
private UserDetailsService userDetailsService;
@Mock
private UserDetails userDetails;
@Mock
private BeanFactory beans;
@Mock
private WithUserDetails withUserDetails;
private WithUserDetailsSecurityContextFactory factory;
@BeforeEach
public void setup() {
this.factory = new WithUserDetailsSecurityContextFactory(this.beans);
}
@Test
public void createSecurityContextNullValue() {
assertThatIllegalArgumentException().isThrownBy(() -> this.factory.createSecurityContext(this.withUserDetails));
}
@Test
public void createSecurityContextEmptyValue() {
given(this.withUserDetails.value()).willReturn("");
assertThatIllegalArgumentException().isThrownBy(() -> this.factory.createSecurityContext(this.withUserDetails));
}
@Test
public void createSecurityContextWithExistingUser() {
String username = "user";
given(this.beans.getBean(ReactiveUserDetailsService.class)).willThrow(new NoSuchBeanDefinitionException(""));
given(this.beans.getBean(UserDetailsService.class)).willReturn(this.userDetailsService);
given(this.withUserDetails.value()).willReturn(username);
given(this.userDetailsService.loadUserByUsername(username)).willReturn(this.userDetails);
SecurityContext context = this.factory.createSecurityContext(this.withUserDetails);
assertThat(context.getAuthentication()).isInstanceOf(UsernamePasswordAuthenticationToken.class);
assertThat(context.getAuthentication().getPrincipal()).isEqualTo(this.userDetails);
verify(this.beans).getBean(UserDetailsService.class);
}
// gh-3346
@Test
public void createSecurityContextWithUserDetailsServiceName() {
String beanName = "secondUserDetailsServiceBean";
String username = "user";
given(this.beans.getBean(beanName, ReactiveUserDetailsService.class)).willThrow(
new BeanNotOfRequiredTypeException("", ReactiveUserDetailsService.class, UserDetailsService.class));
given(this.withUserDetails.value()).willReturn(username);
given(this.withUserDetails.userDetailsServiceBeanName()).willReturn(beanName);
given(this.userDetailsService.loadUserByUsername(username)).willReturn(this.userDetails);
given(this.beans.getBean(beanName, UserDetailsService.class)).willReturn(this.userDetailsService);
SecurityContext context = this.factory.createSecurityContext(this.withUserDetails);
assertThat(context.getAuthentication()).isInstanceOf(UsernamePasswordAuthenticationToken.class);
assertThat(context.getAuthentication().getPrincipal()).isEqualTo(this.userDetails);
verify(this.beans).getBean(beanName, UserDetailsService.class);
}
@Test
public void createSecurityContextWithReactiveUserDetailsService() {
String username = "user";
given(this.withUserDetails.value()).willReturn(username);
given(this.beans.getBean(ReactiveUserDetailsService.class)).willReturn(this.reactiveUserDetailsService);
given(this.reactiveUserDetailsService.findByUsername(username)).willReturn(Mono.just(this.userDetails));
SecurityContext context = this.factory.createSecurityContext(this.withUserDetails);
assertThat(context.getAuthentication()).isInstanceOf(UsernamePasswordAuthenticationToken.class);
assertThat(context.getAuthentication().getPrincipal()).isEqualTo(this.userDetails);
verify(this.beans).getBean(ReactiveUserDetailsService.class);
}
@Test
public void createSecurityContextWithReactiveUserDetailsServiceAndBeanName() {
String beanName = "secondUserDetailsServiceBean";
String username = "user";
given(this.withUserDetails.value()).willReturn(username);
given(this.withUserDetails.userDetailsServiceBeanName()).willReturn(beanName);
given(this.beans.getBean(beanName, ReactiveUserDetailsService.class))
.willReturn(this.reactiveUserDetailsService);
given(this.reactiveUserDetailsService.findByUsername(username)).willReturn(Mono.just(this.userDetails));
SecurityContext context = this.factory.createSecurityContext(this.withUserDetails);
assertThat(context.getAuthentication()).isInstanceOf(UsernamePasswordAuthenticationToken.class);
assertThat(context.getAuthentication().getPrincipal()).isEqualTo(this.userDetails);
verify(this.beans).getBean(beanName, ReactiveUserDetailsService.class);
}
}
| 6,055 | 44.19403 | 114 | java |
null | spring-security-main/test/src/test/java/org/springframework/security/test/context/support/WithMockUserSecurityContextFactoryTests.java | /*
* Copyright 2002-2014 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.test.context.support;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.assertj.core.api.Assertions.assertThatIllegalStateException;
import static org.mockito.BDDMockito.given;
@ExtendWith(MockitoExtension.class)
public class WithMockUserSecurityContextFactoryTests {
@Mock
private WithMockUser withUser;
private WithMockUserSecurityContextFactory factory;
@BeforeEach
public void setup() {
this.factory = new WithMockUserSecurityContextFactory();
}
@Test
public void usernameNull() {
assertThatIllegalArgumentException().isThrownBy(() -> this.factory.createSecurityContext(this.withUser));
}
@Test
public void valueDefaultsUsername() {
given(this.withUser.value()).willReturn("valueUser");
given(this.withUser.password()).willReturn("password");
given(this.withUser.roles()).willReturn(new String[] { "USER" });
given(this.withUser.authorities()).willReturn(new String[] {});
assertThat(this.factory.createSecurityContext(this.withUser).getAuthentication().getName())
.isEqualTo(this.withUser.value());
}
@Test
public void usernamePrioritizedOverValue() {
given(this.withUser.username()).willReturn("customUser");
given(this.withUser.password()).willReturn("password");
given(this.withUser.roles()).willReturn(new String[] { "USER" });
given(this.withUser.authorities()).willReturn(new String[] {});
assertThat(this.factory.createSecurityContext(this.withUser).getAuthentication().getName())
.isEqualTo(this.withUser.username());
}
@Test
public void rolesWorks() {
given(this.withUser.value()).willReturn("valueUser");
given(this.withUser.password()).willReturn("password");
given(this.withUser.roles()).willReturn(new String[] { "USER", "CUSTOM" });
given(this.withUser.authorities()).willReturn(new String[] {});
assertThat(this.factory.createSecurityContext(this.withUser).getAuthentication().getAuthorities())
.extracting("authority").containsOnly("ROLE_USER", "ROLE_CUSTOM");
}
@Test
public void authoritiesWorks() {
given(this.withUser.value()).willReturn("valueUser");
given(this.withUser.password()).willReturn("password");
given(this.withUser.roles()).willReturn(new String[] { "USER" });
given(this.withUser.authorities()).willReturn(new String[] { "USER", "CUSTOM" });
assertThat(this.factory.createSecurityContext(this.withUser).getAuthentication().getAuthorities())
.extracting("authority").containsOnly("USER", "CUSTOM");
}
@Test
public void authoritiesAndRolesInvalid() {
given(this.withUser.value()).willReturn("valueUser");
given(this.withUser.roles()).willReturn(new String[] { "CUSTOM" });
given(this.withUser.authorities()).willReturn(new String[] { "USER", "CUSTOM" });
assertThatIllegalStateException().isThrownBy(() -> this.factory.createSecurityContext(this.withUser));
}
@Test
public void rolesWithRolePrefixFails() {
given(this.withUser.value()).willReturn("valueUser");
given(this.withUser.roles()).willReturn(new String[] { "ROLE_FAIL" });
given(this.withUser.authorities()).willReturn(new String[] {});
assertThatIllegalArgumentException().isThrownBy(() -> this.factory.createSecurityContext(this.withUser));
}
}
| 4,131 | 38.352381 | 107 | java |
null | spring-security-main/test/src/test/java/org/springframework/security/test/context/support/ReactorContextTestExecutionListenerTests.java | /*
* Copyright 2002-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.test.context.support;
/**
* @author Rob Winch
* @since 5.0
*/
import java.util.concurrent.ForkJoinPool;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import reactor.core.publisher.Hooks;
import reactor.core.publisher.Mono;
import reactor.test.StepVerifier;
import org.springframework.core.OrderComparator;
import org.springframework.security.authentication.TestingAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.ReactiveSecurityContextHolder;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextImpl;
import org.springframework.security.test.context.TestSecurityContextHolder;
import org.springframework.test.context.TestContext;
import static org.assertj.core.api.Assertions.assertThat;
@ExtendWith(MockitoExtension.class)
public class ReactorContextTestExecutionListenerTests {
@Mock
private TestContext testContext;
private ReactorContextTestExecutionListener listener = new ReactorContextTestExecutionListener();
@AfterEach
public void cleanup() {
TestSecurityContextHolder.clearContext();
Hooks.resetOnLastOperator();
}
@Test
public void beforeTestMethodWhenSecurityContextEmptyThenReactorContextNull() throws Exception {
this.listener.beforeTestMethod(this.testContext);
Mono<?> result = ReactiveSecurityContextHolder.getContext();
StepVerifier.create(result).verifyComplete();
}
@Test
public void beforeTestMethodWhenNullAuthenticationThenReactorContextNull() throws Exception {
TestSecurityContextHolder.setContext(new SecurityContextImpl());
this.listener.beforeTestMethod(this.testContext);
Mono<?> result = ReactiveSecurityContextHolder.getContext();
StepVerifier.create(result).verifyComplete();
}
@Test
public void beforeTestMethodWhenAuthenticationThenReactorContextHasAuthentication() throws Exception {
TestingAuthenticationToken expectedAuthentication = new TestingAuthenticationToken("user", "password",
"ROLE_USER");
TestSecurityContextHolder.setAuthentication(expectedAuthentication);
this.listener.beforeTestMethod(this.testContext);
assertAuthentication(expectedAuthentication);
}
@Test
public void beforeTestMethodWhenCustomContext() throws Exception {
TestingAuthenticationToken expectedAuthentication = new TestingAuthenticationToken("user", "password",
"ROLE_USER");
SecurityContext context = new CustomContext(expectedAuthentication);
TestSecurityContextHolder.setContext(context);
this.listener.beforeTestMethod(this.testContext);
assertSecurityContext(context);
}
@Test
public void beforeTestMethodWhenExistingAuthenticationThenReactorContextHasOriginalAuthentication()
throws Exception {
TestingAuthenticationToken expectedAuthentication = new TestingAuthenticationToken("user", "password",
"ROLE_USER");
TestingAuthenticationToken contextHolder = new TestingAuthenticationToken("contextHolder", "password",
"ROLE_USER");
TestSecurityContextHolder.setAuthentication(contextHolder);
this.listener.beforeTestMethod(this.testContext);
Mono<Authentication> authentication = Mono.just("any")
.flatMap((s) -> ReactiveSecurityContextHolder.getContext().map(SecurityContext::getAuthentication))
.contextWrite(ReactiveSecurityContextHolder.withAuthentication(expectedAuthentication));
StepVerifier.create(authentication).expectNext(expectedAuthentication).verifyComplete();
}
@Test
public void beforeTestMethodWhenClearThenReactorContextDoesNotOverride() throws Exception {
TestingAuthenticationToken expectedAuthentication = new TestingAuthenticationToken("user", "password",
"ROLE_USER");
TestingAuthenticationToken contextHolder = new TestingAuthenticationToken("contextHolder", "password",
"ROLE_USER");
TestSecurityContextHolder.setAuthentication(contextHolder);
this.listener.beforeTestMethod(this.testContext);
Mono<Authentication> authentication = Mono.just("any")
.flatMap((s) -> ReactiveSecurityContextHolder.getContext().map(SecurityContext::getAuthentication))
.contextWrite(ReactiveSecurityContextHolder.clearContext());
StepVerifier.create(authentication).verifyComplete();
}
@Test
public void afterTestMethodWhenSecurityContextEmptyThenNoError() throws Exception {
this.listener.beforeTestMethod(this.testContext);
this.listener.afterTestMethod(this.testContext);
}
@Test
public void afterTestMethodWhenSetupThenReactorContextNull() throws Exception {
beforeTestMethodWhenAuthenticationThenReactorContextHasAuthentication();
this.listener.afterTestMethod(this.testContext);
assertThat(Mono.deferContextual(Mono::just).block().isEmpty()).isTrue();
}
@Test
public void afterTestMethodWhenDifferentHookIsRegistered() throws Exception {
Object obj = new Object();
Hooks.onLastOperator("CUSTOM_HOOK", (p) -> Mono.just(obj));
this.listener.afterTestMethod(this.testContext);
Object result = Mono.deferContextual(Mono::just).block();
assertThat(result).isEqualTo(obj);
}
@Test
public void orderWhenComparedToWithSecurityContextTestExecutionListenerIsAfter() {
OrderComparator comparator = new OrderComparator();
WithSecurityContextTestExecutionListener withSecurity = new WithSecurityContextTestExecutionListener();
ReactorContextTestExecutionListener reactorContext = new ReactorContextTestExecutionListener();
assertThat(comparator.compare(withSecurity, reactorContext)).isLessThan(0);
}
@Test
public void checkSecurityContextResolutionWhenSubscribedContextCalledOnTheDifferentThreadThanWithSecurityContextTestExecutionListener()
throws Exception {
TestingAuthenticationToken contextHolder = new TestingAuthenticationToken("contextHolder", "password",
"ROLE_USER");
TestSecurityContextHolder.setAuthentication(contextHolder);
this.listener.beforeTestMethod(this.testContext);
ForkJoinPool.commonPool().submit(() -> assertAuthentication(contextHolder)).join();
}
public void assertAuthentication(Authentication expected) {
Mono<Authentication> authentication = ReactiveSecurityContextHolder.getContext()
.map(SecurityContext::getAuthentication);
StepVerifier.create(authentication).expectNext(expected).verifyComplete();
}
private void assertSecurityContext(SecurityContext expected) {
Mono<SecurityContext> securityContext = ReactiveSecurityContextHolder.getContext();
StepVerifier.create(securityContext).expectNext(expected).verifyComplete();
}
static class CustomContext implements SecurityContext {
private Authentication authentication;
CustomContext(Authentication authentication) {
this.authentication = authentication;
}
@Override
public Authentication getAuthentication() {
return this.authentication;
}
@Override
public void setAuthentication(Authentication authentication) {
this.authentication = authentication;
}
}
}
| 7,695 | 38.670103 | 136 | java |
null | spring-security-main/test/src/test/java/org/springframework/security/test/context/support/WithSecurityContextTestExcecutionListenerTests.java | /*
* Copyright 2002-2014 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.test.context.support;
import java.lang.annotation.Annotation;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.AnnotationAwareOrderComparator;
import org.springframework.security.authentication.TestingAuthenticationToken;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.test.context.TestSecurityContextHolder;
import org.springframework.test.context.NestedTestConfiguration;
import org.springframework.test.context.TestContext;
import org.springframework.test.context.TestExecutionListener;
import org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener;
import org.springframework.test.context.support.AbstractTestExecutionListener;
import org.springframework.util.ReflectionUtils;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
@ExtendWith(MockitoExtension.class)
public class WithSecurityContextTestExcecutionListenerTests {
private ConfigurableApplicationContext context;
@Mock
private TestContext testContext;
private WithSecurityContextTestExecutionListener listener;
@BeforeEach
public void setup() {
this.listener = new WithSecurityContextTestExecutionListener();
this.context = new AnnotationConfigApplicationContext(Config.class);
}
@AfterEach
public void cleanup() {
TestSecurityContextHolder.clearContext();
if (this.context != null) {
this.context.close();
}
}
@Test
@SuppressWarnings({ "rawtypes", "unchecked" })
public void beforeTestMethodNullSecurityContextNoError() throws Exception {
Class testClass = FakeTest.class;
given(this.testContext.getTestClass()).willReturn(testClass);
given(this.testContext.getTestMethod()).willReturn(ReflectionUtils.findMethod(testClass, "testNoAnnotation"));
this.listener.beforeTestMethod(this.testContext);
}
@Test
@SuppressWarnings({ "rawtypes", "unchecked" })
public void beforeTestMethodNoApplicationContext() throws Exception {
Class testClass = FakeTest.class;
given(this.testContext.getApplicationContext()).willThrow(new IllegalStateException());
given(this.testContext.getTestMethod()).willReturn(ReflectionUtils.findMethod(testClass, "testWithMockUser"));
this.listener.beforeTestMethod(this.testContext);
assertThat(TestSecurityContextHolder.getContext().getAuthentication().getName()).isEqualTo("user");
}
@Test
@SuppressWarnings({ "rawtypes", "unchecked" })
public void beforeTestMethodInnerClass() throws Exception {
Class testClass = OuterClass.InnerClass.class;
Method testNoAnnotation = ReflectionUtils.findMethod(testClass, "testNoAnnotation");
given(this.testContext.getTestClass()).willReturn(testClass);
given(this.testContext.getTestMethod()).willReturn(testNoAnnotation);
given(this.testContext.getApplicationContext()).willThrow(new IllegalStateException(""));
this.listener.beforeTestMethod(this.testContext);
assertThat(TestSecurityContextHolder.getContext().getAuthentication().getName()).isEqualTo("user");
}
@Test
@SuppressWarnings({ "rawtypes", "unchecked" })
public void beforeTestMethodInnerInnerClass() throws Exception {
Class testClass = OuterClass.InnerClass.InnerInnerClass.class;
Method testNoAnnotation = ReflectionUtils.findMethod(testClass, "testNoAnnotation");
given(this.testContext.getTestClass()).willReturn(testClass);
given(this.testContext.getTestMethod()).willReturn(testNoAnnotation);
given(this.testContext.getApplicationContext()).willThrow(new IllegalStateException(""));
this.listener.beforeTestMethod(this.testContext);
assertThat(TestSecurityContextHolder.getContext().getAuthentication().getName()).isEqualTo("user");
}
@Test
@SuppressWarnings({ "rawtypes", "unchecked" })
public void beforeTestMethodInnerClassWhenOverride() throws Exception {
Class testClass = OverrideOuterClass.InnerClass.class;
Method testNoAnnotation = ReflectionUtils.findMethod(testClass, "testNoAnnotation");
given(this.testContext.getTestClass()).willReturn(testClass);
given(this.testContext.getTestMethod()).willReturn(testNoAnnotation);
this.listener.beforeTestMethod(this.testContext);
assertThat(TestSecurityContextHolder.getContext().getAuthentication()).isNull();
}
// gh-3962
@Test
public void withSecurityContextAfterSqlScripts() {
SqlScriptsTestExecutionListener sql = new SqlScriptsTestExecutionListener();
WithSecurityContextTestExecutionListener security = new WithSecurityContextTestExecutionListener();
List<TestExecutionListener> listeners = Arrays.asList(security, sql);
AnnotationAwareOrderComparator.sort(listeners);
assertThat(listeners).containsExactly(sql, security);
}
// SEC-2709
@Test
public void orderOverridden() {
AbstractTestExecutionListener otherListener = new AbstractTestExecutionListener() {
};
List<TestExecutionListener> listeners = new ArrayList<>();
listeners.add(otherListener);
listeners.add(this.listener);
AnnotationAwareOrderComparator.sort(listeners);
assertThat(listeners).containsSequence(this.listener, otherListener);
}
@Test
// gh-3837
public void handlesGenericAnnotation() throws Exception {
Method method = ReflectionUtils.findMethod(WithSecurityContextTestExcecutionListenerTests.class,
"handlesGenericAnnotationTestMethod");
TestContext testContext = mock(TestContext.class);
given(testContext.getTestMethod()).willReturn(method);
given(testContext.getApplicationContext()).willThrow(new IllegalStateException(""));
this.listener.beforeTestMethod(testContext);
assertThat(SecurityContextHolder.getContext().getAuthentication().getPrincipal())
.isInstanceOf(WithSuperClassWithSecurityContext.class);
}
@WithSuperClassWithSecurityContext
public void handlesGenericAnnotationTestMethod() {
}
@Retention(RetentionPolicy.RUNTIME)
@WithSecurityContext(factory = SuperClassWithSecurityContextFactory.class)
@interface WithSuperClassWithSecurityContext {
String username() default "WithSuperClassWithSecurityContext";
}
static class SuperClassWithSecurityContextFactory implements WithSecurityContextFactory<Annotation> {
@Override
public SecurityContext createSecurityContext(Annotation annotation) {
SecurityContext context = SecurityContextHolder.createEmptyContext();
context.setAuthentication(new TestingAuthenticationToken(annotation, "NA"));
return context;
}
}
static class FakeTest {
void testNoAnnotation() {
}
@WithMockUser
void testWithMockUser() {
}
}
@Configuration
static class Config {
}
@WithMockUser
class OuterClass {
class InnerClass {
void testNoAnnotation() {
}
class InnerInnerClass {
void testNoAnnotation() {
}
}
}
}
@WithMockUser
@NestedTestConfiguration(NestedTestConfiguration.EnclosingConfiguration.OVERRIDE)
class OverrideOuterClass {
class InnerClass {
void testNoAnnotation() {
}
class InnerInnerClass {
void testNoAnnotation() {
}
}
}
}
}
| 8,340 | 33.044898 | 112 | java |
null | spring-security-main/test/src/test/java/org/springframework/security/test/context/support/WithMockUserTests.java | /*
* Copyright 2002-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.test.context.support;
import org.junit.jupiter.api.Test;
import org.springframework.core.annotation.AnnotatedElementUtils;
import static org.assertj.core.api.Assertions.assertThat;
public class WithMockUserTests {
@Test
public void defaults() {
WithMockUser mockUser = AnnotatedElementUtils.findMergedAnnotation(Annotated.class, WithMockUser.class);
assertThat(mockUser.value()).isEqualTo("user");
assertThat(mockUser.username()).isEmpty();
assertThat(mockUser.password()).isEqualTo("password");
assertThat(mockUser.roles()).containsOnly("USER");
assertThat(mockUser.setupBefore()).isEqualByComparingTo(TestExecutionEvent.TEST_METHOD);
WithSecurityContext context = AnnotatedElementUtils.findMergedAnnotation(Annotated.class,
WithSecurityContext.class);
assertThat(context.setupBefore()).isEqualTo(TestExecutionEvent.TEST_METHOD);
}
@Test
public void findMergedAnnotationWhenSetupExplicitThenOverridden() {
WithSecurityContext context = AnnotatedElementUtils.findMergedAnnotation(SetupExplicit.class,
WithSecurityContext.class);
assertThat(context.setupBefore()).isEqualTo(TestExecutionEvent.TEST_METHOD);
}
@Test
public void findMergedAnnotationWhenSetupOverriddenThenOverridden() {
WithSecurityContext context = AnnotatedElementUtils.findMergedAnnotation(SetupOverridden.class,
WithSecurityContext.class);
assertThat(context.setupBefore()).isEqualTo(TestExecutionEvent.TEST_EXECUTION);
}
@WithMockUser
private class Annotated {
}
@WithMockUser(setupBefore = TestExecutionEvent.TEST_METHOD)
private class SetupExplicit {
}
@WithMockUser(setupBefore = TestExecutionEvent.TEST_EXECUTION)
private class SetupOverridden {
}
}
| 2,351 | 32.6 | 106 | java |
null | spring-security-main/test/src/test/java/org/springframework/security/test/context/support/WithUserDetailsTests.java | /*
* Copyright 2002-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.test.context.support;
import org.junit.jupiter.api.Test;
import org.springframework.core.annotation.AnnotatedElementUtils;
import org.springframework.core.annotation.AnnotationUtils;
import static org.assertj.core.api.Assertions.assertThat;
public class WithUserDetailsTests {
@Test
public void defaults() {
WithUserDetails userDetails = AnnotationUtils.findAnnotation(Annotated.class, WithUserDetails.class);
assertThat(userDetails.value()).isEqualTo("user");
WithSecurityContext context = AnnotatedElementUtils.findMergedAnnotation(Annotated.class,
WithSecurityContext.class);
assertThat(context.setupBefore()).isEqualTo(TestExecutionEvent.TEST_METHOD);
}
@Test
public void findMergedAnnotationWhenSetupExplicitThenOverridden() {
WithSecurityContext context = AnnotatedElementUtils.findMergedAnnotation(SetupExplicit.class,
WithSecurityContext.class);
assertThat(context.setupBefore()).isEqualTo(TestExecutionEvent.TEST_METHOD);
}
@Test
public void findMergedAnnotationWhenSetupOverriddenThenOverridden() {
WithSecurityContext context = AnnotatedElementUtils.findMergedAnnotation(SetupOverridden.class,
WithSecurityContext.class);
assertThat(context.setupBefore()).isEqualTo(TestExecutionEvent.TEST_EXECUTION);
}
@WithUserDetails
private static class Annotated {
}
@WithUserDetails(setupBefore = TestExecutionEvent.TEST_METHOD)
private class SetupExplicit {
}
@WithUserDetails(setupBefore = TestExecutionEvent.TEST_EXECUTION)
private class SetupOverridden {
}
}
| 2,184 | 31.61194 | 103 | java |
null | spring-security-main/test/src/test/java/org/springframework/security/test/context/support/WithAnonymousUserTests.java | /*
* Copyright 2002-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.test.context.support;
import org.junit.jupiter.api.Test;
import org.springframework.core.annotation.AnnotatedElementUtils;
import static org.assertj.core.api.Assertions.assertThat;
/**
* @author Rob Winch
* @since 5.0
*/
public class WithAnonymousUserTests {
@Test
public void defaults() {
WithSecurityContext context = AnnotatedElementUtils.findMergedAnnotation(Annotated.class,
WithSecurityContext.class);
assertThat(context.setupBefore()).isEqualTo(TestExecutionEvent.TEST_METHOD);
}
@Test
public void findMergedAnnotationWhenSetupExplicitThenOverridden() {
WithSecurityContext context = AnnotatedElementUtils.findMergedAnnotation(SetupExplicit.class,
WithSecurityContext.class);
assertThat(context.setupBefore()).isEqualTo(TestExecutionEvent.TEST_METHOD);
}
@Test
public void findMergedAnnotationWhenSetupOverriddenThenOverridden() {
WithSecurityContext context = AnnotatedElementUtils.findMergedAnnotation(SetupOverridden.class,
WithSecurityContext.class);
assertThat(context.setupBefore()).isEqualTo(TestExecutionEvent.TEST_EXECUTION);
}
@WithAnonymousUser
private class Annotated {
}
@WithAnonymousUser(setupBefore = TestExecutionEvent.TEST_METHOD)
private class SetupExplicit {
}
@WithAnonymousUser(setupBefore = TestExecutionEvent.TEST_EXECUTION)
private class SetupOverridden {
}
}
| 2,011 | 28.588235 | 97 | java |
null | spring-security-main/test/src/test/java/org/springframework/security/test/context/annotation/SecurityTestExecutionListenerTests.java | /*
* Copyright 2002-2015 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.test.context.annotation;
import java.security.Principal;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import reactor.core.publisher.Mono;
import reactor.test.StepVerifier;
import org.springframework.security.core.context.ReactiveSecurityContextHolder;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.test.context.support.WithMockUser;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import static org.assertj.core.api.Assertions.assertThat;
@ExtendWith(SpringExtension.class)
@SecurityTestExecutionListeners
public class SecurityTestExecutionListenerTests {
@WithMockUser
@Test
public void withSecurityContextTestExecutionListenerIsRegistered() {
assertThat(SecurityContextHolder.getContext().getAuthentication().getName()).isEqualTo("user");
}
@WithMockUser
@Test
public void reactorContextTestSecurityContextHolderExecutionListenerTestIsRegistered() {
Mono<String> name = ReactiveSecurityContextHolder.getContext().map(SecurityContext::getAuthentication)
.map(Principal::getName);
StepVerifier.create(name).expectNext("user").verifyComplete();
}
}
| 1,926 | 35.358491 | 104 | java |
null | spring-security-main/test/src/test/java/org/springframework/security/test/aot/hint/WithSecurityContextTestRuntimeHintsTests.java | /*
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.test.aot.hint;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.aot.hint.MemberCategory;
import org.springframework.aot.hint.RuntimeHints;
import org.springframework.aot.hint.TypeReference;
import org.springframework.aot.hint.predicate.RuntimeHintsPredicates;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.test.context.showcase.WithMockCustomUser;
import org.springframework.security.test.context.showcase.WithMockCustomUserSecurityContextFactory;
import org.springframework.security.test.context.support.WithAnonymousUser;
import org.springframework.security.test.context.support.WithMockUser;
import org.springframework.security.test.context.support.WithSecurityContext;
import org.springframework.security.test.context.support.WithSecurityContextFactory;
import org.springframework.security.test.context.support.WithUserDetails;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Tests for {@link WithSecurityContextTestRuntimeHints}.
*/
@WithMockCustomUser
class WithSecurityContextTestRuntimeHintsTests {
private final RuntimeHints hints = new RuntimeHints();
private final WithSecurityContextTestRuntimeHints registrar = new WithSecurityContextTestRuntimeHints();
@BeforeEach
void setup() {
this.registrar.registerHints(this.hints, WithSecurityContextTestRuntimeHintsTests.class,
WithSecurityContextTestRuntimeHintsTests.class.getClassLoader());
}
@Test
@WithMockUser
void withMockUserHasHints() {
assertThat(RuntimeHintsPredicates.reflection()
.onType(TypeReference
.of("org.springframework.security.test.context.support.WithMockUserSecurityContextFactory"))
.withMemberCategory(MemberCategory.INVOKE_DECLARED_CONSTRUCTORS)).accepts(this.hints);
}
@Test
@WithAnonymousUser
void withAnonymousUserHasHints() {
assertThat(RuntimeHintsPredicates.reflection()
.onType(TypeReference.of(
"org.springframework.security.test.context.support.WithAnonymousUserSecurityContextFactory"))
.withMemberCategory(MemberCategory.INVOKE_DECLARED_CONSTRUCTORS)).accepts(this.hints);
}
@Test
@WithUserDetails
void withUserDetailsHasHints() {
assertThat(RuntimeHintsPredicates.reflection()
.onType(TypeReference
.of("org.springframework.security.test.context.support.WithUserDetailsSecurityContextFactory"))
.withMemberCategory(MemberCategory.INVOKE_DECLARED_CONSTRUCTORS)).accepts(this.hints);
}
@Test
@WithMockTestUser
void withMockTestUserHasHints() {
assertThat(RuntimeHintsPredicates.reflection().onType(WithMockTestUserSecurityContextFactory.class)
.withMemberCategory(MemberCategory.INVOKE_DECLARED_CONSTRUCTORS)).accepts(this.hints);
}
@Test
void withMockCustomUserOnClassHasHints() {
assertThat(RuntimeHintsPredicates.reflection().onType(WithMockCustomUserSecurityContextFactory.class)
.withMemberCategory(MemberCategory.INVOKE_DECLARED_CONSTRUCTORS)).accepts(this.hints);
}
@Retention(RetentionPolicy.RUNTIME)
@WithSecurityContext(factory = WithMockTestUserSecurityContextFactory.class)
@interface WithMockTestUser {
}
static class WithMockTestUserSecurityContextFactory implements WithSecurityContextFactory<WithMockTestUser> {
@Override
public SecurityContext createSecurityContext(WithMockTestUser annotation) {
return SecurityContextHolder.createEmptyContext();
}
}
}
| 4,231 | 36.451327 | 110 | java |
null | spring-security-main/test/src/test/java/org/springframework/security/test/aot/hint/WebTestUtilsTestRuntimeHintsTests.java | /*
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.test.aot.hint;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.aot.hint.MemberCategory;
import org.springframework.aot.hint.RuntimeHints;
import org.springframework.aot.hint.predicate.RuntimeHintsPredicates;
import org.springframework.core.io.support.SpringFactoriesLoader;
import org.springframework.security.web.FilterChainProxy;
import org.springframework.security.web.context.SecurityContextHolderFilter;
import org.springframework.security.web.context.SecurityContextPersistenceFilter;
import org.springframework.security.web.csrf.CsrfFilter;
import org.springframework.test.context.aot.TestRuntimeHintsRegistrar;
import org.springframework.util.ClassUtils;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Tests for {@link WebTestUtilsTestRuntimeHints}.
*
* @author Marcus da Coregio
*/
class WebTestUtilsTestRuntimeHintsTests {
private final RuntimeHints hints = new RuntimeHints();
@BeforeEach
void setup() {
SpringFactoriesLoader.forResourceLocation("META-INF/spring/aot.factories").load(TestRuntimeHintsRegistrar.class)
.forEach((registrar) -> registrar.registerHints(this.hints, WebTestUtilsTestRuntimeHintsTests.class,
ClassUtils.getDefaultClassLoader()));
}
@Test
void filterChainProxyHasHints() {
assertThat(RuntimeHintsPredicates.reflection().onType(FilterChainProxy.class)
.withMemberCategories(MemberCategory.INVOKE_DECLARED_METHODS)).accepts(this.hints);
}
@Test
void csrfFilterHasHints() {
assertThat(RuntimeHintsPredicates.reflection().onType(CsrfFilter.class)
.withMemberCategories(MemberCategory.DECLARED_FIELDS)).accepts(this.hints);
}
@Test
void securityContextPersistenceFilterHasHints() {
assertThat(RuntimeHintsPredicates.reflection().onType(SecurityContextPersistenceFilter.class)
.withMemberCategories(MemberCategory.DECLARED_FIELDS)).accepts(this.hints);
}
@Test
void securityContextHolderFilterHasHints() {
assertThat(RuntimeHintsPredicates.reflection().onType(SecurityContextHolderFilter.class)
.withMemberCategories(MemberCategory.DECLARED_FIELDS)).accepts(this.hints);
}
}
| 2,804 | 35.907895 | 114 | java |
null | spring-security-main/test/src/main/java/org/springframework/security/test/web/reactive/server/SecurityMockServerConfigurers.java | /*
* Copyright 2002-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.test.web.reactive.server;
import java.time.Instant;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Consumer;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import reactor.core.publisher.Mono;
import org.springframework.context.ApplicationContext;
import org.springframework.core.convert.converter.Converter;
import org.springframework.http.client.reactive.ClientHttpConnector;
import org.springframework.lang.Nullable;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.ReactiveSecurityContextHolder;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextImpl;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.oauth2.client.OAuth2AuthorizeRequest;
import org.springframework.security.oauth2.client.OAuth2AuthorizedClient;
import org.springframework.security.oauth2.client.ReactiveOAuth2AuthorizedClientManager;
import org.springframework.security.oauth2.client.authentication.OAuth2AuthenticationToken;
import org.springframework.security.oauth2.client.registration.ClientRegistration;
import org.springframework.security.oauth2.client.web.DefaultReactiveOAuth2AuthorizedClientManager;
import org.springframework.security.oauth2.client.web.OAuth2AuthorizedClientRepository;
import org.springframework.security.oauth2.client.web.reactive.result.method.annotation.OAuth2AuthorizedClientArgumentResolver;
import org.springframework.security.oauth2.client.web.server.ServerOAuth2AuthorizedClientRepository;
import org.springframework.security.oauth2.client.web.server.WebSessionServerOAuth2AuthorizedClientRepository;
import org.springframework.security.oauth2.core.AuthorizationGrantType;
import org.springframework.security.oauth2.core.OAuth2AccessToken;
import org.springframework.security.oauth2.core.OAuth2AuthenticatedPrincipal;
import org.springframework.security.oauth2.core.OAuth2TokenIntrospectionClaimNames;
import org.springframework.security.oauth2.core.oidc.IdTokenClaimNames;
import org.springframework.security.oauth2.core.oidc.OidcIdToken;
import org.springframework.security.oauth2.core.oidc.OidcUserInfo;
import org.springframework.security.oauth2.core.oidc.user.DefaultOidcUser;
import org.springframework.security.oauth2.core.oidc.user.OidcUser;
import org.springframework.security.oauth2.core.oidc.user.OidcUserAuthority;
import org.springframework.security.oauth2.core.user.DefaultOAuth2User;
import org.springframework.security.oauth2.core.user.OAuth2User;
import org.springframework.security.oauth2.core.user.OAuth2UserAuthority;
import org.springframework.security.oauth2.jwt.Jwt;
import org.springframework.security.oauth2.jwt.JwtClaimNames;
import org.springframework.security.oauth2.server.resource.authentication.BearerTokenAuthentication;
import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationToken;
import org.springframework.security.oauth2.server.resource.authentication.JwtGrantedAuthoritiesConverter;
import org.springframework.security.oauth2.server.resource.introspection.OAuth2IntrospectionAuthenticatedPrincipal;
import org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors;
import org.springframework.security.web.server.csrf.CsrfWebFilter;
import org.springframework.security.web.server.util.matcher.ServerWebExchangeMatcher;
import org.springframework.test.util.ReflectionTestUtils;
import org.springframework.test.web.reactive.server.MockServerConfigurer;
import org.springframework.test.web.reactive.server.WebTestClient;
import org.springframework.test.web.reactive.server.WebTestClientConfigurer;
import org.springframework.util.Assert;
import org.springframework.util.ClassUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.reactive.result.method.HandlerMethodArgumentResolver;
import org.springframework.web.reactive.result.method.annotation.ArgumentResolverConfigurer;
import org.springframework.web.reactive.result.method.annotation.RequestMappingHandlerAdapter;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebFilter;
import org.springframework.web.server.WebFilterChain;
import org.springframework.web.server.adapter.WebHttpHandlerBuilder;
/**
* Test utilities for working with Spring Security and
* {@link org.springframework.test.web.reactive.server.WebTestClient.Builder#apply(WebTestClientConfigurer)}.
*
* @author Rob Winch
* @since 5.0
*/
public final class SecurityMockServerConfigurers {
private SecurityMockServerConfigurers() {
}
/**
* Sets up Spring Security's {@link WebTestClient} test support
* @return the MockServerConfigurer to use
*/
public static MockServerConfigurer springSecurity() {
return new MockServerConfigurer() {
@Override
public void beforeServerCreated(WebHttpHandlerBuilder builder) {
builder.filters((filters) -> filters.add(0, new MutatorFilter()));
}
};
}
/**
* Updates the ServerWebExchange to use the provided Authentication as the Principal
* @param authentication the Authentication to use.
* @return the configurer to use
*/
public static <T extends WebTestClientConfigurer & MockServerConfigurer> T mockAuthentication(
Authentication authentication) {
return (T) new MutatorWebTestClientConfigurer(() -> Mono.just(authentication).map(SecurityContextImpl::new));
}
/**
* Updates the ServerWebExchange to use the provided UserDetails to create a
* UsernamePasswordAuthenticationToken as the Principal
* @param userDetails the UserDetails to use.
* @return the configurer to use
*/
public static <T extends WebTestClientConfigurer & MockServerConfigurer> T mockUser(UserDetails userDetails) {
return mockAuthentication(UsernamePasswordAuthenticationToken.authenticated(userDetails,
userDetails.getPassword(), userDetails.getAuthorities()));
}
/**
* Updates the ServerWebExchange to use a UserDetails to create a
* UsernamePasswordAuthenticationToken as the Principal. This uses a default username
* of "user", password of "password", and granted authorities of "ROLE_USER".
* @return the {@link UserExchangeMutator} to use
*/
public static UserExchangeMutator mockUser() {
return mockUser("user");
}
/**
* Updates the ServerWebExchange to use a UserDetails to create a
* UsernamePasswordAuthenticationToken as the Principal. This uses a default password
* of "password" and granted authorities of "ROLE_USER".
* @return the {@link WebTestClientConfigurer} to use
*/
public static UserExchangeMutator mockUser(String username) {
return new UserExchangeMutator(username);
}
/**
* Updates the ServerWebExchange to establish a {@link SecurityContext} that has a
* {@link JwtAuthenticationToken} for the {@link Authentication} and a {@link Jwt} for
* the {@link Authentication#getPrincipal()}. All details are declarative and do not
* require the JWT to be valid.
* @return the {@link JwtMutator} to further configure or use
* @since 5.2
*/
public static JwtMutator mockJwt() {
return new JwtMutator();
}
/**
* Updates the ServerWebExchange to establish a {@link SecurityContext} that has a
* {@link BearerTokenAuthentication} for the {@link Authentication} and an
* {@link OAuth2AuthenticatedPrincipal} for the {@link Authentication#getPrincipal()}.
* All details are declarative and do not require the token to be valid.
* @return the {@link OpaqueTokenMutator} to further configure or use
* @since 5.3
*/
public static OpaqueTokenMutator mockOpaqueToken() {
return new OpaqueTokenMutator();
}
/**
* Updates the ServerWebExchange to establish a {@link SecurityContext} that has a
* {@link OAuth2AuthenticationToken} for the {@link Authentication}. All details are
* declarative and do not require the corresponding OAuth 2.0 tokens to be valid.
* @return the {@link OAuth2LoginMutator} to further configure or use
* @since 5.3
*/
public static OAuth2LoginMutator mockOAuth2Login() {
OAuth2AccessToken accessToken = new OAuth2AccessToken(OAuth2AccessToken.TokenType.BEARER, "access-token", null,
null, Collections.singleton("read"));
return new OAuth2LoginMutator(accessToken);
}
/**
* Updates the ServerWebExchange to establish a {@link SecurityContext} that has a
* {@link OAuth2AuthenticationToken} for the {@link Authentication}. All details are
* declarative and do not require the corresponding OAuth 2.0 tokens to be valid.
* @return the {@link OidcLoginMutator} to further configure or use
* @since 5.3
*/
public static OidcLoginMutator mockOidcLogin() {
OAuth2AccessToken accessToken = new OAuth2AccessToken(OAuth2AccessToken.TokenType.BEARER, "access-token", null,
null, Collections.singleton("read"));
return new OidcLoginMutator(accessToken);
}
/**
* Updates the ServerWebExchange to establish a {@link OAuth2AuthorizedClient} in the
* session. All details are declarative and do not require the corresponding OAuth 2.0
* tokens to be valid.
*
* <p>
* The support works by associating the authorized client to the ServerWebExchange
* using a {@link ServerOAuth2AuthorizedClientRepository}
* </p>
* @return the {@link OAuth2ClientMutator} to further configure or use
* @since 5.3
*/
public static OAuth2ClientMutator mockOAuth2Client() {
return new OAuth2ClientMutator();
}
/**
* Updates the ServerWebExchange to establish a {@link OAuth2AuthorizedClient} in the
* session. All details are declarative and do not require the corresponding OAuth 2.0
* tokens to be valid.
*
* <p>
* The support works by associating the authorized client to the ServerWebExchange
* using a {@link ServerOAuth2AuthorizedClientRepository}
* </p>
* @param registrationId The registration id associated with the
* {@link OAuth2AuthorizedClient}
* @return the {@link OAuth2ClientMutator} to further configure or use
* @since 5.3
*/
public static OAuth2ClientMutator mockOAuth2Client(String registrationId) {
return new OAuth2ClientMutator(registrationId);
}
public static CsrfMutator csrf() {
return new CsrfMutator();
}
public static final class CsrfMutator implements WebTestClientConfigurer, MockServerConfigurer {
private CsrfMutator() {
}
@Override
public void afterConfigurerAdded(WebTestClient.Builder builder,
@Nullable WebHttpHandlerBuilder httpHandlerBuilder, @Nullable ClientHttpConnector connector) {
CsrfWebFilter filter = new CsrfWebFilter();
filter.setRequireCsrfProtectionMatcher((e) -> ServerWebExchangeMatcher.MatchResult.notMatch());
httpHandlerBuilder.filters((filters) -> filters.add(0, filter));
}
@Override
public void afterConfigureAdded(WebTestClient.MockServerSpec<?> serverSpec) {
}
@Override
public void beforeServerCreated(WebHttpHandlerBuilder builder) {
}
}
/**
* Updates the WebServerExchange using {@code {@link
* SecurityMockServerConfigurers#mockUser(UserDetails)}}. Defaults to use a password
* of "password" and granted authorities of "ROLE_USER".
*/
public static final class UserExchangeMutator implements WebTestClientConfigurer, MockServerConfigurer {
private final User.UserBuilder userBuilder;
private UserExchangeMutator(String username) {
this.userBuilder = User.withUsername(username);
password("password");
roles("USER");
}
/**
* Specifies the password to use. Default is "password".
* @param password the password to use
* @return the UserExchangeMutator
*/
public UserExchangeMutator password(String password) {
this.userBuilder.password(password);
return this;
}
/**
* Specifies the roles to use. Default is "USER". This is similar to authorities
* except each role is automatically prefixed with "ROLE_USER".
* @param roles the roles to use.
* @return the UserExchangeMutator
*/
public UserExchangeMutator roles(String... roles) {
this.userBuilder.roles(roles);
return this;
}
/**
* Specifies the {@code GrantedAuthority}s to use. Default is "ROLE_USER".
* @param authorities the authorities to use.
* @return the UserExchangeMutator
*/
public UserExchangeMutator authorities(GrantedAuthority... authorities) {
this.userBuilder.authorities(authorities);
return this;
}
/**
* Specifies the {@code GrantedAuthority}s to use. Default is "ROLE_USER".
* @param authorities the authorities to use.
* @return the UserExchangeMutator
*/
public UserExchangeMutator authorities(Collection<? extends GrantedAuthority> authorities) {
this.userBuilder.authorities(authorities);
return this;
}
/**
* Specifies the {@code GrantedAuthority}s to use. Default is "ROLE_USER".
* @param authorities the authorities to use.
* @return the UserExchangeMutator
*/
public UserExchangeMutator authorities(String... authorities) {
this.userBuilder.authorities(authorities);
return this;
}
public UserExchangeMutator accountExpired(boolean accountExpired) {
this.userBuilder.accountExpired(accountExpired);
return this;
}
public UserExchangeMutator accountLocked(boolean accountLocked) {
this.userBuilder.accountLocked(accountLocked);
return this;
}
public UserExchangeMutator credentialsExpired(boolean credentialsExpired) {
this.userBuilder.credentialsExpired(credentialsExpired);
return this;
}
public UserExchangeMutator disabled(boolean disabled) {
this.userBuilder.disabled(disabled);
return this;
}
@Override
public void beforeServerCreated(WebHttpHandlerBuilder builder) {
configurer().beforeServerCreated(builder);
}
@Override
public void afterConfigureAdded(WebTestClient.MockServerSpec<?> serverSpec) {
configurer().afterConfigureAdded(serverSpec);
}
@Override
public void afterConfigurerAdded(WebTestClient.Builder builder,
@Nullable WebHttpHandlerBuilder webHttpHandlerBuilder,
@Nullable ClientHttpConnector clientHttpConnector) {
configurer().afterConfigurerAdded(builder, webHttpHandlerBuilder, clientHttpConnector);
}
private <T extends WebTestClientConfigurer & MockServerConfigurer> T configurer() {
return mockUser(this.userBuilder.build());
}
}
private static final class MutatorWebTestClientConfigurer implements WebTestClientConfigurer, MockServerConfigurer {
private final Supplier<Mono<SecurityContext>> context;
private MutatorWebTestClientConfigurer(Supplier<Mono<SecurityContext>> context) {
this.context = context;
}
@Override
public void beforeServerCreated(WebHttpHandlerBuilder builder) {
builder.filters(addSetupMutatorFilter());
}
@Override
public void afterConfigurerAdded(WebTestClient.Builder builder,
@Nullable WebHttpHandlerBuilder webHttpHandlerBuilder,
@Nullable ClientHttpConnector clientHttpConnector) {
webHttpHandlerBuilder.filters(addSetupMutatorFilter());
}
private Consumer<List<WebFilter>> addSetupMutatorFilter() {
return (filters) -> filters.add(0, new SetupMutatorFilter(this.context));
}
}
private static final class SetupMutatorFilter implements WebFilter {
private final Supplier<Mono<SecurityContext>> context;
private SetupMutatorFilter(Supplier<Mono<SecurityContext>> context) {
this.context = context;
}
@Override
public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain webFilterChain) {
exchange.getAttributes().computeIfAbsent(MutatorFilter.ATTRIBUTE_NAME, (key) -> this.context);
return webFilterChain.filter(exchange);
}
}
private static class MutatorFilter implements WebFilter {
public static final String ATTRIBUTE_NAME = "context";
@Override
public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain webFilterChain) {
Supplier<Mono<SecurityContext>> context = exchange.getAttribute(ATTRIBUTE_NAME);
if (context != null) {
exchange.getAttributes().remove(ATTRIBUTE_NAME);
return webFilterChain.filter(exchange)
.contextWrite(ReactiveSecurityContextHolder.withSecurityContext(context.get()));
}
return webFilterChain.filter(exchange);
}
}
/**
* Updates the WebServerExchange using {@code {@link
* SecurityMockServerConfigurers#mockAuthentication(Authentication)}}.
*
* @author Jérôme Wacongne <ch4mp@c4-soft.com>
* @author Josh Cummings
* @since 5.2
*/
public static final class JwtMutator implements WebTestClientConfigurer, MockServerConfigurer {
private Jwt jwt;
private Converter<Jwt, Collection<GrantedAuthority>> authoritiesConverter = new JwtGrantedAuthoritiesConverter();
private JwtMutator() {
jwt((jwt) -> {
});
}
/**
* Use the given {@link Jwt.Builder} {@link Consumer} to configure the underlying
* {@link Jwt}
*
* This method first creates a default {@link Jwt.Builder} instance with default
* values for the {@code alg}, {@code sub}, and {@code scope} claims. The
* {@link Consumer} can then modify these or provide additional configuration.
*
* Calling {@link SecurityMockServerConfigurers#mockJwt()} is the equivalent of
* calling {@code SecurityMockMvcRequestPostProcessors.mockJwt().jwt(() -> {})}.
* @param jwtBuilderConsumer For configuring the underlying {@link Jwt}
* @return the {@link JwtMutator} for further configuration
*/
public JwtMutator jwt(Consumer<Jwt.Builder> jwtBuilderConsumer) {
Jwt.Builder jwtBuilder = Jwt.withTokenValue("token").header("alg", "none").claim(JwtClaimNames.SUB, "user")
.claim("scope", "read");
jwtBuilderConsumer.accept(jwtBuilder);
this.jwt = jwtBuilder.build();
return this;
}
/**
* Use the given {@link Jwt}
* @param jwt The {@link Jwt} to use
* @return the {@link JwtMutator} for further configuration
*/
public JwtMutator jwt(Jwt jwt) {
this.jwt = jwt;
return this;
}
/**
* Use the provided authorities in the token
* @param authorities the authorities to use
* @return the {@link JwtMutator} for further configuration
*/
public JwtMutator authorities(Collection<GrantedAuthority> authorities) {
Assert.notNull(authorities, "authorities cannot be null");
this.authoritiesConverter = (jwt) -> authorities;
return this;
}
/**
* Use the provided authorities in the token
* @param authorities the authorities to use
* @return the {@link JwtMutator} for further configuration
*/
public JwtMutator authorities(GrantedAuthority... authorities) {
Assert.notNull(authorities, "authorities cannot be null");
this.authoritiesConverter = (jwt) -> Arrays.asList(authorities);
return this;
}
/**
* Provides the configured {@link Jwt} so that custom authorities can be derived
* from it
* @param authoritiesConverter the conversion strategy from {@link Jwt} to a
* {@link Collection} of {@link GrantedAuthority}s
* @return the {@link JwtMutator} for further configuration
*/
public JwtMutator authorities(Converter<Jwt, Collection<GrantedAuthority>> authoritiesConverter) {
Assert.notNull(authoritiesConverter, "authoritiesConverter cannot be null");
this.authoritiesConverter = authoritiesConverter;
return this;
}
@Override
public void beforeServerCreated(WebHttpHandlerBuilder builder) {
configurer().beforeServerCreated(builder);
}
@Override
public void afterConfigureAdded(WebTestClient.MockServerSpec<?> serverSpec) {
configurer().afterConfigureAdded(serverSpec);
}
@Override
public void afterConfigurerAdded(WebTestClient.Builder builder,
@Nullable WebHttpHandlerBuilder httpHandlerBuilder, @Nullable ClientHttpConnector connector) {
httpHandlerBuilder.filter((exchange, chain) -> {
CsrfWebFilter.skipExchange(exchange);
return chain.filter(exchange);
});
configurer().afterConfigurerAdded(builder, httpHandlerBuilder, connector);
}
private <T extends WebTestClientConfigurer & MockServerConfigurer> T configurer() {
return mockAuthentication(
new JwtAuthenticationToken(this.jwt, this.authoritiesConverter.convert(this.jwt)));
}
}
/**
* @author Josh Cummings
* @since 5.3
*/
public static final class OpaqueTokenMutator implements WebTestClientConfigurer, MockServerConfigurer {
private Supplier<Map<String, Object>> attributes = this::defaultAttributes;
private Supplier<Collection<GrantedAuthority>> authorities = this::defaultAuthorities;
private Supplier<OAuth2AuthenticatedPrincipal> principal = this::defaultPrincipal;
private OpaqueTokenMutator() {
}
/**
* Mutate the attributes using the given {@link Consumer}
* @param attributesConsumer The {@link Consumer} for mutating the {@Map} of
* attributes
* @return the {@link OpaqueTokenMutator} for further configuration
*/
public OpaqueTokenMutator attributes(Consumer<Map<String, Object>> attributesConsumer) {
Assert.notNull(attributesConsumer, "attributesConsumer cannot be null");
this.attributes = () -> {
Map<String, Object> attributes = defaultAttributes();
attributesConsumer.accept(attributes);
return attributes;
};
this.principal = this::defaultPrincipal;
return this;
}
/**
* Use the provided authorities in the resulting principal
* @param authorities the authorities to use
* @return the {@link OpaqueTokenMutator} for further configuration
*/
public OpaqueTokenMutator authorities(Collection<GrantedAuthority> authorities) {
Assert.notNull(authorities, "authorities cannot be null");
this.authorities = () -> authorities;
this.principal = this::defaultPrincipal;
return this;
}
/**
* Use the provided authorities in the resulting principal
* @param authorities the authorities to use
* @return the {@link OpaqueTokenMutator} for further configuration
*/
public OpaqueTokenMutator authorities(GrantedAuthority... authorities) {
Assert.notNull(authorities, "authorities cannot be null");
this.authorities = () -> Arrays.asList(authorities);
this.principal = this::defaultPrincipal;
return this;
}
/**
* Use the provided principal
* @param principal the principal to use
* @return the {@link OpaqueTokenMutator} for further configuration
*/
public OpaqueTokenMutator principal(OAuth2AuthenticatedPrincipal principal) {
Assert.notNull(principal, "principal cannot be null");
this.principal = () -> principal;
return this;
}
@Override
public void beforeServerCreated(WebHttpHandlerBuilder builder) {
configurer().beforeServerCreated(builder);
}
@Override
public void afterConfigureAdded(WebTestClient.MockServerSpec<?> serverSpec) {
configurer().afterConfigureAdded(serverSpec);
}
@Override
public void afterConfigurerAdded(WebTestClient.Builder builder,
@Nullable WebHttpHandlerBuilder httpHandlerBuilder, @Nullable ClientHttpConnector connector) {
httpHandlerBuilder.filter((exchange, chain) -> {
CsrfWebFilter.skipExchange(exchange);
return chain.filter(exchange);
});
configurer().afterConfigurerAdded(builder, httpHandlerBuilder, connector);
}
private <T extends WebTestClientConfigurer & MockServerConfigurer> T configurer() {
OAuth2AuthenticatedPrincipal principal = this.principal.get();
OAuth2AccessToken accessToken = getOAuth2AccessToken(principal);
BearerTokenAuthentication token = new BearerTokenAuthentication(principal, accessToken,
principal.getAuthorities());
return mockAuthentication(token);
}
private Map<String, Object> defaultAttributes() {
Map<String, Object> attributes = new HashMap<>();
attributes.put(OAuth2TokenIntrospectionClaimNames.SUB, "user");
attributes.put(OAuth2TokenIntrospectionClaimNames.SCOPE, "read");
return attributes;
}
private Collection<GrantedAuthority> defaultAuthorities() {
Map<String, Object> attributes = this.attributes.get();
Object scope = attributes.get(OAuth2TokenIntrospectionClaimNames.SCOPE);
if (scope == null) {
return Collections.emptyList();
}
if (scope instanceof Collection) {
return getAuthorities((Collection) scope);
}
String scopes = scope.toString();
if (!StringUtils.hasText(scopes)) {
return Collections.emptyList();
}
return getAuthorities(Arrays.asList(scopes.split(" ")));
}
private OAuth2AuthenticatedPrincipal defaultPrincipal() {
return new OAuth2IntrospectionAuthenticatedPrincipal(this.attributes.get(), this.authorities.get());
}
private Collection<GrantedAuthority> getAuthorities(Collection<?> scopes) {
return scopes.stream().map((scope) -> new SimpleGrantedAuthority("SCOPE_" + scope))
.collect(Collectors.toList());
}
private OAuth2AccessToken getOAuth2AccessToken(OAuth2AuthenticatedPrincipal principal) {
Instant expiresAt = getInstant(principal.getAttributes(), "exp");
Instant issuedAt = getInstant(principal.getAttributes(), "iat");
return new OAuth2AccessToken(OAuth2AccessToken.TokenType.BEARER, "token", issuedAt, expiresAt);
}
private Instant getInstant(Map<String, Object> attributes, String name) {
Object value = attributes.get(name);
if (value == null) {
return null;
}
if (value instanceof Instant) {
return (Instant) value;
}
throw new IllegalArgumentException(name + " attribute must be of type Instant");
}
}
/**
* @author Josh Cummings
* @since 5.3
*/
public static final class OAuth2LoginMutator implements WebTestClientConfigurer, MockServerConfigurer {
private final String nameAttributeKey = "sub";
private ClientRegistration clientRegistration;
private OAuth2AccessToken accessToken;
private Supplier<Collection<GrantedAuthority>> authorities = this::defaultAuthorities;
private Supplier<Map<String, Object>> attributes = this::defaultAttributes;
private Supplier<OAuth2User> oauth2User = this::defaultPrincipal;
private OAuth2LoginMutator(OAuth2AccessToken accessToken) {
this.accessToken = accessToken;
this.clientRegistration = clientRegistrationBuilder().build();
}
/**
* Use the provided authorities in the {@link Authentication}
* @param authorities the authorities to use
* @return the {@link OAuth2LoginMutator} for further configuration
*/
public OAuth2LoginMutator authorities(Collection<GrantedAuthority> authorities) {
Assert.notNull(authorities, "authorities cannot be null");
this.authorities = () -> authorities;
this.oauth2User = this::defaultPrincipal;
return this;
}
/**
* Use the provided authorities in the {@link Authentication}
* @param authorities the authorities to use
* @return the {@link OAuth2LoginMutator} for further configuration
*/
public OAuth2LoginMutator authorities(GrantedAuthority... authorities) {
Assert.notNull(authorities, "authorities cannot be null");
this.authorities = () -> Arrays.asList(authorities);
this.oauth2User = this::defaultPrincipal;
return this;
}
/**
* Mutate the attributes using the given {@link Consumer}
* @param attributesConsumer The {@link Consumer} for mutating the {@Map} of
* attributes
* @return the {@link OAuth2LoginMutator} for further configuration
*/
public OAuth2LoginMutator attributes(Consumer<Map<String, Object>> attributesConsumer) {
Assert.notNull(attributesConsumer, "attributesConsumer cannot be null");
this.attributes = () -> {
Map<String, Object> attributes = defaultAttributes();
attributesConsumer.accept(attributes);
return attributes;
};
this.oauth2User = this::defaultPrincipal;
return this;
}
/**
* Use the provided {@link OAuth2User} as the authenticated user.
* @param oauth2User the {@link OAuth2User} to use
* @return the {@link OAuth2LoginMutator} for further configuration
*/
public OAuth2LoginMutator oauth2User(OAuth2User oauth2User) {
this.oauth2User = () -> oauth2User;
return this;
}
/**
* Use the provided {@link ClientRegistration} as the client to authorize.
* <p>
* The supplied {@link ClientRegistration} will be registered into a
* {@link ServerOAuth2AuthorizedClientRepository}.
* @param clientRegistration the {@link ClientRegistration} to use
* @return the {@link OAuth2LoginMutator} for further configuration
*/
public OAuth2LoginMutator clientRegistration(ClientRegistration clientRegistration) {
this.clientRegistration = clientRegistration;
return this;
}
@Override
public void beforeServerCreated(WebHttpHandlerBuilder builder) {
OAuth2AuthenticationToken token = getToken();
mockOAuth2Client().accessToken(this.accessToken).clientRegistration(this.clientRegistration)
.principalName(token.getPrincipal().getName()).beforeServerCreated(builder);
mockAuthentication(token).beforeServerCreated(builder);
}
@Override
public void afterConfigureAdded(WebTestClient.MockServerSpec<?> serverSpec) {
OAuth2AuthenticationToken token = getToken();
mockOAuth2Client().accessToken(this.accessToken).clientRegistration(this.clientRegistration)
.principalName(token.getPrincipal().getName()).afterConfigureAdded(serverSpec);
mockAuthentication(token).afterConfigureAdded(serverSpec);
}
@Override
public void afterConfigurerAdded(WebTestClient.Builder builder,
@Nullable WebHttpHandlerBuilder httpHandlerBuilder, @Nullable ClientHttpConnector connector) {
OAuth2AuthenticationToken token = getToken();
mockOAuth2Client().accessToken(this.accessToken).clientRegistration(this.clientRegistration)
.principalName(token.getPrincipal().getName())
.afterConfigurerAdded(builder, httpHandlerBuilder, connector);
mockAuthentication(token).afterConfigurerAdded(builder, httpHandlerBuilder, connector);
}
private OAuth2AuthenticationToken getToken() {
OAuth2User oauth2User = this.oauth2User.get();
return new OAuth2AuthenticationToken(oauth2User, oauth2User.getAuthorities(),
this.clientRegistration.getRegistrationId());
}
private ClientRegistration.Builder clientRegistrationBuilder() {
return ClientRegistration.withRegistrationId("test").authorizationGrantType(AuthorizationGrantType.PASSWORD)
.clientId("test-client").tokenUri("https://token-uri.example.org");
}
private Collection<GrantedAuthority> defaultAuthorities() {
Set<GrantedAuthority> authorities = new LinkedHashSet<>();
authorities.add(new OAuth2UserAuthority(this.attributes.get()));
for (String authority : this.accessToken.getScopes()) {
authorities.add(new SimpleGrantedAuthority("SCOPE_" + authority));
}
return authorities;
}
private Map<String, Object> defaultAttributes() {
Map<String, Object> attributes = new HashMap<>();
attributes.put(this.nameAttributeKey, "user");
return attributes;
}
private OAuth2User defaultPrincipal() {
return new DefaultOAuth2User(this.authorities.get(), this.attributes.get(), this.nameAttributeKey);
}
}
/**
* @author Josh Cummings
* @since 5.3
*/
public static final class OidcLoginMutator implements WebTestClientConfigurer, MockServerConfigurer {
private ClientRegistration clientRegistration;
private OAuth2AccessToken accessToken;
private OidcIdToken idToken;
private OidcUserInfo userInfo;
private Supplier<OidcUser> oidcUser = this::defaultPrincipal;
private Collection<GrantedAuthority> authorities;
private OidcLoginMutator(OAuth2AccessToken accessToken) {
this.accessToken = accessToken;
this.clientRegistration = clientRegistrationBuilder().build();
}
/**
* Use the provided authorities in the {@link Authentication}
* @param authorities the authorities to use
* @return the {@link OidcLoginMutator} for further configuration
*/
public OidcLoginMutator authorities(Collection<GrantedAuthority> authorities) {
Assert.notNull(authorities, "authorities cannot be null");
this.authorities = authorities;
this.oidcUser = this::defaultPrincipal;
return this;
}
/**
* Use the provided authorities in the {@link Authentication}
* @param authorities the authorities to use
* @return the {@link OidcLoginMutator} for further configuration
*/
public OidcLoginMutator authorities(GrantedAuthority... authorities) {
Assert.notNull(authorities, "authorities cannot be null");
this.authorities = Arrays.asList(authorities);
this.oidcUser = this::defaultPrincipal;
return this;
}
/**
* Use the provided {@link OidcIdToken} when constructing the authenticated user
* @param idTokenBuilderConsumer a {@link Consumer} of a
* {@link OidcIdToken.Builder}
* @return the {@link OidcLoginMutator} for further configuration
*/
public OidcLoginMutator idToken(Consumer<OidcIdToken.Builder> idTokenBuilderConsumer) {
OidcIdToken.Builder builder = OidcIdToken.withTokenValue("id-token");
builder.subject("user");
idTokenBuilderConsumer.accept(builder);
this.idToken = builder.build();
this.oidcUser = this::defaultPrincipal;
return this;
}
/**
* Use the provided {@link OidcUserInfo} when constructing the authenticated user
* @param userInfoBuilderConsumer a {@link Consumer} of a
* {@link OidcUserInfo.Builder}
* @return the {@link OidcLoginMutator} for further configuration
*/
public OidcLoginMutator userInfoToken(Consumer<OidcUserInfo.Builder> userInfoBuilderConsumer) {
OidcUserInfo.Builder builder = OidcUserInfo.builder();
userInfoBuilderConsumer.accept(builder);
this.userInfo = builder.build();
this.oidcUser = this::defaultPrincipal;
return this;
}
/**
* Use the provided {@link OidcUser} as the authenticated user.
* <p>
* Supplying an {@link OidcUser} will take precedence over {@link #idToken},
* {@link #userInfo}, and list of {@link GrantedAuthority}s to use.
* @param oidcUser the {@link OidcUser} to use
* @return the {@link OidcLoginMutator} for further configuration
*/
public OidcLoginMutator oidcUser(OidcUser oidcUser) {
this.oidcUser = () -> oidcUser;
return this;
}
/**
* Use the provided {@link ClientRegistration} as the client to authorize.
* <p>
* The supplied {@link ClientRegistration} will be registered into a
* {@link ServerOAuth2AuthorizedClientRepository}.
* @param clientRegistration the {@link ClientRegistration} to use
* @return the {@link OidcLoginMutator} for further configuration
*/
public OidcLoginMutator clientRegistration(ClientRegistration clientRegistration) {
this.clientRegistration = clientRegistration;
return this;
}
@Override
public void beforeServerCreated(WebHttpHandlerBuilder builder) {
OAuth2AuthenticationToken token = getToken();
mockOAuth2Client().accessToken(this.accessToken).principalName(token.getPrincipal().getName())
.clientRegistration(this.clientRegistration).beforeServerCreated(builder);
mockAuthentication(token).beforeServerCreated(builder);
}
@Override
public void afterConfigureAdded(WebTestClient.MockServerSpec<?> serverSpec) {
OAuth2AuthenticationToken token = getToken();
mockOAuth2Client().accessToken(this.accessToken).principalName(token.getPrincipal().getName())
.clientRegistration(this.clientRegistration).afterConfigureAdded(serverSpec);
mockAuthentication(token).afterConfigureAdded(serverSpec);
}
@Override
public void afterConfigurerAdded(WebTestClient.Builder builder,
@Nullable WebHttpHandlerBuilder httpHandlerBuilder, @Nullable ClientHttpConnector connector) {
OAuth2AuthenticationToken token = getToken();
mockOAuth2Client().accessToken(this.accessToken).principalName(token.getPrincipal().getName())
.clientRegistration(this.clientRegistration)
.afterConfigurerAdded(builder, httpHandlerBuilder, connector);
mockAuthentication(token).afterConfigurerAdded(builder, httpHandlerBuilder, connector);
}
private ClientRegistration.Builder clientRegistrationBuilder() {
return ClientRegistration.withRegistrationId("test").authorizationGrantType(AuthorizationGrantType.PASSWORD)
.clientId("test-client").tokenUri("https://token-uri.example.org");
}
private OAuth2AuthenticationToken getToken() {
OidcUser oidcUser = this.oidcUser.get();
return new OAuth2AuthenticationToken(oidcUser, oidcUser.getAuthorities(),
this.clientRegistration.getRegistrationId());
}
private Collection<GrantedAuthority> getAuthorities() {
if (this.authorities != null) {
return this.authorities;
}
Set<GrantedAuthority> authorities = new LinkedHashSet<>();
authorities.add(new OidcUserAuthority(getOidcIdToken(), getOidcUserInfo()));
for (String authority : this.accessToken.getScopes()) {
authorities.add(new SimpleGrantedAuthority("SCOPE_" + authority));
}
return authorities;
}
private OidcIdToken getOidcIdToken() {
if (this.idToken != null) {
return this.idToken;
}
return new OidcIdToken("id-token", null, null, Collections.singletonMap(IdTokenClaimNames.SUB, "user"));
}
private OidcUserInfo getOidcUserInfo() {
return this.userInfo;
}
private OidcUser defaultPrincipal() {
return new DefaultOidcUser(getAuthorities(), getOidcIdToken(), this.userInfo);
}
}
/**
* @author Josh Cummings
* @since 5.3
*/
public static final class OAuth2ClientMutator implements WebTestClientConfigurer, MockServerConfigurer {
private String registrationId = "test";
private ClientRegistration clientRegistration;
private String principalName = "user";
private OAuth2AccessToken accessToken = new OAuth2AccessToken(OAuth2AccessToken.TokenType.BEARER,
"access-token", null, null, Collections.singleton("read"));
private OAuth2ClientMutator() {
}
private OAuth2ClientMutator(String registrationId) {
this.registrationId = registrationId;
clientRegistration((c) -> {
});
}
/**
* Use this {@link ClientRegistration}
* @param clientRegistration
* @return the
* {@link SecurityMockMvcRequestPostProcessors.OAuth2ClientRequestPostProcessor}
* for further configuration
*/
public OAuth2ClientMutator clientRegistration(ClientRegistration clientRegistration) {
this.clientRegistration = clientRegistration;
return this;
}
/**
* Use this {@link Consumer} to configure a {@link ClientRegistration}
* @param clientRegistrationConfigurer the {@link ClientRegistration} configurer
* @return the
* {@link SecurityMockMvcRequestPostProcessors.OAuth2ClientRequestPostProcessor}
* for further configuration
*/
public OAuth2ClientMutator clientRegistration(
Consumer<ClientRegistration.Builder> clientRegistrationConfigurer) {
ClientRegistration.Builder builder = clientRegistrationBuilder();
clientRegistrationConfigurer.accept(builder);
this.clientRegistration = builder.build();
return this;
}
/**
* Use this as the resource owner's principal name
* @param principalName the resource owner's principal name
* @return the {@link OAuth2ClientMutator} for further configuration
*/
public OAuth2ClientMutator principalName(String principalName) {
Assert.notNull(principalName, "principalName cannot be null");
this.principalName = principalName;
return this;
}
/**
* Use this {@link OAuth2AccessToken}
* @param accessToken the {@link OAuth2AccessToken} to use
* @return the
* {@link SecurityMockMvcRequestPostProcessors.OAuth2ClientRequestPostProcessor}
* for further configuration
*/
public OAuth2ClientMutator accessToken(OAuth2AccessToken accessToken) {
this.accessToken = accessToken;
return this;
}
@Override
public void beforeServerCreated(WebHttpHandlerBuilder builder) {
builder.filters(addAuthorizedClientFilter());
}
@Override
public void afterConfigureAdded(WebTestClient.MockServerSpec<?> serverSpec) {
}
@Override
public void afterConfigurerAdded(WebTestClient.Builder builder,
@Nullable WebHttpHandlerBuilder httpHandlerBuilder, @Nullable ClientHttpConnector connector) {
httpHandlerBuilder.filters(addAuthorizedClientFilter());
}
private Consumer<List<WebFilter>> addAuthorizedClientFilter() {
OAuth2AuthorizedClient client = getClient();
return (filters) -> filters.add(0, (exchange, chain) -> {
ServerOAuth2AuthorizedClientRepository authorizedClientRepository = OAuth2ClientServerTestUtils
.getAuthorizedClientRepository(exchange);
if (!(authorizedClientRepository instanceof TestOAuth2AuthorizedClientRepository)) {
authorizedClientRepository = new TestOAuth2AuthorizedClientRepository(authorizedClientRepository);
OAuth2ClientServerTestUtils.setAuthorizedClientRepository(exchange, authorizedClientRepository);
}
TestOAuth2AuthorizedClientRepository.enable(exchange);
return authorizedClientRepository.saveAuthorizedClient(client, null, exchange)
.then(chain.filter(exchange));
});
}
private OAuth2AuthorizedClient getClient() {
Assert.notNull(this.clientRegistration,
"Please specify a ClientRegistration via one of the clientRegistration methods");
return new OAuth2AuthorizedClient(this.clientRegistration, this.principalName, this.accessToken);
}
private ClientRegistration.Builder clientRegistrationBuilder() {
return ClientRegistration.withRegistrationId(this.registrationId)
.authorizationGrantType(AuthorizationGrantType.PASSWORD).clientId("test-client")
.clientSecret("test-secret").tokenUri("https://idp.example.org/oauth/token");
}
/**
* Used to wrap the {@link OAuth2AuthorizedClientRepository} to provide support
* for testing when the request is wrapped
*/
private static final class TestOAuth2AuthorizedClientManager implements ReactiveOAuth2AuthorizedClientManager {
static final String ENABLED_ATTR_NAME = TestOAuth2AuthorizedClientManager.class.getName()
.concat(".ENABLED");
private final ReactiveOAuth2AuthorizedClientManager delegate;
private ServerOAuth2AuthorizedClientRepository authorizedClientRepository;
TestOAuth2AuthorizedClientManager(ReactiveOAuth2AuthorizedClientManager delegate) {
this.delegate = delegate;
}
@Override
public Mono<OAuth2AuthorizedClient> authorize(OAuth2AuthorizeRequest authorizeRequest) {
ServerWebExchange exchange = authorizeRequest.getAttribute(ServerWebExchange.class.getName());
if (isEnabled(exchange)) {
return this.authorizedClientRepository.loadAuthorizedClient(
authorizeRequest.getClientRegistrationId(), authorizeRequest.getPrincipal(), exchange);
}
return this.delegate.authorize(authorizeRequest);
}
static void enable(ServerWebExchange exchange) {
exchange.getAttributes().put(ENABLED_ATTR_NAME, Boolean.TRUE);
}
boolean isEnabled(ServerWebExchange exchange) {
return Boolean.TRUE.equals(exchange.getAttribute(ENABLED_ATTR_NAME));
}
}
/**
* Used to wrap the {@link OAuth2AuthorizedClientRepository} to provide support
* for testing when the request is wrapped
*/
static final class TestOAuth2AuthorizedClientRepository implements ServerOAuth2AuthorizedClientRepository {
static final String TOKEN_ATTR_NAME = TestOAuth2AuthorizedClientRepository.class.getName().concat(".TOKEN");
static final String ENABLED_ATTR_NAME = TestOAuth2AuthorizedClientRepository.class.getName()
.concat(".ENABLED");
private final ServerOAuth2AuthorizedClientRepository delegate;
TestOAuth2AuthorizedClientRepository(ServerOAuth2AuthorizedClientRepository delegate) {
this.delegate = delegate;
}
@Override
public <T extends OAuth2AuthorizedClient> Mono<T> loadAuthorizedClient(String clientRegistrationId,
Authentication principal, ServerWebExchange exchange) {
if (isEnabled(exchange)) {
return Mono.just(exchange.getAttribute(TOKEN_ATTR_NAME));
}
return this.delegate.loadAuthorizedClient(clientRegistrationId, principal, exchange);
}
@Override
public Mono<Void> saveAuthorizedClient(OAuth2AuthorizedClient authorizedClient, Authentication principal,
ServerWebExchange exchange) {
if (isEnabled(exchange)) {
exchange.getAttributes().put(TOKEN_ATTR_NAME, authorizedClient);
return Mono.empty();
}
return this.delegate.saveAuthorizedClient(authorizedClient, principal, exchange);
}
@Override
public Mono<Void> removeAuthorizedClient(String clientRegistrationId, Authentication principal,
ServerWebExchange exchange) {
if (isEnabled(exchange)) {
exchange.getAttributes().remove(TOKEN_ATTR_NAME);
return Mono.empty();
}
return this.delegate.removeAuthorizedClient(clientRegistrationId, principal, exchange);
}
static void enable(ServerWebExchange exchange) {
exchange.getAttributes().put(ENABLED_ATTR_NAME, Boolean.TRUE);
}
boolean isEnabled(ServerWebExchange exchange) {
return Boolean.TRUE.equals(exchange.getAttribute(ENABLED_ATTR_NAME));
}
}
private static final class OAuth2ClientServerTestUtils {
private static final ServerOAuth2AuthorizedClientRepository DEFAULT_CLIENT_REPO = new WebSessionServerOAuth2AuthorizedClientRepository();
private OAuth2ClientServerTestUtils() {
}
/**
* Gets the {@link ServerOAuth2AuthorizedClientRepository} for the specified
* {@link ServerWebExchange}. If one is not found, one based off of
* {@link WebSessionServerOAuth2AuthorizedClientRepository} is used.
* @param exchange the {@link ServerWebExchange} to obtain the
* {@link ReactiveOAuth2AuthorizedClientManager}
* @return the {@link ReactiveOAuth2AuthorizedClientManager} for the specified
* {@link ServerWebExchange}
*/
static ServerOAuth2AuthorizedClientRepository getAuthorizedClientRepository(ServerWebExchange exchange) {
ReactiveOAuth2AuthorizedClientManager manager = getOAuth2AuthorizedClientManager(exchange);
if (manager == null) {
return DEFAULT_CLIENT_REPO;
}
if (manager instanceof DefaultReactiveOAuth2AuthorizedClientManager) {
return (ServerOAuth2AuthorizedClientRepository) ReflectionTestUtils.getField(manager,
"authorizedClientRepository");
}
if (manager instanceof TestOAuth2AuthorizedClientManager) {
return ((TestOAuth2AuthorizedClientManager) manager).authorizedClientRepository;
}
return DEFAULT_CLIENT_REPO;
}
static void setAuthorizedClientRepository(ServerWebExchange exchange,
ServerOAuth2AuthorizedClientRepository repository) {
ReactiveOAuth2AuthorizedClientManager manager = getOAuth2AuthorizedClientManager(exchange);
if (manager == null) {
return;
}
if (manager instanceof DefaultReactiveOAuth2AuthorizedClientManager) {
ReflectionTestUtils.setField(manager, "authorizedClientRepository", repository);
return;
}
if (!(manager instanceof TestOAuth2AuthorizedClientManager)) {
manager = new TestOAuth2AuthorizedClientManager(manager);
setOAuth2AuthorizedClientManager(exchange, manager);
}
TestOAuth2AuthorizedClientManager.enable(exchange);
((TestOAuth2AuthorizedClientManager) manager).authorizedClientRepository = repository;
}
static ReactiveOAuth2AuthorizedClientManager getOAuth2AuthorizedClientManager(ServerWebExchange exchange) {
OAuth2AuthorizedClientArgumentResolver resolver = findResolver(exchange,
OAuth2AuthorizedClientArgumentResolver.class);
if (resolver == null) {
return (authorizeRequest) -> DEFAULT_CLIENT_REPO.loadAuthorizedClient(
authorizeRequest.getClientRegistrationId(), authorizeRequest.getPrincipal(), exchange);
}
return (ReactiveOAuth2AuthorizedClientManager) ReflectionTestUtils.getField(resolver,
"authorizedClientManager");
}
/**
* Sets the {@link ReactiveOAuth2AuthorizedClientManager} for the specified
* {@link ServerWebExchange}.
* @param exchange the {@link ServerWebExchange} to obtain the
* {@link ReactiveOAuth2AuthorizedClientManager}
* @param manager the {@link ReactiveOAuth2AuthorizedClientManager} to set
*/
static void setOAuth2AuthorizedClientManager(ServerWebExchange exchange,
ReactiveOAuth2AuthorizedClientManager manager) {
OAuth2AuthorizedClientArgumentResolver resolver = findResolver(exchange,
OAuth2AuthorizedClientArgumentResolver.class);
if (resolver == null) {
return;
}
ReflectionTestUtils.setField(resolver, "authorizedClientManager", manager);
}
@SuppressWarnings("unchecked")
static <T extends HandlerMethodArgumentResolver> T findResolver(ServerWebExchange exchange,
Class<T> resolverClass) {
if (!ClassUtils.isPresent(
"org.springframework.web.reactive.result.method.annotation.RequestMappingHandlerAdapter",
null)) {
return null;
}
return WebFluxClasspathGuard.findResolver(exchange, resolverClass);
}
private static class WebFluxClasspathGuard {
static <T extends HandlerMethodArgumentResolver> T findResolver(ServerWebExchange exchange,
Class<T> resolverClass) {
RequestMappingHandlerAdapter handlerAdapter = getRequestMappingHandlerAdapter(exchange);
if (handlerAdapter == null) {
return null;
}
ArgumentResolverConfigurer configurer = handlerAdapter.getArgumentResolverConfigurer();
if (configurer == null) {
return null;
}
List<HandlerMethodArgumentResolver> resolvers = (List<HandlerMethodArgumentResolver>) ReflectionTestUtils
.invokeGetterMethod(configurer, "customResolvers");
if (resolvers == null) {
return null;
}
for (HandlerMethodArgumentResolver resolver : resolvers) {
if (resolverClass.isAssignableFrom(resolver.getClass())) {
return (T) resolver;
}
}
return null;
}
private static RequestMappingHandlerAdapter getRequestMappingHandlerAdapter(
ServerWebExchange exchange) {
ApplicationContext context = exchange.getApplicationContext();
if (context != null) {
String[] names = context.getBeanNamesForType(RequestMappingHandlerAdapter.class);
if (names.length > 0) {
return (RequestMappingHandlerAdapter) context.getBean(names[0]);
}
}
return null;
}
}
}
}
}
| 51,155 | 36.753506 | 140 | java |
null | spring-security-main/test/src/main/java/org/springframework/security/test/web/support/WebTestUtils.java | /*
* Copyright 2002-2014 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.test.web.support;
import java.util.List;
import jakarta.servlet.Filter;
import jakarta.servlet.ServletContext;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.security.config.BeanIds;
import org.springframework.security.web.context.AbstractSecurityWebApplicationInitializer;
import org.springframework.security.web.context.HttpSessionSecurityContextRepository;
import org.springframework.security.web.context.SecurityContextHolderFilter;
import org.springframework.security.web.context.SecurityContextPersistenceFilter;
import org.springframework.security.web.context.SecurityContextRepository;
import org.springframework.security.web.csrf.CsrfFilter;
import org.springframework.security.web.csrf.CsrfTokenRepository;
import org.springframework.security.web.csrf.CsrfTokenRequestHandler;
import org.springframework.security.web.csrf.HttpSessionCsrfTokenRepository;
import org.springframework.security.web.csrf.XorCsrfTokenRequestAttributeHandler;
import org.springframework.test.util.ReflectionTestUtils;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
/**
* A utility class for testing spring security
*
* @author Rob Winch
* @since 4.0
*/
public abstract class WebTestUtils {
private static final SecurityContextRepository DEFAULT_CONTEXT_REPO = new HttpSessionSecurityContextRepository();
private static final CsrfTokenRepository DEFAULT_TOKEN_REPO = new HttpSessionCsrfTokenRepository();
private static final CsrfTokenRequestHandler DEFAULT_CSRF_HANDLER = new XorCsrfTokenRequestAttributeHandler();
private WebTestUtils() {
}
/**
* Gets the {@link SecurityContextRepository} for the specified
* {@link HttpServletRequest}. If one is not found, a default
* {@link HttpSessionSecurityContextRepository} is used.
* @param request the {@link HttpServletRequest} to obtain the
* {@link SecurityContextRepository}
* @return the {@link SecurityContextRepository} for the specified
* {@link HttpServletRequest}
*/
public static SecurityContextRepository getSecurityContextRepository(HttpServletRequest request) {
SecurityContextPersistenceFilter filter = findFilter(request, SecurityContextPersistenceFilter.class);
if (filter != null) {
return (SecurityContextRepository) ReflectionTestUtils.getField(filter, "repo");
}
SecurityContextHolderFilter holderFilter = findFilter(request, SecurityContextHolderFilter.class);
if (holderFilter != null) {
return (SecurityContextRepository) ReflectionTestUtils.getField(holderFilter, "securityContextRepository");
}
return DEFAULT_CONTEXT_REPO;
}
/**
* Sets the {@link SecurityContextRepository} for the specified
* {@link HttpServletRequest}.
* @param request the {@link HttpServletRequest} to obtain the
* {@link SecurityContextRepository}
* @param securityContextRepository the {@link SecurityContextRepository} to set
*/
public static void setSecurityContextRepository(HttpServletRequest request,
SecurityContextRepository securityContextRepository) {
SecurityContextPersistenceFilter filter = findFilter(request, SecurityContextPersistenceFilter.class);
if (filter != null) {
ReflectionTestUtils.setField(filter, "repo", securityContextRepository);
}
SecurityContextHolderFilter holderFilter = findFilter(request, SecurityContextHolderFilter.class);
if (holderFilter != null) {
ReflectionTestUtils.setField(holderFilter, "securityContextRepository", securityContextRepository);
}
}
/**
* Gets the {@link CsrfTokenRepository} for the specified {@link HttpServletRequest}.
* If one is not found, the default {@link HttpSessionCsrfTokenRepository} is used.
* @param request the {@link HttpServletRequest} to obtain the
* {@link CsrfTokenRepository}
* @return the {@link CsrfTokenRepository} for the specified
* {@link HttpServletRequest}
*/
public static CsrfTokenRepository getCsrfTokenRepository(HttpServletRequest request) {
CsrfFilter filter = findFilter(request, CsrfFilter.class);
if (filter == null) {
return DEFAULT_TOKEN_REPO;
}
return (CsrfTokenRepository) ReflectionTestUtils.getField(filter, "tokenRepository");
}
/**
* Gets the {@link CsrfTokenRequestHandler} for the specified
* {@link HttpServletRequest}. If one is not found, the default
* {@link XorCsrfTokenRequestAttributeHandler} is used.
* @param request the {@link HttpServletRequest} to obtain the
* {@link CsrfTokenRequestHandler}
* @return the {@link CsrfTokenRequestHandler} for the specified
* {@link HttpServletRequest}
*/
public static CsrfTokenRequestHandler getCsrfTokenRequestHandler(HttpServletRequest request) {
CsrfFilter filter = findFilter(request, CsrfFilter.class);
if (filter == null) {
return DEFAULT_CSRF_HANDLER;
}
return (CsrfTokenRequestHandler) ReflectionTestUtils.getField(filter, "requestHandler");
}
/**
* Sets the {@link CsrfTokenRepository} for the specified {@link HttpServletRequest}.
* @param request the {@link HttpServletRequest} to obtain the
* {@link CsrfTokenRepository}
* @param repository the {@link CsrfTokenRepository} to set
*/
public static void setCsrfTokenRepository(HttpServletRequest request, CsrfTokenRepository repository) {
CsrfFilter filter = findFilter(request, CsrfFilter.class);
if (filter != null) {
ReflectionTestUtils.setField(filter, "tokenRepository", repository);
}
}
@SuppressWarnings("unchecked")
static <T extends Filter> T findFilter(HttpServletRequest request, Class<T> filterClass) {
ServletContext servletContext = request.getServletContext();
Filter springSecurityFilterChain = getSpringSecurityFilterChain(servletContext);
if (springSecurityFilterChain == null) {
return null;
}
List<Filter> filters = ReflectionTestUtils.invokeMethod(springSecurityFilterChain, "getFilters", request);
if (filters == null) {
return null;
}
for (Filter filter : filters) {
if (filterClass.isAssignableFrom(filter.getClass())) {
return (T) filter;
}
}
return null;
}
private static Filter getSpringSecurityFilterChain(ServletContext servletContext) {
Filter result = (Filter) servletContext.getAttribute(BeanIds.SPRING_SECURITY_FILTER_CHAIN);
if (result != null) {
return result;
}
WebApplicationContext webApplicationContext = WebApplicationContextUtils
.getWebApplicationContext(servletContext);
if (webApplicationContext == null) {
return null;
}
try {
String beanName = AbstractSecurityWebApplicationInitializer.DEFAULT_FILTER_NAME;
return webApplicationContext.getBean(beanName, Filter.class);
}
catch (NoSuchBeanDefinitionException ex) {
return null;
}
}
}
| 7,435 | 39.63388 | 114 | java |
null | spring-security-main/test/src/main/java/org/springframework/security/test/web/servlet/request/SecurityMockMvcRequestBuilders.java | /*
* Copyright 2002-2014 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.test.web.servlet.request;
import jakarta.servlet.ServletContext;
import org.springframework.beans.Mergeable;
import org.springframework.http.MediaType;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.security.web.csrf.CsrfToken;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.RequestBuilder;
import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder;
import org.springframework.test.web.servlet.request.RequestPostProcessor;
import org.springframework.web.util.UriComponentsBuilder;
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
/**
* Contains Spring Security related {@link MockMvc} {@link RequestBuilder}s.
*
* @author Rob Winch
* @since 4.0
*/
public final class SecurityMockMvcRequestBuilders {
private SecurityMockMvcRequestBuilders() {
}
/**
* Creates a request (including any necessary {@link CsrfToken}) that will submit a
* form based login to POST "/login".
* @return the FormLoginRequestBuilder for further customizations
*/
public static FormLoginRequestBuilder formLogin() {
return new FormLoginRequestBuilder();
}
/**
* Creates a request (including any necessary {@link CsrfToken}) that will submit a
* form based login to POST {@code loginProcessingUrl}.
* @param loginProcessingUrl the URL to POST to
* @return the FormLoginRequestBuilder for further customizations
*/
public static FormLoginRequestBuilder formLogin(String loginProcessingUrl) {
return formLogin().loginProcessingUrl(loginProcessingUrl);
}
/**
* Creates a logout request.
* @return the LogoutRequestBuilder for additional customizations
*/
public static LogoutRequestBuilder logout() {
return new LogoutRequestBuilder();
}
/**
* Creates a logout request (including any necessary {@link CsrfToken}) to the
* specified {@code logoutUrl}
* @param logoutUrl the logout request URL
* @return the LogoutRequestBuilder for additional customizations
*/
public static LogoutRequestBuilder logout(String logoutUrl) {
return new LogoutRequestBuilder().logoutUrl(logoutUrl);
}
/**
* Creates a logout request (including any necessary {@link CsrfToken})
*
* @author Rob Winch
* @since 4.0
*/
public static final class LogoutRequestBuilder implements RequestBuilder, Mergeable {
private String logoutUrl = "/logout";
private RequestPostProcessor postProcessor = csrf();
private Mergeable parent;
private LogoutRequestBuilder() {
}
@Override
public MockHttpServletRequest buildRequest(ServletContext servletContext) {
MockHttpServletRequestBuilder logoutRequest = post(this.logoutUrl).accept(MediaType.TEXT_HTML,
MediaType.ALL);
if (this.parent != null) {
logoutRequest = (MockHttpServletRequestBuilder) logoutRequest.merge(this.parent);
}
MockHttpServletRequest request = logoutRequest.buildRequest(servletContext);
logoutRequest.postProcessRequest(request);
return this.postProcessor.postProcessRequest(request);
}
/**
* Specifies the logout URL to POST to. Defaults to "/logout".
* @param logoutUrl the logout URL to POST to. Defaults to "/logout".
* @return the {@link LogoutRequestBuilder} for additional customizations
*/
public LogoutRequestBuilder logoutUrl(String logoutUrl) {
this.logoutUrl = logoutUrl;
return this;
}
/**
* Specifies the logout URL to POST to.
* @param logoutUrl the logout URL to POST to.
* @param uriVars the URI variables
* @return the {@link LogoutRequestBuilder} for additional customizations
*/
public LogoutRequestBuilder logoutUrl(String logoutUrl, Object... uriVars) {
this.logoutUrl = UriComponentsBuilder.fromPath(logoutUrl).buildAndExpand(uriVars).encode().toString();
return this;
}
@Override
public boolean isMergeEnabled() {
return true;
}
@Override
public Object merge(Object parent) {
if (parent == null) {
return this;
}
if (parent instanceof Mergeable) {
this.parent = (Mergeable) parent;
return this;
}
throw new IllegalArgumentException("Cannot merge with [" + parent.getClass().getName() + "]");
}
}
/**
* Creates a form based login request including any necessary {@link CsrfToken}.
*
* @author Rob Winch
* @since 4.0
*/
public static final class FormLoginRequestBuilder implements RequestBuilder, Mergeable {
private String usernameParam = "username";
private String passwordParam = "password";
private String username = "user";
private String password = "password";
private String loginProcessingUrl = "/login";
private MediaType acceptMediaType = MediaType.APPLICATION_FORM_URLENCODED;
private Mergeable parent;
private RequestPostProcessor postProcessor = csrf();
private FormLoginRequestBuilder() {
}
@Override
public MockHttpServletRequest buildRequest(ServletContext servletContext) {
MockHttpServletRequestBuilder loginRequest = post(this.loginProcessingUrl).accept(this.acceptMediaType)
.param(this.usernameParam, this.username).param(this.passwordParam, this.password);
if (this.parent != null) {
loginRequest = (MockHttpServletRequestBuilder) loginRequest.merge(this.parent);
}
MockHttpServletRequest request = loginRequest.buildRequest(servletContext);
loginRequest.postProcessRequest(request);
return this.postProcessor.postProcessRequest(request);
}
/**
* Specifies the URL to POST to. Default is "/login"
* @param loginProcessingUrl the URL to POST to. Default is "/login"
* @return the {@link FormLoginRequestBuilder} for additional customizations
*/
public FormLoginRequestBuilder loginProcessingUrl(String loginProcessingUrl) {
this.loginProcessingUrl = loginProcessingUrl;
return this;
}
/**
* Specifies the URL to POST to.
* @param loginProcessingUrl the URL to POST to
* @param uriVars the URI variables
* @return the {@link FormLoginRequestBuilder} for additional customizations
*/
public FormLoginRequestBuilder loginProcessingUrl(String loginProcessingUrl, Object... uriVars) {
this.loginProcessingUrl = UriComponentsBuilder.fromPath(loginProcessingUrl).buildAndExpand(uriVars).encode()
.toString();
return this;
}
/**
* The HTTP parameter to place the username. Default is "username".
* @param usernameParameter the HTTP parameter to place the username. Default is
* "username".
* @return the {@link FormLoginRequestBuilder} for additional customizations
*/
public FormLoginRequestBuilder userParameter(String usernameParameter) {
this.usernameParam = usernameParameter;
return this;
}
/**
* The HTTP parameter to place the password. Default is "password".
* @param passwordParameter the HTTP parameter to place the password. Default is
* "password".
* @return the {@link FormLoginRequestBuilder} for additional customizations
*/
public FormLoginRequestBuilder passwordParam(String passwordParameter) {
this.passwordParam = passwordParameter;
return this;
}
/**
* The value of the password parameter. Default is "password".
* @param password the value of the password parameter. Default is "password".
* @return the {@link FormLoginRequestBuilder} for additional customizations
*/
public FormLoginRequestBuilder password(String password) {
this.password = password;
return this;
}
/**
* The value of the username parameter. Default is "user".
* @param username the value of the username parameter. Default is "user".
* @return the {@link FormLoginRequestBuilder} for additional customizations
*/
public FormLoginRequestBuilder user(String username) {
this.username = username;
return this;
}
/**
* Specify both the password parameter name and the password.
* @param passwordParameter the HTTP parameter to place the password. Default is
* "password".
* @param password the value of the password parameter. Default is "password".
* @return the {@link FormLoginRequestBuilder} for additional customizations
*/
public FormLoginRequestBuilder password(String passwordParameter, String password) {
passwordParam(passwordParameter);
this.password = password;
return this;
}
/**
* Specify both the password parameter name and the password.
* @param usernameParameter the HTTP parameter to place the username. Default is
* "username".
* @param username the value of the username parameter. Default is "user".
* @return the {@link FormLoginRequestBuilder} for additional customizations
*/
public FormLoginRequestBuilder user(String usernameParameter, String username) {
userParameter(usernameParameter);
this.username = username;
return this;
}
/**
* Specify a media type to set as the Accept header in the request.
* @param acceptMediaType the {@link MediaType} to set the Accept header to.
* Default is: MediaType.APPLICATION_FORM_URLENCODED
* @return the {@link FormLoginRequestBuilder} for additional customizations
*/
public FormLoginRequestBuilder acceptMediaType(MediaType acceptMediaType) {
this.acceptMediaType = acceptMediaType;
return this;
}
@Override
public boolean isMergeEnabled() {
return true;
}
@Override
public Object merge(Object parent) {
if (parent == null) {
return this;
}
if (parent instanceof Mergeable) {
this.parent = (Mergeable) parent;
return this;
}
throw new IllegalArgumentException("Cannot merge with [" + parent.getClass().getName() + "]");
}
}
}
| 10,355 | 32.299035 | 111 | java |
null | spring-security-main/test/src/main/java/org/springframework/security/test/web/servlet/request/SecurityMockMvcRequestPostProcessors.java | /*
* Copyright 2002-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.test.web.servlet.request;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Base64;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Consumer;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import jakarta.servlet.ServletContext;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.core.convert.converter.Converter;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.context.SecurityContextHolderStrategy;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.oauth2.client.OAuth2AuthorizeRequest;
import org.springframework.security.oauth2.client.OAuth2AuthorizedClient;
import org.springframework.security.oauth2.client.OAuth2AuthorizedClientManager;
import org.springframework.security.oauth2.client.authentication.OAuth2AuthenticationToken;
import org.springframework.security.oauth2.client.registration.ClientRegistration;
import org.springframework.security.oauth2.client.web.DefaultOAuth2AuthorizedClientManager;
import org.springframework.security.oauth2.client.web.HttpSessionOAuth2AuthorizedClientRepository;
import org.springframework.security.oauth2.client.web.OAuth2AuthorizedClientRepository;
import org.springframework.security.oauth2.client.web.method.annotation.OAuth2AuthorizedClientArgumentResolver;
import org.springframework.security.oauth2.core.AuthorizationGrantType;
import org.springframework.security.oauth2.core.OAuth2AccessToken;
import org.springframework.security.oauth2.core.OAuth2AuthenticatedPrincipal;
import org.springframework.security.oauth2.core.OAuth2TokenIntrospectionClaimNames;
import org.springframework.security.oauth2.core.oidc.IdTokenClaimNames;
import org.springframework.security.oauth2.core.oidc.OidcIdToken;
import org.springframework.security.oauth2.core.oidc.OidcUserInfo;
import org.springframework.security.oauth2.core.oidc.user.DefaultOidcUser;
import org.springframework.security.oauth2.core.oidc.user.OidcUser;
import org.springframework.security.oauth2.core.oidc.user.OidcUserAuthority;
import org.springframework.security.oauth2.core.user.DefaultOAuth2User;
import org.springframework.security.oauth2.core.user.OAuth2User;
import org.springframework.security.oauth2.core.user.OAuth2UserAuthority;
import org.springframework.security.oauth2.jwt.Jwt;
import org.springframework.security.oauth2.jwt.JwtClaimNames;
import org.springframework.security.oauth2.server.resource.authentication.BearerTokenAuthentication;
import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationToken;
import org.springframework.security.oauth2.server.resource.authentication.JwtGrantedAuthoritiesConverter;
import org.springframework.security.oauth2.server.resource.introspection.OAuth2IntrospectionAuthenticatedPrincipal;
import org.springframework.security.test.context.TestSecurityContextHolder;
import org.springframework.security.test.context.TestSecurityContextHolderStrategyAdapter;
import org.springframework.security.test.web.servlet.setup.SecurityMockMvcConfigurers;
import org.springframework.security.test.web.support.WebTestUtils;
import org.springframework.security.web.context.HttpRequestResponseHolder;
import org.springframework.security.web.context.SecurityContextPersistenceFilter;
import org.springframework.security.web.context.SecurityContextRepository;
import org.springframework.security.web.csrf.CsrfFilter;
import org.springframework.security.web.csrf.CsrfToken;
import org.springframework.security.web.csrf.CsrfTokenRepository;
import org.springframework.security.web.csrf.CsrfTokenRequestHandler;
import org.springframework.security.web.csrf.DeferredCsrfToken;
import org.springframework.security.web.csrf.HttpSessionCsrfTokenRepository;
import org.springframework.test.util.ReflectionTestUtils;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.RequestPostProcessor;
import org.springframework.util.Assert;
import org.springframework.util.ClassUtils;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter;
/**
* Contains {@link MockMvc} {@link RequestPostProcessor} implementations for Spring
* Security.
*
* @author Rob Winch
* @since 4.0
*/
public final class SecurityMockMvcRequestPostProcessors {
private static final SecurityContextHolderStrategy DEFAULT_SECURITY_CONTEXT_HOLDER_STRATEGY = new TestSecurityContextHolderStrategyAdapter();
private SecurityMockMvcRequestPostProcessors() {
}
/**
* Creates a DigestRequestPostProcessor that enables easily adding digest based
* authentication to a request.
* @return the DigestRequestPostProcessor to use
*/
public static DigestRequestPostProcessor digest() {
return new DigestRequestPostProcessor();
}
/**
* 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);
}
/**
* Populates the provided X509Certificate instances on the request.
* @param certificates the X509Certificate instances to pouplate
* @return the
* {@link org.springframework.test.web.servlet.request.RequestPostProcessor} to use.
*/
public static RequestPostProcessor x509(X509Certificate... certificates) {
return new X509RequestPostProcessor(certificates);
}
/**
* 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);
}
/**
* Creates a {@link RequestPostProcessor} that will automatically populate a valid
* {@link CsrfToken} in the request.
* @return the {@link CsrfRequestPostProcessor} for further customizations.
*/
public static CsrfRequestPostProcessor csrf() {
return new CsrfRequestPostProcessor();
}
/**
* Creates a {@link RequestPostProcessor} that can be used to ensure that the
* resulting request is ran with the user in the {@link TestSecurityContextHolder}.
* @return the {@link RequestPostProcessor} to use
*/
public static RequestPostProcessor testSecurityContext() {
return new TestSecurityContextHolderPostProcessor();
}
/**
* Establish a {@link SecurityContext} that has a
* {@link UsernamePasswordAuthenticationToken} for the
* {@link Authentication#getPrincipal()} and a {@link User} for the
* {@link UsernamePasswordAuthenticationToken#getPrincipal()}. All details are
* declarative and do not require that the user actually exists.
*
* <p>
* The support works by associating the user to the HttpServletRequest. To associate
* the request to the SecurityContextHolder you need to ensure that the
* SecurityContextPersistenceFilter is associated with the MockMvc instance. A few
* ways to do this are:
* </p>
*
* <ul>
* <li>Invoking apply {@link SecurityMockMvcConfigurers#springSecurity()}</li>
* <li>Adding Spring Security's FilterChainProxy to MockMvc</li>
* <li>Manually adding {@link SecurityContextPersistenceFilter} to the MockMvc
* instance may make sense when using MockMvcBuilders standaloneSetup</li>
* </ul>
* @param username the username to populate
* @return the {@link UserRequestPostProcessor} for additional customization
*/
public static UserRequestPostProcessor user(String username) {
return new UserRequestPostProcessor(username);
}
/**
* Establish a {@link SecurityContext} that has a
* {@link UsernamePasswordAuthenticationToken} for the
* {@link Authentication#getPrincipal()} and a custom {@link UserDetails} for the
* {@link UsernamePasswordAuthenticationToken#getPrincipal()}. All details are
* declarative and do not require that the user actually exists.
*
* <p>
* The support works by associating the user to the HttpServletRequest. To associate
* the request to the SecurityContextHolder you need to ensure that the
* SecurityContextPersistenceFilter is associated with the MockMvc instance. A few
* ways to do this are:
* </p>
*
* <ul>
* <li>Invoking apply {@link SecurityMockMvcConfigurers#springSecurity()}</li>
* <li>Adding Spring Security's FilterChainProxy to MockMvc</li>
* <li>Manually adding {@link SecurityContextPersistenceFilter} to the MockMvc
* instance may make sense when using MockMvcBuilders standaloneSetup</li>
* </ul>
* @param user the UserDetails to populate
* @return the {@link RequestPostProcessor} to use
*/
public static RequestPostProcessor user(UserDetails user) {
return new UserDetailsRequestPostProcessor(user);
}
/**
* Establish a {@link SecurityContext} that has a {@link JwtAuthenticationToken} for
* the {@link Authentication} and a {@link Jwt} for the
* {@link Authentication#getPrincipal()}. All details are declarative and do not
* require the JWT to be valid.
*
* <p>
* The support works by associating the authentication to the HttpServletRequest. To
* associate the request to the SecurityContextHolder you need to ensure that the
* SecurityContextPersistenceFilter is associated with the MockMvc instance. A few
* ways to do this are:
* </p>
*
* <ul>
* <li>Invoking apply {@link SecurityMockMvcConfigurers#springSecurity()}</li>
* <li>Adding Spring Security's FilterChainProxy to MockMvc</li>
* <li>Manually adding {@link SecurityContextPersistenceFilter} to the MockMvc
* instance may make sense when using MockMvcBuilders standaloneSetup</li>
* </ul>
* @return the {@link JwtRequestPostProcessor} for additional customization
*/
public static JwtRequestPostProcessor jwt() {
return new JwtRequestPostProcessor();
}
/**
* Establish a {@link SecurityContext} that has a {@link BearerTokenAuthentication}
* for the {@link Authentication} and a {@link OAuth2AuthenticatedPrincipal} for the
* {@link Authentication#getPrincipal()}. All details are declarative and do not
* require the token to be valid
*
* <p>
* The support works by associating the authentication to the HttpServletRequest. To
* associate the request to the SecurityContextHolder you need to ensure that the
* SecurityContextPersistenceFilter is associated with the MockMvc instance. A few
* ways to do this are:
* </p>
*
* <ul>
* <li>Invoking apply {@link SecurityMockMvcConfigurers#springSecurity()}</li>
* <li>Adding Spring Security's FilterChainProxy to MockMvc</li>
* <li>Manually adding {@link SecurityContextPersistenceFilter} to the MockMvc
* instance may make sense when using MockMvcBuilders standaloneSetup</li>
* </ul>
* @return the {@link OpaqueTokenRequestPostProcessor} for additional customization
* @since 5.3
*/
public static OpaqueTokenRequestPostProcessor opaqueToken() {
return new OpaqueTokenRequestPostProcessor();
}
/**
* Establish a {@link SecurityContext} that uses the specified {@link Authentication}
* for the {@link Authentication#getPrincipal()} and a custom {@link UserDetails}. All
* details are declarative and do not require that the user actually exists.
*
* <p>
* The support works by associating the user to the HttpServletRequest. To associate
* the request to the SecurityContextHolder you need to ensure that the
* SecurityContextPersistenceFilter is associated with the MockMvc instance. A few
* ways to do this are:
* </p>
*
* <ul>
* <li>Invoking apply {@link SecurityMockMvcConfigurers#springSecurity()}</li>
* <li>Adding Spring Security's FilterChainProxy to MockMvc</li>
* <li>Manually adding {@link SecurityContextPersistenceFilter} to the MockMvc
* instance may make sense when using MockMvcBuilders standaloneSetup</li>
* </ul>
* @param authentication the Authentication to populate
* @return the {@link RequestPostProcessor} to use
*/
public static RequestPostProcessor authentication(Authentication authentication) {
return new AuthenticationRequestPostProcessor(authentication);
}
/**
* Establish a {@link SecurityContext} that uses an
* {@link AnonymousAuthenticationToken}. This is useful when a user wants to run a
* majority of tests as a specific user and wishes to override a few methods to be
* anonymous. For example:
*
* <pre>
* <code>
* public class SecurityTests {
* @Before
* public void setup() {
* mockMvc = MockMvcBuilders
* .webAppContextSetup(context)
* .defaultRequest(get("/").with(user("user")))
* .build();
* }
*
* @Test
* public void anonymous() {
* mockMvc.perform(get("anonymous").with(anonymous()));
* }
* // ... lots of tests ran with a default user ...
* }
* </code> </pre>
* @return the {@link RequestPostProcessor} to use
*/
public static RequestPostProcessor anonymous() {
return new AnonymousRequestPostProcessor();
}
/**
* Establish the specified {@link SecurityContext} to be used.
*
* <p>
* This works by associating the user to the {@link HttpServletRequest}. To associate
* the request to the {@link SecurityContextHolder} you need to ensure that the
* {@link SecurityContextPersistenceFilter} (i.e. Spring Security's FilterChainProxy
* will typically do this) is associated with the {@link MockMvc} instance.
* </p>
*/
public static RequestPostProcessor securityContext(SecurityContext securityContext) {
return new SecurityContextRequestPostProcessor(securityContext);
}
/**
* Convenience mechanism for setting the Authorization header to use HTTP Basic with
* the given username and password. This method will automatically perform the
* necessary Base64 encoding.
* @param username the username to include in the Authorization header.
* @param password the password to include in the Authorization header.
* @return the {@link RequestPostProcessor} to use
*/
public static RequestPostProcessor httpBasic(String username, String password) {
return new HttpBasicRequestPostProcessor(username, password);
}
/**
* Establish a {@link SecurityContext} that has a {@link OAuth2AuthenticationToken}
* for the {@link Authentication}, a {@link OAuth2User} as the principal, and a
* {@link OAuth2AuthorizedClient} in the session. All details are declarative and do
* not require associated tokens to be valid.
*
* <p>
* The support works by associating the authentication to the HttpServletRequest. To
* associate the request to the SecurityContextHolder you need to ensure that the
* SecurityContextPersistenceFilter is associated with the MockMvc instance. A few
* ways to do this are:
* </p>
*
* <ul>
* <li>Invoking apply {@link SecurityMockMvcConfigurers#springSecurity()}</li>
* <li>Adding Spring Security's FilterChainProxy to MockMvc</li>
* <li>Manually adding {@link SecurityContextPersistenceFilter} to the MockMvc
* instance may make sense when using MockMvcBuilders standaloneSetup</li>
* </ul>
* @return the {@link OidcLoginRequestPostProcessor} for additional customization
* @since 5.3
*/
public static OAuth2LoginRequestPostProcessor oauth2Login() {
OAuth2AccessToken accessToken = new OAuth2AccessToken(OAuth2AccessToken.TokenType.BEARER, "access-token", null,
null, Collections.singleton("read"));
return new OAuth2LoginRequestPostProcessor(accessToken);
}
/**
* Establish a {@link SecurityContext} that has a {@link OAuth2AuthenticationToken}
* for the {@link Authentication}, a {@link OidcUser} as the principal, and a
* {@link OAuth2AuthorizedClient} in the session. All details are declarative and do
* not require associated tokens to be valid.
*
* <p>
* The support works by associating the authentication to the HttpServletRequest. To
* associate the request to the SecurityContextHolder you need to ensure that the
* SecurityContextPersistenceFilter is associated with the MockMvc instance. A few
* ways to do this are:
* </p>
*
* <ul>
* <li>Invoking apply {@link SecurityMockMvcConfigurers#springSecurity()}</li>
* <li>Adding Spring Security's FilterChainProxy to MockMvc</li>
* <li>Manually adding {@link SecurityContextPersistenceFilter} to the MockMvc
* instance may make sense when using MockMvcBuilders standaloneSetup</li>
* </ul>
* @return the {@link OidcLoginRequestPostProcessor} for additional customization
* @since 5.3
*/
public static OidcLoginRequestPostProcessor oidcLogin() {
OAuth2AccessToken accessToken = new OAuth2AccessToken(OAuth2AccessToken.TokenType.BEARER, "access-token", null,
null, Collections.singleton("read"));
return new OidcLoginRequestPostProcessor(accessToken);
}
/**
* Establish an {@link OAuth2AuthorizedClient} in the session. All details are
* declarative and do not require associated tokens to be valid.
*
* <p>
* The support works by associating the authorized client to the HttpServletRequest
* using an {@link OAuth2AuthorizedClientRepository}
* </p>
* @return the {@link OAuth2ClientRequestPostProcessor} for additional customization
* @since 5.3
*/
public static OAuth2ClientRequestPostProcessor oauth2Client() {
return new OAuth2ClientRequestPostProcessor();
}
/**
* Establish an {@link OAuth2AuthorizedClient} in the session. All details are
* declarative and do not require associated tokens to be valid.
*
* <p>
* The support works by associating the authorized client to the HttpServletRequest
* using an {@link OAuth2AuthorizedClientRepository}
* </p>
* @param registrationId The registration id for the {@link OAuth2AuthorizedClient}
* @return the {@link OAuth2ClientRequestPostProcessor} for additional customization
* @since 5.3
*/
public static OAuth2ClientRequestPostProcessor oauth2Client(String registrationId) {
return new OAuth2ClientRequestPostProcessor(registrationId);
}
private static SecurityContextHolderStrategy getSecurityContextHolderStrategy(HttpServletRequest request) {
WebApplicationContext context = WebApplicationContextUtils
.findWebApplicationContext(request.getServletContext());
if (context == null) {
return DEFAULT_SECURITY_CONTEXT_HOLDER_STRATEGY;
}
if (context.getBeanNamesForType(SecurityContextHolderStrategy.class).length == 0) {
return DEFAULT_SECURITY_CONTEXT_HOLDER_STRATEGY;
}
return context.getBean(SecurityContextHolderStrategy.class);
}
/**
* Populates the X509Certificate instances onto the request
*/
private static final class X509RequestPostProcessor implements RequestPostProcessor {
private final X509Certificate[] certificates;
private X509RequestPostProcessor(X509Certificate... certificates) {
Assert.notNull(certificates, "X509Certificate cannot be null");
this.certificates = certificates;
}
@Override
public MockHttpServletRequest postProcessRequest(MockHttpServletRequest request) {
request.setAttribute("jakarta.servlet.request.X509Certificate", this.certificates);
return request;
}
}
/**
* Populates a valid {@link CsrfToken} into the request.
*
* @author Rob Winch
* @since 4.0
*/
public static final class CsrfRequestPostProcessor implements RequestPostProcessor {
private static final byte[] INVALID_TOKEN_BYTES = new byte[] { 1, 1, 1, 96, 99, 98 };
private static final String INVALID_TOKEN_VALUE = Base64.getEncoder().encodeToString(INVALID_TOKEN_BYTES);
private boolean asHeader;
private boolean useInvalidToken;
private CsrfRequestPostProcessor() {
}
@Override
public MockHttpServletRequest postProcessRequest(MockHttpServletRequest request) {
CsrfTokenRepository repository = WebTestUtils.getCsrfTokenRepository(request);
CsrfTokenRequestHandler handler = WebTestUtils.getCsrfTokenRequestHandler(request);
if (!(repository instanceof TestCsrfTokenRepository)) {
repository = new TestCsrfTokenRepository(new HttpSessionCsrfTokenRepository());
WebTestUtils.setCsrfTokenRepository(request, repository);
}
TestCsrfTokenRepository.enable(request);
MockHttpServletResponse response = new MockHttpServletResponse();
DeferredCsrfToken deferredCsrfToken = repository.loadDeferredToken(request, response);
handler.handle(request, response, deferredCsrfToken::get);
CsrfToken token = (CsrfToken) request.getAttribute(CsrfToken.class.getName());
String tokenValue = this.useInvalidToken ? INVALID_TOKEN_VALUE : token.getToken();
if (this.asHeader) {
request.addHeader(token.getHeaderName(), tokenValue);
}
else {
request.setParameter(token.getParameterName(), tokenValue);
}
return request;
}
/**
* Instead of using the {@link CsrfToken} as a request parameter (default) will
* populate the {@link CsrfToken} as a header.
* @return the {@link CsrfRequestPostProcessor} for additional customizations
*/
public CsrfRequestPostProcessor asHeader() {
this.asHeader = true;
return this;
}
/**
* Populates an invalid token value on the request.
* @return the {@link CsrfRequestPostProcessor} for additional customizations
*/
public CsrfRequestPostProcessor useInvalidToken() {
this.useInvalidToken = true;
return this;
}
/**
* Used to wrap the CsrfTokenRepository to provide support for testing when the
* request is wrapped (i.e. Spring Session is in use).
*/
static class TestCsrfTokenRepository implements CsrfTokenRepository {
static final String TOKEN_ATTR_NAME = TestCsrfTokenRepository.class.getName().concat(".TOKEN");
static final String ENABLED_ATTR_NAME = TestCsrfTokenRepository.class.getName().concat(".ENABLED");
private final CsrfTokenRepository delegate;
TestCsrfTokenRepository(CsrfTokenRepository delegate) {
this.delegate = delegate;
}
@Override
public CsrfToken generateToken(HttpServletRequest request) {
return this.delegate.generateToken(request);
}
@Override
public void saveToken(CsrfToken token, HttpServletRequest request, HttpServletResponse response) {
if (isEnabled(request)) {
request.setAttribute(TOKEN_ATTR_NAME, token);
}
else {
this.delegate.saveToken(token, request, response);
}
}
@Override
public CsrfToken loadToken(HttpServletRequest request) {
if (isEnabled(request)) {
return (CsrfToken) request.getAttribute(TOKEN_ATTR_NAME);
}
else {
return this.delegate.loadToken(request);
}
}
static void enable(HttpServletRequest request) {
request.setAttribute(ENABLED_ATTR_NAME, Boolean.TRUE);
}
boolean isEnabled(HttpServletRequest request) {
return Boolean.TRUE.equals(request.getAttribute(ENABLED_ATTR_NAME));
}
}
}
public static class DigestRequestPostProcessor implements RequestPostProcessor {
private String username = "user";
private String password = "password";
private String realm = "Spring Security";
private String nonce = generateNonce(60);
private String qop = "auth";
private String nc = "00000001";
private String cnonce = "c822c727a648aba7";
/**
* Configures the username to use
* @param username the username to use
* @return the DigestRequestPostProcessor for further customization
*/
private DigestRequestPostProcessor username(String username) {
Assert.notNull(username, "username cannot be null");
this.username = username;
return this;
}
/**
* Configures the password to use
* @param password the password to use
* @return the DigestRequestPostProcessor for further customization
*/
public DigestRequestPostProcessor password(String password) {
Assert.notNull(password, "password cannot be null");
this.password = password;
return this;
}
/**
* Configures the realm to use
* @param realm the realm to use
* @return the DigestRequestPostProcessor for further customization
*/
public DigestRequestPostProcessor realm(String realm) {
Assert.notNull(realm, "realm cannot be null");
this.realm = realm;
return this;
}
private static String generateNonce(int validitySeconds) {
long expiryTime = System.currentTimeMillis() + (validitySeconds * 1000);
String toDigest = expiryTime + ":" + "key";
String signatureValue = md5Hex(toDigest);
String nonceValue = expiryTime + ":" + signatureValue;
return new String(Base64.getEncoder().encode(nonceValue.getBytes()));
}
private String createAuthorizationHeader(MockHttpServletRequest request) {
String uri = request.getRequestURI();
String responseDigest = generateDigest(this.username, this.realm, this.password, request.getMethod(), uri,
this.qop, this.nonce, this.nc, this.cnonce);
return "Digest username=\"" + this.username + "\", realm=\"" + this.realm + "\", nonce=\"" + this.nonce
+ "\", uri=\"" + uri + "\", response=\"" + responseDigest + "\", qop=" + this.qop + ", nc="
+ this.nc + ", cnonce=\"" + this.cnonce + "\"";
}
@Override
public MockHttpServletRequest postProcessRequest(MockHttpServletRequest request) {
request.addHeader("Authorization", createAuthorizationHeader(request));
return request;
}
/**
* Computes the <code>response</code> portion of a Digest authentication header.
* Both the server and user agent should compute the <code>response</code>
* independently. Provided as a static method to simplify the coding of user
* agents.
* @param username the user's login name.
* @param realm the name of the realm.
* @param password the user's password in plaintext or ready-encoded.
* @param httpMethod the HTTP request method (GET, POST etc.)
* @param uri the request URI.
* @param qop the qop directive, or null if not set.
* @param nonce the nonce supplied by the server
* @param nc the "nonce-count" as defined in RFC 2617.
* @param cnonce opaque string supplied by the client when qop is set.
* @return the MD5 of the digest authentication response, encoded in hex
* @throws IllegalArgumentException if the supplied qop value is unsupported.
*/
private static String generateDigest(String username, String realm, String password, String httpMethod,
String uri, String qop, String nonce, String nc, String cnonce) throws IllegalArgumentException {
String a1Md5 = encodePasswordInA1Format(username, realm, password);
String a2 = httpMethod + ":" + uri;
String a2Md5 = md5Hex(a2);
if (qop == null) {
// as per RFC 2069 compliant clients (also reaffirmed by RFC 2617)
return md5Hex(a1Md5 + ":" + nonce + ":" + a2Md5);
}
if ("auth".equals(qop)) {
// As per RFC 2617 compliant clients
return md5Hex(a1Md5 + ":" + nonce + ":" + nc + ":" + cnonce + ":" + qop + ":" + a2Md5);
}
throw new IllegalArgumentException("This method does not support a qop: '" + qop + "'");
}
static String encodePasswordInA1Format(String username, String realm, String password) {
return md5Hex(username + ":" + realm + ":" + password);
}
private static String md5Hex(String a2) {
return DigestUtils.md5DigestAsHex(a2.getBytes(StandardCharsets.UTF_8));
}
}
/**
* Support class for {@link RequestPostProcessor}'s that establish a Spring Security
* context
*/
private abstract static class SecurityContextRequestPostProcessorSupport {
/**
* Saves the specified {@link Authentication} into an empty
* {@link SecurityContext} using the {@link SecurityContextRepository}.
* @param authentication the {@link Authentication} to save
* @param request the {@link HttpServletRequest} to use
*/
final void save(Authentication authentication, HttpServletRequest request) {
SecurityContext securityContext = getSecurityContextHolderStrategy(request).createEmptyContext();
securityContext.setAuthentication(authentication);
save(securityContext, request);
}
/**
* Saves the {@link SecurityContext} using the {@link SecurityContextRepository}
* @param securityContext the {@link SecurityContext} to save
* @param request the {@link HttpServletRequest} to use
*/
final void save(SecurityContext securityContext, HttpServletRequest request) {
SecurityContextRepository securityContextRepository = WebTestUtils.getSecurityContextRepository(request);
boolean isTestRepository = securityContextRepository instanceof TestSecurityContextRepository;
if (!isTestRepository) {
securityContextRepository = new TestSecurityContextRepository(securityContextRepository);
WebTestUtils.setSecurityContextRepository(request, securityContextRepository);
}
HttpServletResponse response = new MockHttpServletResponse();
HttpRequestResponseHolder requestResponseHolder = new HttpRequestResponseHolder(request, response);
securityContextRepository.loadContext(requestResponseHolder);
request = requestResponseHolder.getRequest();
response = requestResponseHolder.getResponse();
securityContextRepository.saveContext(securityContext, request, response);
}
/**
* Used to wrap the SecurityContextRepository to provide support for testing in
* stateless mode
*/
static final class TestSecurityContextRepository implements SecurityContextRepository {
private static final String ATTR_NAME = TestSecurityContextRepository.class.getName().concat(".REPO");
private final SecurityContextRepository delegate;
private TestSecurityContextRepository(SecurityContextRepository delegate) {
this.delegate = delegate;
}
@Override
public SecurityContext loadContext(HttpRequestResponseHolder requestResponseHolder) {
SecurityContext result = getContext(requestResponseHolder.getRequest());
// always load from the delegate to ensure the request/response in the
// holder are updated
// remember the SecurityContextRepository is used in many different
// locations
SecurityContext delegateResult = this.delegate.loadContext(requestResponseHolder);
return (result != null) ? result : delegateResult;
}
@Override
public void saveContext(SecurityContext context, HttpServletRequest request, HttpServletResponse response) {
request.setAttribute(ATTR_NAME, context);
this.delegate.saveContext(context, request, response);
}
@Override
public boolean containsContext(HttpServletRequest request) {
return getContext(request) != null || this.delegate.containsContext(request);
}
private static SecurityContext getContext(HttpServletRequest request) {
return (SecurityContext) request.getAttribute(ATTR_NAME);
}
}
}
/**
* Associates the {@link SecurityContext} found in
* {@link TestSecurityContextHolder#getContext()} with the
* {@link MockHttpServletRequest}.
*
* @author Rob Winch
* @since 4.0
*/
private static final class TestSecurityContextHolderPostProcessor extends SecurityContextRequestPostProcessorSupport
implements RequestPostProcessor {
@Override
public MockHttpServletRequest postProcessRequest(MockHttpServletRequest request) {
// TestSecurityContextHolder is only a default value
SecurityContext existingContext = TestSecurityContextRepository.getContext(request);
if (existingContext != null) {
return request;
}
SecurityContextHolderStrategy strategy = getSecurityContextHolderStrategy(request);
SecurityContext empty = strategy.createEmptyContext();
SecurityContext context = strategy.getContext();
if (!empty.equals(context)) {
save(context, request);
}
return request;
}
}
/**
* Associates the specified {@link SecurityContext} with the
* {@link MockHttpServletRequest}.
*
* @author Rob Winch
* @since 4.0
*/
private static final class SecurityContextRequestPostProcessor extends SecurityContextRequestPostProcessorSupport
implements RequestPostProcessor {
private final SecurityContext securityContext;
private SecurityContextRequestPostProcessor(SecurityContext securityContext) {
this.securityContext = securityContext;
}
@Override
public MockHttpServletRequest postProcessRequest(MockHttpServletRequest request) {
save(this.securityContext, request);
return request;
}
}
/**
* Sets the specified {@link Authentication} on an empty {@link SecurityContext} and
* associates it to the {@link MockHttpServletRequest}
*
* @author Rob Winch
* @since 4.0
*
*/
private static final class AuthenticationRequestPostProcessor extends SecurityContextRequestPostProcessorSupport
implements RequestPostProcessor {
private final Authentication authentication;
private AuthenticationRequestPostProcessor(Authentication authentication) {
this.authentication = authentication;
}
@Override
public MockHttpServletRequest postProcessRequest(MockHttpServletRequest request) {
SecurityContext context = getSecurityContextHolderStrategy(request).createEmptyContext();
context.setAuthentication(this.authentication);
save(this.authentication, request);
return request;
}
}
/**
* Creates a {@link UsernamePasswordAuthenticationToken} and sets the
* {@link UserDetails} as the principal and associates it to the
* {@link MockHttpServletRequest}.
*
* @author Rob Winch
* @since 4.0
*/
private static final class UserDetailsRequestPostProcessor implements RequestPostProcessor {
private final AuthenticationRequestPostProcessor delegate;
UserDetailsRequestPostProcessor(UserDetails user) {
Authentication token = UsernamePasswordAuthenticationToken.authenticated(user, user.getPassword(),
user.getAuthorities());
this.delegate = new AuthenticationRequestPostProcessor(token);
}
@Override
public MockHttpServletRequest postProcessRequest(MockHttpServletRequest request) {
return this.delegate.postProcessRequest(request);
}
}
/**
* Creates a {@link UsernamePasswordAuthenticationToken} and sets the principal to be
* a {@link User} and associates it to the {@link MockHttpServletRequest}.
*
* @author Rob Winch
* @since 4.0
*/
public static final class UserRequestPostProcessor extends SecurityContextRequestPostProcessorSupport
implements RequestPostProcessor {
private String username;
private String password = "password";
private static final String ROLE_PREFIX = "ROLE_";
private Collection<? extends GrantedAuthority> authorities = AuthorityUtils.createAuthorityList("ROLE_USER");
private boolean enabled = true;
private boolean accountNonExpired = true;
private boolean credentialsNonExpired = true;
private boolean accountNonLocked = true;
/**
* Creates a new instance with the given username
* @param username the username to use
*/
private UserRequestPostProcessor(String username) {
Assert.notNull(username, "username cannot be null");
this.username = username;
}
/**
* Specify the roles of the user to authenticate as. This method is similar to
* {@link #authorities(GrantedAuthority...)}, but just not as flexible.
* @param roles The roles to populate. Note that if the role does not start with
* {@link #ROLE_PREFIX} it will automatically be prepended. This means by default
* {@code roles("ROLE_USER")} and {@code roles("USER")} are equivalent.
* @return the UserRequestPostProcessor for further customizations
* @see #authorities(GrantedAuthority...)
* @see #ROLE_PREFIX
*/
public UserRequestPostProcessor roles(String... roles) {
List<GrantedAuthority> authorities = new ArrayList<>(roles.length);
for (String role : roles) {
Assert.isTrue(!role.startsWith(ROLE_PREFIX), () -> "Role should not start with " + ROLE_PREFIX
+ " since this method automatically prefixes with this value. Got " + role);
authorities.add(new SimpleGrantedAuthority(ROLE_PREFIX + role));
}
this.authorities = authorities;
return this;
}
/**
* Populates the user's {@link GrantedAuthority}'s. The default is ROLE_USER.
* @param authorities
* @return the UserRequestPostProcessor for further customizations
* @see #roles(String...)
*/
public UserRequestPostProcessor authorities(GrantedAuthority... authorities) {
return authorities(Arrays.asList(authorities));
}
/**
* Populates the user's {@link GrantedAuthority}'s. The default is ROLE_USER.
* @param authorities
* @return the UserRequestPostProcessor for further customizations
* @see #roles(String...)
*/
public UserRequestPostProcessor authorities(Collection<? extends GrantedAuthority> authorities) {
this.authorities = authorities;
return this;
}
/**
* Populates the user's password. The default is "password"
* @param password the user's password
* @return the UserRequestPostProcessor for further customizations
*/
public UserRequestPostProcessor password(String password) {
this.password = password;
return this;
}
@Override
public MockHttpServletRequest postProcessRequest(MockHttpServletRequest request) {
UserDetailsRequestPostProcessor delegate = new UserDetailsRequestPostProcessor(createUser());
return delegate.postProcessRequest(request);
}
/**
* Creates a new {@link User}
* @return the {@link User} for the principal
*/
private User createUser() {
return new User(this.username, this.password, this.enabled, this.accountNonExpired,
this.credentialsNonExpired, this.accountNonLocked, this.authorities);
}
}
private static class AnonymousRequestPostProcessor extends SecurityContextRequestPostProcessorSupport
implements RequestPostProcessor {
private AuthenticationRequestPostProcessor delegate = new AuthenticationRequestPostProcessor(
new AnonymousAuthenticationToken("key", "anonymous",
AuthorityUtils.createAuthorityList("ROLE_ANONYMOUS")));
@Override
public MockHttpServletRequest postProcessRequest(MockHttpServletRequest request) {
return this.delegate.postProcessRequest(request);
}
}
private static final class HttpBasicRequestPostProcessor implements RequestPostProcessor {
private String headerValue;
private HttpBasicRequestPostProcessor(String username, String password) {
byte[] toEncode = (username + ":" + password).getBytes(StandardCharsets.UTF_8);
this.headerValue = "Basic " + new String(Base64.getEncoder().encode(toEncode));
}
@Override
public MockHttpServletRequest postProcessRequest(MockHttpServletRequest request) {
request.addHeader("Authorization", this.headerValue);
return request;
}
}
/**
* @author Jérôme Wacongne <ch4mp@c4-soft.com>
* @author Josh Cummings
* @since 5.2
*/
public static final class JwtRequestPostProcessor implements RequestPostProcessor {
private Jwt jwt;
private Converter<Jwt, Collection<GrantedAuthority>> authoritiesConverter = new JwtGrantedAuthoritiesConverter();
private JwtRequestPostProcessor() {
this.jwt((jwt) -> {
});
}
/**
* Use the given {@link Jwt.Builder} {@link Consumer} to configure the underlying
* {@link Jwt}
*
* This method first creates a default {@link Jwt.Builder} instance with default
* values for the {@code alg}, {@code sub}, and {@code scope} claims. The
* {@link Consumer} can then modify these or provide additional configuration.
*
* Calling {@link SecurityMockMvcRequestPostProcessors#jwt()} is the equivalent of
* calling {@code SecurityMockMvcRequestPostProcessors.jwt().jwt(() -> {})}.
* @param jwtBuilderConsumer For configuring the underlying {@link Jwt}
* @return the {@link JwtRequestPostProcessor} for additional customization
*/
public JwtRequestPostProcessor jwt(Consumer<Jwt.Builder> jwtBuilderConsumer) {
Jwt.Builder jwtBuilder = Jwt.withTokenValue("token").header("alg", "none").claim(JwtClaimNames.SUB, "user")
.claim("scope", "read");
jwtBuilderConsumer.accept(jwtBuilder);
this.jwt = jwtBuilder.build();
return this;
}
/**
* Use the given {@link Jwt}
* @param jwt The {@link Jwt} to use
* @return the {@link JwtRequestPostProcessor} for additional customization
*/
public JwtRequestPostProcessor jwt(Jwt jwt) {
this.jwt = jwt;
return this;
}
/**
* Use the provided authorities in the token
* @param authorities the authorities to use
* @return the {@link JwtRequestPostProcessor} for further configuration
*/
public JwtRequestPostProcessor authorities(Collection<GrantedAuthority> authorities) {
Assert.notNull(authorities, "authorities cannot be null");
this.authoritiesConverter = (jwt) -> authorities;
return this;
}
/**
* Use the provided authorities in the token
* @param authorities the authorities to use
* @return the {@link JwtRequestPostProcessor} for further configuration
*/
public JwtRequestPostProcessor authorities(GrantedAuthority... authorities) {
Assert.notNull(authorities, "authorities cannot be null");
this.authoritiesConverter = (jwt) -> Arrays.asList(authorities);
return this;
}
/**
* Provides the configured {@link Jwt} so that custom authorities can be derived
* from it
* @param authoritiesConverter the conversion strategy from {@link Jwt} to a
* {@link Collection} of {@link GrantedAuthority}s
* @return the {@link JwtRequestPostProcessor} for further configuration
*/
public JwtRequestPostProcessor authorities(Converter<Jwt, Collection<GrantedAuthority>> authoritiesConverter) {
Assert.notNull(authoritiesConverter, "authoritiesConverter cannot be null");
this.authoritiesConverter = authoritiesConverter;
return this;
}
@Override
public MockHttpServletRequest postProcessRequest(MockHttpServletRequest request) {
CsrfFilter.skipRequest(request);
JwtAuthenticationToken token = new JwtAuthenticationToken(this.jwt,
this.authoritiesConverter.convert(this.jwt));
return new AuthenticationRequestPostProcessor(token).postProcessRequest(request);
}
}
/**
* @author Josh Cummings
* @since 5.3
*/
public static final class OpaqueTokenRequestPostProcessor implements RequestPostProcessor {
private Supplier<Map<String, Object>> attributes = this::defaultAttributes;
private Supplier<Collection<GrantedAuthority>> authorities = this::defaultAuthorities;
private Supplier<OAuth2AuthenticatedPrincipal> principal = this::defaultPrincipal;
private OpaqueTokenRequestPostProcessor() {
}
/**
* Mutate the attributes using the given {@link Consumer}
* @param attributesConsumer The {@link Consumer} for mutating the {@Map} of
* attributes
* @return the {@link OpaqueTokenRequestPostProcessor} for further configuration
*/
public OpaqueTokenRequestPostProcessor attributes(Consumer<Map<String, Object>> attributesConsumer) {
Assert.notNull(attributesConsumer, "attributesConsumer cannot be null");
this.attributes = () -> {
Map<String, Object> attributes = defaultAttributes();
attributesConsumer.accept(attributes);
return attributes;
};
this.principal = this::defaultPrincipal;
return this;
}
/**
* Use the provided authorities in the resulting principal
* @param authorities the authorities to use
* @return the {@link OpaqueTokenRequestPostProcessor} for further configuration
*/
public OpaqueTokenRequestPostProcessor authorities(Collection<GrantedAuthority> authorities) {
Assert.notNull(authorities, "authorities cannot be null");
this.authorities = () -> authorities;
this.principal = this::defaultPrincipal;
return this;
}
/**
* Use the provided authorities in the resulting principal
* @param authorities the authorities to use
* @return the {@link OpaqueTokenRequestPostProcessor} for further configuration
*/
public OpaqueTokenRequestPostProcessor authorities(GrantedAuthority... authorities) {
Assert.notNull(authorities, "authorities cannot be null");
this.authorities = () -> Arrays.asList(authorities);
this.principal = this::defaultPrincipal;
return this;
}
/**
* Use the provided principal
* @param principal the principal to use
* @return the {@link OpaqueTokenRequestPostProcessor} for further configuration
*/
public OpaqueTokenRequestPostProcessor principal(OAuth2AuthenticatedPrincipal principal) {
Assert.notNull(principal, "principal cannot be null");
this.principal = () -> principal;
return this;
}
@Override
public MockHttpServletRequest postProcessRequest(MockHttpServletRequest request) {
CsrfFilter.skipRequest(request);
OAuth2AuthenticatedPrincipal principal = this.principal.get();
OAuth2AccessToken accessToken = getOAuth2AccessToken(principal);
BearerTokenAuthentication token = new BearerTokenAuthentication(principal, accessToken,
principal.getAuthorities());
return new AuthenticationRequestPostProcessor(token).postProcessRequest(request);
}
private Map<String, Object> defaultAttributes() {
Map<String, Object> attributes = new HashMap<>();
attributes.put(OAuth2TokenIntrospectionClaimNames.SUB, "user");
attributes.put(OAuth2TokenIntrospectionClaimNames.SCOPE, "read");
return attributes;
}
private Collection<GrantedAuthority> defaultAuthorities() {
Map<String, Object> attributes = this.attributes.get();
Object scope = attributes.get(OAuth2TokenIntrospectionClaimNames.SCOPE);
if (scope == null) {
return Collections.emptyList();
}
if (scope instanceof Collection) {
return getAuthorities((Collection) scope);
}
String scopes = scope.toString();
if (!StringUtils.hasText(scopes)) {
return Collections.emptyList();
}
return getAuthorities(Arrays.asList(scopes.split(" ")));
}
private OAuth2AuthenticatedPrincipal defaultPrincipal() {
return new OAuth2IntrospectionAuthenticatedPrincipal(this.attributes.get(), this.authorities.get());
}
private Collection<GrantedAuthority> getAuthorities(Collection<?> scopes) {
return scopes.stream().map((scope) -> new SimpleGrantedAuthority("SCOPE_" + scope))
.collect(Collectors.toList());
}
private OAuth2AccessToken getOAuth2AccessToken(OAuth2AuthenticatedPrincipal principal) {
Instant expiresAt = getInstant(principal.getAttributes(), "exp");
Instant issuedAt = getInstant(principal.getAttributes(), "iat");
return new OAuth2AccessToken(OAuth2AccessToken.TokenType.BEARER, "token", issuedAt, expiresAt);
}
private Instant getInstant(Map<String, Object> attributes, String name) {
Object value = attributes.get(name);
if (value == null) {
return null;
}
if (value instanceof Instant) {
return (Instant) value;
}
throw new IllegalArgumentException(name + " attribute must be of type Instant");
}
}
/**
* @author Josh Cummings
* @since 5.3
*/
public static final class OAuth2LoginRequestPostProcessor implements RequestPostProcessor {
private final String nameAttributeKey = "sub";
private ClientRegistration clientRegistration;
private OAuth2AccessToken accessToken;
private Supplier<Collection<GrantedAuthority>> authorities = this::defaultAuthorities;
private Supplier<Map<String, Object>> attributes = this::defaultAttributes;
private Supplier<OAuth2User> oauth2User = this::defaultPrincipal;
private OAuth2LoginRequestPostProcessor(OAuth2AccessToken accessToken) {
this.accessToken = accessToken;
this.clientRegistration = clientRegistrationBuilder().build();
}
/**
* Use the provided authorities in the {@link Authentication}
* @param authorities the authorities to use
* @return the {@link OAuth2LoginRequestPostProcessor} for further configuration
*/
public OAuth2LoginRequestPostProcessor authorities(Collection<GrantedAuthority> authorities) {
Assert.notNull(authorities, "authorities cannot be null");
this.authorities = () -> authorities;
this.oauth2User = this::defaultPrincipal;
return this;
}
/**
* Use the provided authorities in the {@link Authentication}
* @param authorities the authorities to use
* @return the {@link OAuth2LoginRequestPostProcessor} for further configuration
*/
public OAuth2LoginRequestPostProcessor authorities(GrantedAuthority... authorities) {
Assert.notNull(authorities, "authorities cannot be null");
this.authorities = () -> Arrays.asList(authorities);
this.oauth2User = this::defaultPrincipal;
return this;
}
/**
* Mutate the attributes using the given {@link Consumer}
* @param attributesConsumer The {@link Consumer} for mutating the {@Map} of
* attributes
* @return the {@link OAuth2LoginRequestPostProcessor} for further configuration
*/
public OAuth2LoginRequestPostProcessor attributes(Consumer<Map<String, Object>> attributesConsumer) {
Assert.notNull(attributesConsumer, "attributesConsumer cannot be null");
this.attributes = () -> {
Map<String, Object> attributes = defaultAttributes();
attributesConsumer.accept(attributes);
return attributes;
};
this.oauth2User = this::defaultPrincipal;
return this;
}
/**
* Use the provided {@link OAuth2User} as the authenticated user.
* @param oauth2User the {@link OAuth2User} to use
* @return the {@link OAuth2LoginRequestPostProcessor} for further configuration
*/
public OAuth2LoginRequestPostProcessor oauth2User(OAuth2User oauth2User) {
this.oauth2User = () -> oauth2User;
return this;
}
/**
* Use the provided {@link ClientRegistration} as the client to authorize.
*
* The supplied {@link ClientRegistration} will be registered into an
* {@link OAuth2AuthorizedClientRepository}.
* @param clientRegistration the {@link ClientRegistration} to use
* @return the {@link OAuth2LoginRequestPostProcessor} for further configuration
*/
public OAuth2LoginRequestPostProcessor clientRegistration(ClientRegistration clientRegistration) {
this.clientRegistration = clientRegistration;
return this;
}
@Override
public MockHttpServletRequest postProcessRequest(MockHttpServletRequest request) {
OAuth2User oauth2User = this.oauth2User.get();
OAuth2AuthenticationToken token = new OAuth2AuthenticationToken(oauth2User, oauth2User.getAuthorities(),
this.clientRegistration.getRegistrationId());
request = new AuthenticationRequestPostProcessor(token).postProcessRequest(request);
return new OAuth2ClientRequestPostProcessor().clientRegistration(this.clientRegistration)
.principalName(oauth2User.getName()).accessToken(this.accessToken).postProcessRequest(request);
}
private ClientRegistration.Builder clientRegistrationBuilder() {
return ClientRegistration.withRegistrationId("test").authorizationGrantType(AuthorizationGrantType.PASSWORD)
.clientId("test-client").tokenUri("https://token-uri.example.org");
}
private Collection<GrantedAuthority> defaultAuthorities() {
Set<GrantedAuthority> authorities = new LinkedHashSet<>();
authorities.add(new OAuth2UserAuthority(this.attributes.get()));
for (String authority : this.accessToken.getScopes()) {
authorities.add(new SimpleGrantedAuthority("SCOPE_" + authority));
}
return authorities;
}
private Map<String, Object> defaultAttributes() {
Map<String, Object> attributes = new HashMap<>();
attributes.put(this.nameAttributeKey, "user");
return attributes;
}
private OAuth2User defaultPrincipal() {
return new DefaultOAuth2User(this.authorities.get(), this.attributes.get(), this.nameAttributeKey);
}
}
/**
* @author Josh Cummings
* @since 5.3
*/
public static final class OidcLoginRequestPostProcessor implements RequestPostProcessor {
private ClientRegistration clientRegistration;
private OAuth2AccessToken accessToken;
private OidcIdToken idToken;
private OidcUserInfo userInfo;
private Supplier<OidcUser> oidcUser = this::defaultPrincipal;
private Collection<GrantedAuthority> authorities;
private OidcLoginRequestPostProcessor(OAuth2AccessToken accessToken) {
this.accessToken = accessToken;
this.clientRegistration = clientRegistrationBuilder().build();
}
/**
* Use the provided authorities in the {@link Authentication}
* @param authorities the authorities to use
* @return the {@link OidcLoginRequestPostProcessor} for further configuration
*/
public OidcLoginRequestPostProcessor authorities(Collection<GrantedAuthority> authorities) {
Assert.notNull(authorities, "authorities cannot be null");
this.authorities = authorities;
this.oidcUser = this::defaultPrincipal;
return this;
}
/**
* Use the provided authorities in the {@link Authentication}
* @param authorities the authorities to use
* @return the {@link OidcLoginRequestPostProcessor} for further configuration
*/
public OidcLoginRequestPostProcessor authorities(GrantedAuthority... authorities) {
Assert.notNull(authorities, "authorities cannot be null");
this.authorities = Arrays.asList(authorities);
this.oidcUser = this::defaultPrincipal;
return this;
}
/**
* Use the provided {@link OidcIdToken} when constructing the authenticated user
* @param idTokenBuilderConsumer a {@link Consumer} of a
* {@link OidcIdToken.Builder}
* @return the {@link OidcLoginRequestPostProcessor} for further configuration
*/
public OidcLoginRequestPostProcessor idToken(Consumer<OidcIdToken.Builder> idTokenBuilderConsumer) {
OidcIdToken.Builder builder = OidcIdToken.withTokenValue("id-token");
builder.subject("user");
idTokenBuilderConsumer.accept(builder);
this.idToken = builder.build();
this.oidcUser = this::defaultPrincipal;
return this;
}
/**
* Use the provided {@link OidcUserInfo} when constructing the authenticated user
* @param userInfoBuilderConsumer a {@link Consumer} of a
* {@link OidcUserInfo.Builder}
* @return the {@link OidcLoginRequestPostProcessor} for further configuration
*/
public OidcLoginRequestPostProcessor userInfoToken(Consumer<OidcUserInfo.Builder> userInfoBuilderConsumer) {
OidcUserInfo.Builder builder = OidcUserInfo.builder();
userInfoBuilderConsumer.accept(builder);
this.userInfo = builder.build();
this.oidcUser = this::defaultPrincipal;
return this;
}
/**
* Use the provided {@link OidcUser} as the authenticated user.
* @param oidcUser the {@link OidcUser} to use
* @return the {@link OidcLoginRequestPostProcessor} for further configuration
*/
public OidcLoginRequestPostProcessor oidcUser(OidcUser oidcUser) {
this.oidcUser = () -> oidcUser;
return this;
}
/**
* Use the provided {@link ClientRegistration} as the client to authorize.
*
* The supplied {@link ClientRegistration} will be registered into an
* {@link HttpSessionOAuth2AuthorizedClientRepository}.
* @param clientRegistration the {@link ClientRegistration} to use
* @return the {@link OidcLoginRequestPostProcessor} for further configuration
*/
public OidcLoginRequestPostProcessor clientRegistration(ClientRegistration clientRegistration) {
this.clientRegistration = clientRegistration;
return this;
}
@Override
public MockHttpServletRequest postProcessRequest(MockHttpServletRequest request) {
OidcUser oidcUser = this.oidcUser.get();
return new OAuth2LoginRequestPostProcessor(this.accessToken).oauth2User(oidcUser)
.clientRegistration(this.clientRegistration).postProcessRequest(request);
}
private ClientRegistration.Builder clientRegistrationBuilder() {
return ClientRegistration.withRegistrationId("test").authorizationGrantType(AuthorizationGrantType.PASSWORD)
.clientId("test-client").tokenUri("https://token-uri.example.org");
}
private Collection<GrantedAuthority> getAuthorities() {
if (this.authorities != null) {
return this.authorities;
}
Set<GrantedAuthority> authorities = new LinkedHashSet<>();
authorities.add(new OidcUserAuthority(getOidcIdToken(), getOidcUserInfo()));
for (String authority : this.accessToken.getScopes()) {
authorities.add(new SimpleGrantedAuthority("SCOPE_" + authority));
}
return authorities;
}
private OidcIdToken getOidcIdToken() {
if (this.idToken != null) {
return this.idToken;
}
return new OidcIdToken("id-token", null, null, Collections.singletonMap(IdTokenClaimNames.SUB, "user"));
}
private OidcUserInfo getOidcUserInfo() {
return this.userInfo;
}
private OidcUser defaultPrincipal() {
return new DefaultOidcUser(getAuthorities(), getOidcIdToken(), this.userInfo);
}
}
/**
* @author Josh Cummings
* @since 5.3
*/
public static final class OAuth2ClientRequestPostProcessor implements RequestPostProcessor {
private String registrationId = "test";
private ClientRegistration clientRegistration;
private String principalName = "user";
private OAuth2AccessToken accessToken = new OAuth2AccessToken(OAuth2AccessToken.TokenType.BEARER,
"access-token", null, null, Collections.singleton("read"));
private OAuth2ClientRequestPostProcessor() {
}
private OAuth2ClientRequestPostProcessor(String registrationId) {
this.registrationId = registrationId;
clientRegistration((c) -> {
});
}
/**
* Use this {@link ClientRegistration}
* @param clientRegistration
* @return the {@link OAuth2ClientRequestPostProcessor} for further configuration
*/
public OAuth2ClientRequestPostProcessor clientRegistration(ClientRegistration clientRegistration) {
this.clientRegistration = clientRegistration;
return this;
}
/**
* Use this {@link Consumer} to configure a {@link ClientRegistration}
* @param clientRegistrationConfigurer the {@link ClientRegistration} configurer
* @return the {@link OAuth2ClientRequestPostProcessor} for further configuration
*/
public OAuth2ClientRequestPostProcessor clientRegistration(
Consumer<ClientRegistration.Builder> clientRegistrationConfigurer) {
ClientRegistration.Builder builder = clientRegistrationBuilder();
clientRegistrationConfigurer.accept(builder);
this.clientRegistration = builder.build();
return this;
}
/**
* Use this as the resource owner's principal name
* @param principalName the resource owner's principal name
* @return the {@link OAuth2ClientRequestPostProcessor} for further configuration
*/
public OAuth2ClientRequestPostProcessor principalName(String principalName) {
Assert.notNull(principalName, "principalName cannot be null");
this.principalName = principalName;
return this;
}
/**
* Use this {@link OAuth2AccessToken}
* @param accessToken the {@link OAuth2AccessToken} to use
* @return the {@link OAuth2ClientRequestPostProcessor} for further configuration
*/
public OAuth2ClientRequestPostProcessor accessToken(OAuth2AccessToken accessToken) {
this.accessToken = accessToken;
return this;
}
@Override
public MockHttpServletRequest postProcessRequest(MockHttpServletRequest request) {
if (this.clientRegistration == null) {
throw new IllegalArgumentException(
"Please specify a ClientRegistration via one " + "of the clientRegistration methods");
}
OAuth2AuthorizedClient client = new OAuth2AuthorizedClient(this.clientRegistration, this.principalName,
this.accessToken);
OAuth2AuthorizedClientRepository authorizedClientRepository = OAuth2ClientServletTestUtils
.getAuthorizedClientRepository(request);
if (!(authorizedClientRepository instanceof TestOAuth2AuthorizedClientRepository)) {
authorizedClientRepository = new TestOAuth2AuthorizedClientRepository(authorizedClientRepository);
OAuth2ClientServletTestUtils.setAuthorizedClientRepository(request, authorizedClientRepository);
}
TestOAuth2AuthorizedClientRepository.enable(request);
authorizedClientRepository.saveAuthorizedClient(client, null, request, new MockHttpServletResponse());
return request;
}
private ClientRegistration.Builder clientRegistrationBuilder() {
return ClientRegistration.withRegistrationId(this.registrationId)
.authorizationGrantType(AuthorizationGrantType.PASSWORD).clientId("test-client")
.clientSecret("test-secret").tokenUri("https://idp.example.org/oauth/token");
}
/**
* Used to wrap the {@link OAuth2AuthorizedClientRepository} to provide support
* for testing when the request is wrapped
*/
private static final class TestOAuth2AuthorizedClientManager implements OAuth2AuthorizedClientManager {
static final String ENABLED_ATTR_NAME = TestOAuth2AuthorizedClientManager.class.getName()
.concat(".ENABLED");
private final OAuth2AuthorizedClientManager delegate;
private OAuth2AuthorizedClientRepository authorizedClientRepository;
TestOAuth2AuthorizedClientManager(OAuth2AuthorizedClientManager delegate) {
this.delegate = delegate;
}
@Override
public OAuth2AuthorizedClient authorize(OAuth2AuthorizeRequest authorizeRequest) {
HttpServletRequest request = authorizeRequest.getAttribute(HttpServletRequest.class.getName());
if (isEnabled(request)) {
return this.authorizedClientRepository.loadAuthorizedClient(
authorizeRequest.getClientRegistrationId(), authorizeRequest.getPrincipal(), request);
}
return this.delegate.authorize(authorizeRequest);
}
static void enable(HttpServletRequest request) {
request.setAttribute(ENABLED_ATTR_NAME, Boolean.TRUE);
}
boolean isEnabled(HttpServletRequest request) {
return Boolean.TRUE.equals(request.getAttribute(ENABLED_ATTR_NAME));
}
}
/**
* Used to wrap the {@link OAuth2AuthorizedClientRepository} to provide support
* for testing when the request is wrapped
*/
static final class TestOAuth2AuthorizedClientRepository implements OAuth2AuthorizedClientRepository {
static final String TOKEN_ATTR_NAME = TestOAuth2AuthorizedClientRepository.class.getName().concat(".TOKEN");
static final String ENABLED_ATTR_NAME = TestOAuth2AuthorizedClientRepository.class.getName()
.concat(".ENABLED");
private final OAuth2AuthorizedClientRepository delegate;
TestOAuth2AuthorizedClientRepository(OAuth2AuthorizedClientRepository delegate) {
this.delegate = delegate;
}
@Override
public <T extends OAuth2AuthorizedClient> T loadAuthorizedClient(String clientRegistrationId,
Authentication principal, HttpServletRequest request) {
if (isEnabled(request)) {
return (T) request.getAttribute(TOKEN_ATTR_NAME);
}
return this.delegate.loadAuthorizedClient(clientRegistrationId, principal, request);
}
@Override
public void saveAuthorizedClient(OAuth2AuthorizedClient authorizedClient, Authentication principal,
HttpServletRequest request, HttpServletResponse response) {
if (isEnabled(request)) {
request.setAttribute(TOKEN_ATTR_NAME, authorizedClient);
return;
}
this.delegate.saveAuthorizedClient(authorizedClient, principal, request, response);
}
@Override
public void removeAuthorizedClient(String clientRegistrationId, Authentication principal,
HttpServletRequest request, HttpServletResponse response) {
if (isEnabled(request)) {
request.removeAttribute(TOKEN_ATTR_NAME);
return;
}
this.delegate.removeAuthorizedClient(clientRegistrationId, principal, request, response);
}
static void enable(HttpServletRequest request) {
request.setAttribute(ENABLED_ATTR_NAME, Boolean.TRUE);
}
boolean isEnabled(HttpServletRequest request) {
return Boolean.TRUE.equals(request.getAttribute(ENABLED_ATTR_NAME));
}
}
private static final class OAuth2ClientServletTestUtils {
private static final OAuth2AuthorizedClientRepository DEFAULT_CLIENT_REPO = new HttpSessionOAuth2AuthorizedClientRepository();
private OAuth2ClientServletTestUtils() {
}
/**
* Gets the {@link OAuth2AuthorizedClientRepository} for the specified
* {@link HttpServletRequest}. If one is not found, one based off of
* {@link HttpSessionOAuth2AuthorizedClientRepository} is used.
* @param request the {@link HttpServletRequest} to obtain the
* {@link OAuth2AuthorizedClientManager}
* @return the {@link OAuth2AuthorizedClientManager} for the specified
* {@link HttpServletRequest}
*/
static OAuth2AuthorizedClientRepository getAuthorizedClientRepository(HttpServletRequest request) {
OAuth2AuthorizedClientManager manager = getOAuth2AuthorizedClientManager(request);
if (manager == null) {
return DEFAULT_CLIENT_REPO;
}
if (manager instanceof DefaultOAuth2AuthorizedClientManager) {
return (OAuth2AuthorizedClientRepository) ReflectionTestUtils.getField(manager,
"authorizedClientRepository");
}
if (manager instanceof TestOAuth2AuthorizedClientManager) {
return ((TestOAuth2AuthorizedClientManager) manager).authorizedClientRepository;
}
return DEFAULT_CLIENT_REPO;
}
static void setAuthorizedClientRepository(HttpServletRequest request,
OAuth2AuthorizedClientRepository repository) {
OAuth2AuthorizedClientManager manager = getOAuth2AuthorizedClientManager(request);
if (manager == null) {
return;
}
if (manager instanceof DefaultOAuth2AuthorizedClientManager) {
ReflectionTestUtils.setField(manager, "authorizedClientRepository", repository);
return;
}
if (!(manager instanceof TestOAuth2AuthorizedClientManager)) {
manager = new TestOAuth2AuthorizedClientManager(manager);
setOAuth2AuthorizedClientManager(request, manager);
}
TestOAuth2AuthorizedClientManager.enable(request);
((TestOAuth2AuthorizedClientManager) manager).authorizedClientRepository = repository;
}
static OAuth2AuthorizedClientManager getOAuth2AuthorizedClientManager(HttpServletRequest request) {
OAuth2AuthorizedClientArgumentResolver resolver = findResolver(request,
OAuth2AuthorizedClientArgumentResolver.class);
if (resolver == null) {
return null;
}
return (OAuth2AuthorizedClientManager) ReflectionTestUtils.getField(resolver,
"authorizedClientManager");
}
/**
* Sets the {@link OAuth2AuthorizedClientManager} for the specified
* {@link HttpServletRequest}.
* @param request the {@link HttpServletRequest} to obtain the
* {@link OAuth2AuthorizedClientManager}
* @param manager the {@link OAuth2AuthorizedClientManager} to set
*/
static void setOAuth2AuthorizedClientManager(HttpServletRequest request,
OAuth2AuthorizedClientManager manager) {
OAuth2AuthorizedClientArgumentResolver resolver = findResolver(request,
OAuth2AuthorizedClientArgumentResolver.class);
if (resolver == null) {
return;
}
ReflectionTestUtils.setField(resolver, "authorizedClientManager", manager);
}
@SuppressWarnings("unchecked")
static <T extends HandlerMethodArgumentResolver> T findResolver(HttpServletRequest request,
Class<T> resolverClass) {
if (!ClassUtils.isPresent(
"org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter", null)) {
return null;
}
return WebMvcClasspathGuard.findResolver(request, resolverClass);
}
private static class WebMvcClasspathGuard {
static <T extends HandlerMethodArgumentResolver> T findResolver(HttpServletRequest request,
Class<T> resolverClass) {
ServletContext servletContext = request.getServletContext();
RequestMappingHandlerAdapter mapping = getRequestMappingHandlerAdapter(servletContext);
if (mapping == null) {
return null;
}
List<HandlerMethodArgumentResolver> resolvers = mapping.getCustomArgumentResolvers();
if (resolvers == null) {
return null;
}
for (HandlerMethodArgumentResolver resolver : resolvers) {
if (resolverClass.isAssignableFrom(resolver.getClass())) {
return (T) resolver;
}
}
return null;
}
private static RequestMappingHandlerAdapter getRequestMappingHandlerAdapter(
ServletContext servletContext) {
WebApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(servletContext);
if (context != null) {
String[] names = context.getBeanNamesForType(RequestMappingHandlerAdapter.class);
if (names.length > 0) {
return (RequestMappingHandlerAdapter) context.getBean(names[0]);
}
}
return null;
}
}
}
}
}
| 70,968 | 37.507325 | 142 | java |
null | spring-security-main/test/src/main/java/org/springframework/security/test/web/servlet/setup/SecurityMockMvcConfigurer.java | /*
* Copyright 2002-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.test.web.servlet.setup;
import java.io.IOException;
import jakarta.servlet.Filter;
import jakarta.servlet.FilterChain;
import jakarta.servlet.FilterConfig;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;
import org.springframework.security.config.BeanIds;
import org.springframework.test.web.servlet.request.RequestPostProcessor;
import org.springframework.test.web.servlet.setup.ConfigurableMockMvcBuilder;
import org.springframework.test.web.servlet.setup.MockMvcConfigurerAdapter;
import org.springframework.util.Assert;
import org.springframework.web.context.WebApplicationContext;
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.testSecurityContext;
/**
* Configures Spring Security by adding the springSecurityFilterChain and adding the
* {@link org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors#testSecurityContext()}
* .
*
* @author Rob Winch
* @since 4.0
*/
final class SecurityMockMvcConfigurer extends MockMvcConfigurerAdapter {
private final DelegateFilter delegateFilter;
/**
* Creates a new instance
*/
SecurityMockMvcConfigurer() {
this.delegateFilter = new DelegateFilter();
}
/**
* Creates a new instance with the provided {@link jakarta.servlet.Filter}
* @param springSecurityFilterChain the {@link jakarta.servlet.Filter} to use
*/
SecurityMockMvcConfigurer(Filter springSecurityFilterChain) {
this.delegateFilter = new DelegateFilter(springSecurityFilterChain);
}
@Override
public void afterConfigurerAdded(ConfigurableMockMvcBuilder<?> builder) {
builder.addFilters(this.delegateFilter);
}
@Override
public RequestPostProcessor beforeMockMvcCreated(ConfigurableMockMvcBuilder<?> builder,
WebApplicationContext context) {
String securityBeanId = BeanIds.SPRING_SECURITY_FILTER_CHAIN;
if (getSpringSecurityFilterChain() == null && context.containsBean(securityBeanId)) {
setSpringSecurityFilterChain(context.getBean(securityBeanId, Filter.class));
}
Assert.state(getSpringSecurityFilterChain() != null,
() -> "springSecurityFilterChain cannot be null. Ensure a Bean with the name " + securityBeanId
+ " implementing Filter is present or inject the Filter to be used.");
// This is used by other test support to obtain the FilterChainProxy
context.getServletContext().setAttribute(BeanIds.SPRING_SECURITY_FILTER_CHAIN, getSpringSecurityFilterChain());
return testSecurityContext();
}
private void setSpringSecurityFilterChain(Filter filter) {
this.delegateFilter.setDelegate(filter);
}
private Filter getSpringSecurityFilterChain() {
return this.delegateFilter.delegate;
}
/**
* Allows adding in {@link #afterConfigurerAdded(ConfigurableMockMvcBuilder)} to
* preserve Filter order and then lazily set the delegate in
* {@link #beforeMockMvcCreated(ConfigurableMockMvcBuilder, WebApplicationContext)}.
*
* {@link org.springframework.web.filter.DelegatingFilterProxy} is not used because it
* is not easy to lazily set the delegate or get the delegate which is necessary for
* the test infrastructure.
*/
static class DelegateFilter implements Filter {
private Filter delegate;
DelegateFilter() {
}
DelegateFilter(Filter delegate) {
this.delegate = delegate;
}
void setDelegate(Filter delegate) {
this.delegate = delegate;
}
Filter getDelegate() {
Filter result = this.delegate;
Assert.state(result != null,
() -> "delegate cannot be null. Ensure a Bean with the name " + BeanIds.SPRING_SECURITY_FILTER_CHAIN
+ " implementing Filter is present or inject the Filter to be used.");
return result;
}
@Override
public void init(FilterConfig filterConfig) throws ServletException {
getDelegate().init(filterConfig);
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
getDelegate().doFilter(request, response, chain);
}
@Override
public void destroy() {
getDelegate().destroy();
}
@Override
public boolean equals(Object obj) {
return getDelegate().equals(obj);
}
@Override
public int hashCode() {
return getDelegate().hashCode();
}
@Override
public String toString() {
return getDelegate().toString();
}
}
}
| 5,060 | 31.031646 | 125 | java |
null | spring-security-main/test/src/main/java/org/springframework/security/test/web/servlet/setup/SecurityMockMvcConfigurers.java | /*
* Copyright 2002-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.test.web.servlet.setup;
import jakarta.servlet.Filter;
import org.springframework.test.web.servlet.setup.MockMvcConfigurer;
import org.springframework.util.Assert;
/**
* Provides Security related
* {@link org.springframework.test.web.servlet.setup.MockMvcConfigurer} implementations.
*
* @author Rob Winch
* @since 4.0
*/
public final class SecurityMockMvcConfigurers {
private SecurityMockMvcConfigurers() {
}
/**
* Configures the MockMvcBuilder for use with Spring Security. Specifically the
* configurer adds the Spring Bean named "springSecurityFilterChain" as a Filter. It
* will also ensure that the TestSecurityContextHolder is leveraged for each request
* by applying
* {@link org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors#testSecurityContext()}
* .
* @return the {@link org.springframework.test.web.servlet.setup.MockMvcConfigurer} to
* use
*/
public static MockMvcConfigurer springSecurity() {
return new SecurityMockMvcConfigurer();
}
/**
* Configures the MockMvcBuilder for use with Spring Security. Specifically the
* configurer adds the provided Filter. It will also ensure that the
* TestSecurityContextHolder is leveraged for each request by applying
* {@link org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors#testSecurityContext()}
* .
* @param springSecurityFilterChain the Filter to be added
* @return the {@link org.springframework.test.web.servlet.setup.MockMvcConfigurer} to
* use
*/
public static MockMvcConfigurer springSecurity(Filter springSecurityFilterChain) {
Assert.notNull(springSecurityFilterChain, "springSecurityFilterChain cannot be null");
return new SecurityMockMvcConfigurer(springSecurityFilterChain);
}
}
| 2,454 | 36.19697 | 124 | java |
null | spring-security-main/test/src/main/java/org/springframework/security/test/web/servlet/response/SecurityMockMvcResultHandlers.java | /*
* Copyright 2002-2021 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.test.web.servlet.response;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.test.context.TestSecurityContextHolder;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.ResultHandler;
/**
* Security related {@link MockMvc} {@link ResultHandler}s
*
* @author Marcus da Coregio
* @since 5.6
*/
public final class SecurityMockMvcResultHandlers {
private SecurityMockMvcResultHandlers() {
}
/**
* Exports the {@link SecurityContext} from {@link TestSecurityContextHolder} to
* {@link SecurityContextHolder}
*/
public static ResultHandler exportTestSecurityContext() {
return new ExportTestSecurityContextHandler();
}
/**
* A {@link ResultHandler} that copies the {@link SecurityContext} from
* {@link TestSecurityContextHolder} to {@link SecurityContextHolder}
*
* @author Marcus da Coregio
* @since 5.6
*/
private static class ExportTestSecurityContextHandler implements ResultHandler {
@Override
public void handle(MvcResult result) {
SecurityContextHolder.setContext(TestSecurityContextHolder.getContext());
}
}
}
| 1,947 | 30.419355 | 81 | java |
null | spring-security-main/test/src/main/java/org/springframework/security/test/web/servlet/response/SecurityMockMvcResultMatchers.java | /*
* Copyright 2002-2014 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.test.web.servlet.response;
import java.util.ArrayList;
import java.util.Collection;
import java.util.function.Consumer;
import org.springframework.security.authentication.AuthenticationTrustResolver;
import org.springframework.security.authentication.AuthenticationTrustResolverImpl;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.test.web.support.WebTestUtils;
import org.springframework.security.web.context.HttpRequestResponseHolder;
import org.springframework.security.web.context.SecurityContextRepository;
import org.springframework.test.util.AssertionErrors;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.ResultMatcher;
/**
* Security related {@link MockMvc} {@link ResultMatcher}s.
*
* @author Rob Winch
* @author Eddú Meléndez
* @since 4.0
*/
public final class SecurityMockMvcResultMatchers {
private SecurityMockMvcResultMatchers() {
}
/**
* {@link ResultMatcher} that verifies that a specified user is authenticated.
* @return the {@link AuthenticatedMatcher} to use
*/
public static AuthenticatedMatcher authenticated() {
return new AuthenticatedMatcher();
}
/**
* {@link ResultMatcher} that verifies that no user is authenticated.
* @return the {@link AuthenticatedMatcher} to use
*/
public static ResultMatcher unauthenticated() {
return new UnAuthenticatedMatcher();
}
private abstract static class AuthenticationMatcher<T extends AuthenticationMatcher<T>> implements ResultMatcher {
protected SecurityContext load(MvcResult result) {
HttpRequestResponseHolder holder = new HttpRequestResponseHolder(result.getRequest(), result.getResponse());
SecurityContextRepository repository = WebTestUtils.getSecurityContextRepository(result.getRequest());
return repository.loadContext(holder);
}
}
/**
* A {@link MockMvc} {@link ResultMatcher} that verifies a specific user is associated
* to the {@link MvcResult}.
*
* @author Rob Winch
* @since 4.0
*/
public static final class AuthenticatedMatcher extends AuthenticationMatcher<AuthenticatedMatcher> {
private SecurityContext expectedContext;
private Authentication expectedAuthentication;
private Object expectedAuthenticationPrincipal;
private String expectedAuthenticationName;
private Collection<? extends GrantedAuthority> expectedGrantedAuthorities;
private Consumer<Authentication> assertAuthentication;
AuthenticatedMatcher() {
}
@Override
public void match(MvcResult result) {
SecurityContext context = load(result);
Authentication auth = context.getAuthentication();
AssertionErrors.assertTrue("Authentication should not be null", auth != null);
if (this.assertAuthentication != null) {
this.assertAuthentication.accept(auth);
}
if (this.expectedContext != null) {
AssertionErrors.assertEquals(this.expectedContext + " does not equal " + context, this.expectedContext,
context);
}
if (this.expectedAuthentication != null) {
AssertionErrors.assertEquals(
this.expectedAuthentication + " does not equal " + context.getAuthentication(),
this.expectedAuthentication, context.getAuthentication());
}
if (this.expectedAuthenticationPrincipal != null) {
AssertionErrors.assertTrue("Authentication cannot be null", context.getAuthentication() != null);
AssertionErrors.assertEquals(
this.expectedAuthenticationPrincipal + " does not equal "
+ context.getAuthentication().getPrincipal(),
this.expectedAuthenticationPrincipal, context.getAuthentication().getPrincipal());
}
if (this.expectedAuthenticationName != null) {
AssertionErrors.assertTrue("Authentication cannot be null", auth != null);
String name = auth.getName();
AssertionErrors.assertEquals(this.expectedAuthenticationName + " does not equal " + name,
this.expectedAuthenticationName, name);
}
if (this.expectedGrantedAuthorities != null) {
AssertionErrors.assertTrue("Authentication cannot be null", auth != null);
Collection<? extends GrantedAuthority> authorities = auth.getAuthorities();
AssertionErrors.assertTrue(
authorities + " does not contain the same authorities as " + this.expectedGrantedAuthorities,
authorities.containsAll(this.expectedGrantedAuthorities));
AssertionErrors.assertTrue(
this.expectedGrantedAuthorities + " does not contain the same authorities as " + authorities,
this.expectedGrantedAuthorities.containsAll(authorities));
}
}
/**
* Allows for any validating the authentication with arbitrary assertions
* @param assertAuthentication the Consumer which validates the authentication
* @return the AuthenticatedMatcher to perform additional assertions
*/
public AuthenticatedMatcher withAuthentication(Consumer<Authentication> assertAuthentication) {
this.assertAuthentication = assertAuthentication;
return this;
}
/**
* Specifies the expected username
* @param expected the expected username
* @return the {@link AuthenticatedMatcher} for further customization
*/
public AuthenticatedMatcher withUsername(String expected) {
return withAuthenticationName(expected);
}
/**
* Specifies the expected {@link SecurityContext}
* @param expected the expected {@link SecurityContext}
* @return the {@link AuthenticatedMatcher} for further customization
*/
public AuthenticatedMatcher withSecurityContext(SecurityContext expected) {
this.expectedContext = expected;
return this;
}
/**
* Specifies the expected {@link Authentication}
* @param expected the expected {@link Authentication}
* @return the {@link AuthenticatedMatcher} for further customization
*/
public AuthenticatedMatcher withAuthentication(Authentication expected) {
this.expectedAuthentication = expected;
return this;
}
/**
* Specifies the expected principal
* @param expected the expected principal
* @return the {@link AuthenticatedMatcher} for further customization
*/
public AuthenticatedMatcher withAuthenticationPrincipal(Object expected) {
this.expectedAuthenticationPrincipal = expected;
return this;
}
/**
* Specifies the expected {@link Authentication#getName()}
* @param expected the expected {@link Authentication#getName()}
* @return the {@link AuthenticatedMatcher} for further customization
*/
public AuthenticatedMatcher withAuthenticationName(String expected) {
this.expectedAuthenticationName = expected;
return this;
}
/**
* Specifies the {@link Authentication#getAuthorities()}
* @param expected the {@link Authentication#getAuthorities()}
* @return the {@link AuthenticatedMatcher} for further customization
*/
public AuthenticatedMatcher withAuthorities(Collection<? extends GrantedAuthority> expected) {
this.expectedGrantedAuthorities = expected;
return this;
}
/**
* Specifies the {@link Authentication#getAuthorities()}
* @param roles the roles. Each value is automatically prefixed with "ROLE_"
* @return the {@link AuthenticatedMatcher} for further customization
*/
public AuthenticatedMatcher withRoles(String... roles) {
Collection<GrantedAuthority> authorities = new ArrayList<>();
for (String role : roles) {
authorities.add(new SimpleGrantedAuthority("ROLE_" + role));
}
return withAuthorities(authorities);
}
}
/**
* A {@link MockMvc} {@link ResultMatcher} that verifies no {@link Authentication} is
* associated with the {@link MvcResult}.
*
* @author Rob Winch
* @since 4.0
*/
private static final class UnAuthenticatedMatcher extends AuthenticationMatcher<UnAuthenticatedMatcher> {
private AuthenticationTrustResolver trustResolver = new AuthenticationTrustResolverImpl();
private UnAuthenticatedMatcher() {
}
@Override
public void match(MvcResult result) {
SecurityContext context = load(result);
Authentication authentication = context.getAuthentication();
AssertionErrors.assertTrue("Expected anonymous Authentication got " + context,
authentication == null || this.trustResolver.isAnonymous(authentication));
}
}
}
| 9,099 | 35.25498 | 115 | java |
null | spring-security-main/test/src/main/java/org/springframework/security/test/context/TestSecurityContextHolder.java | /*
* Copyright 2002-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.test.context;
import jakarta.servlet.FilterChain;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors;
import org.springframework.security.web.context.SecurityContextPersistenceFilter;
import org.springframework.security.web.context.SecurityContextRepository;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.util.Assert;
/**
* The {@link TestSecurityContextHolder} is very similar to {@link SecurityContextHolder},
* but is necessary for testing. For example, we cannot populate the desired
* {@link SecurityContext} in {@link SecurityContextHolder} for web based testing. In a
* web request, the {@link SecurityContextPersistenceFilter} will override the
* {@link SecurityContextHolder} with the value returned by the
* {@link SecurityContextRepository}. At the end of the {@link FilterChain} the
* {@link SecurityContextPersistenceFilter} will clear out the
* {@link SecurityContextHolder}. This means if we make multiple web requests, we will not
* know which {@link SecurityContext} to use on subsequent requests.
*
* Typical usage is as follows:
*
* <ul>
* <li>Before a test is executed, the {@link TestSecurityContextHolder} is populated.
* Typically this is done using the
* {@link org.springframework.security.test.context.support.WithSecurityContextTestExecutionListener}
* </li>
* <li>The test is ran. When used with {@link MockMvc} it is typically used with
* {@link SecurityMockMvcRequestPostProcessors#testSecurityContext()}. Which ensures the
* {@link SecurityContext} from {@link TestSecurityContextHolder} is properly
* populated.</li>
* <li>After the test is executed, the {@link TestSecurityContextHolder} and the
* {@link SecurityContextHolder} are cleared out</li>
* </ul>
*
* @author Rob Winch
* @author Tadaya Tsuyukubo
* @since 4.0
*/
public final class TestSecurityContextHolder {
private static final ThreadLocal<SecurityContext> contextHolder = new ThreadLocal<>();
private TestSecurityContextHolder() {
}
/**
* Clears the {@link SecurityContext} from {@link TestSecurityContextHolder} and
* {@link SecurityContextHolder}.
*/
public static void clearContext() {
contextHolder.remove();
SecurityContextHolder.clearContext();
}
/**
* Gets the {@link SecurityContext} from {@link TestSecurityContextHolder}.
* @return the {@link SecurityContext} from {@link TestSecurityContextHolder}.
*/
public static SecurityContext getContext() {
SecurityContext ctx = contextHolder.get();
if (ctx == null) {
ctx = getDefaultContext();
contextHolder.set(ctx);
}
return ctx;
}
/**
* Sets the {@link SecurityContext} on {@link TestSecurityContextHolder} and
* {@link SecurityContextHolder}.
* @param context the {@link SecurityContext} to use
*/
public static void setContext(SecurityContext context) {
Assert.notNull(context, "Only non-null SecurityContext instances are permitted");
contextHolder.set(context);
SecurityContextHolder.setContext(context);
}
/**
* Creates a new {@link SecurityContext} with the given {@link Authentication}. The
* {@link SecurityContext} is set on {@link TestSecurityContextHolder} and
* {@link SecurityContextHolder}.
* @param authentication the {@link Authentication} to use
* @since 5.1.1
*/
public static void setAuthentication(Authentication authentication) {
Assert.notNull(authentication, "Only non-null Authentication instances are permitted");
SecurityContext context = SecurityContextHolder.createEmptyContext();
context.setAuthentication(authentication);
setContext(context);
}
/**
* Gets the default {@link SecurityContext} by delegating to the
* {@link SecurityContextHolder}
* @return the default {@link SecurityContext}
*/
private static SecurityContext getDefaultContext() {
return SecurityContextHolder.getContext();
}
}
| 4,744 | 37.266129 | 101 | java |
null | spring-security-main/test/src/main/java/org/springframework/security/test/context/TestSecurityContextHolderStrategyAdapter.java | /*
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.test.context;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.context.SecurityContextHolderStrategy;
public final class TestSecurityContextHolderStrategyAdapter implements SecurityContextHolderStrategy {
@Override
public void clearContext() {
TestSecurityContextHolder.clearContext();
}
@Override
public SecurityContext getContext() {
return TestSecurityContextHolder.getContext();
}
@Override
public void setContext(SecurityContext context) {
TestSecurityContextHolder.setContext(context);
}
@Override
public SecurityContext createEmptyContext() {
return SecurityContextHolder.createEmptyContext();
}
}
| 1,422 | 29.934783 | 102 | java |
null | spring-security-main/test/src/main/java/org/springframework/security/test/context/support/WithSecurityContextTestExecutionListener.java | /*
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.test.context.support;
import java.lang.annotation.Annotation;
import java.lang.reflect.AnnotatedElement;
import java.util.function.Supplier;
import org.springframework.beans.BeanUtils;
import org.springframework.context.ApplicationContext;
import org.springframework.core.GenericTypeResolver;
import org.springframework.core.annotation.AnnotatedElementUtils;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.core.convert.converter.Converter;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.context.SecurityContextHolderStrategy;
import org.springframework.security.test.context.TestSecurityContextHolder;
import org.springframework.security.test.context.TestSecurityContextHolderStrategyAdapter;
import org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors;
import org.springframework.test.context.TestContext;
import org.springframework.test.context.TestContextAnnotationUtils;
import org.springframework.test.context.TestExecutionListener;
import org.springframework.test.context.support.AbstractTestExecutionListener;
import org.springframework.test.web.servlet.MockMvc;
/**
* A {@link TestExecutionListener} that will find annotations that are annotated with
* {@link WithSecurityContext} on a test method or at the class level. If found, the
* {@link WithSecurityContext#factory()} is used to create a {@link SecurityContext} that
* will be used with this test. If using with {@link MockMvc} the
* {@link SecurityMockMvcRequestPostProcessors#testSecurityContext()} needs to be used
* too.
*
* @author Rob Winch
* @author Eddú Meléndez
* @since 4.0
* @see ReactorContextTestExecutionListener
* @see org.springframework.security.test.context.annotation.SecurityTestExecutionListeners
*/
public class WithSecurityContextTestExecutionListener extends AbstractTestExecutionListener {
static final String SECURITY_CONTEXT_ATTR_NAME = WithSecurityContextTestExecutionListener.class.getName()
.concat(".SECURITY_CONTEXT");
static final SecurityContextHolderStrategy DEFAULT_SECURITY_CONTEXT_HOLDER_STRATEGY = new TestSecurityContextHolderStrategyAdapter();
Converter<TestContext, SecurityContextHolderStrategy> securityContextHolderStrategyConverter = (testContext) -> {
if (!testContext.hasApplicationContext()) {
return DEFAULT_SECURITY_CONTEXT_HOLDER_STRATEGY;
}
ApplicationContext context = testContext.getApplicationContext();
if (context.getBeanNamesForType(SecurityContextHolderStrategy.class).length == 0) {
return DEFAULT_SECURITY_CONTEXT_HOLDER_STRATEGY;
}
return context.getBean(SecurityContextHolderStrategy.class);
};
/**
* Sets up the {@link SecurityContext} for each test method. First the specific method
* is inspected for a {@link WithSecurityContext} or {@link Annotation} that has
* {@link WithSecurityContext} on it. If that is not found, the class is inspected. If
* still not found, then no {@link SecurityContext} is populated.
*/
@Override
public void beforeTestMethod(TestContext testContext) {
TestSecurityContext testSecurityContext = createTestSecurityContext(testContext.getTestMethod(), testContext);
if (testSecurityContext == null) {
testSecurityContext = createTestSecurityContext(testContext.getTestClass(), testContext);
}
if (testSecurityContext == null) {
return;
}
Supplier<SecurityContext> supplier = testSecurityContext.getSecurityContextSupplier();
if (testSecurityContext.getTestExecutionEvent() == TestExecutionEvent.TEST_METHOD) {
this.securityContextHolderStrategyConverter.convert(testContext).setContext(supplier.get());
}
else {
testContext.setAttribute(SECURITY_CONTEXT_ATTR_NAME, supplier);
}
}
/**
* If configured before test execution sets the SecurityContext
* @since 5.1
*/
@Override
public void beforeTestExecution(TestContext testContext) {
Supplier<SecurityContext> supplier = (Supplier<SecurityContext>) testContext
.removeAttribute(SECURITY_CONTEXT_ATTR_NAME);
if (supplier != null) {
this.securityContextHolderStrategyConverter.convert(testContext).setContext(supplier.get());
}
}
private TestSecurityContext createTestSecurityContext(AnnotatedElement annotated, TestContext context) {
WithSecurityContext withSecurityContext = AnnotatedElementUtils.findMergedAnnotation(annotated,
WithSecurityContext.class);
return createTestSecurityContext(annotated, withSecurityContext, context);
}
private TestSecurityContext createTestSecurityContext(Class<?> annotated, TestContext context) {
TestContextAnnotationUtils.AnnotationDescriptor<WithSecurityContext> withSecurityContextDescriptor = TestContextAnnotationUtils
.findAnnotationDescriptor(annotated, WithSecurityContext.class);
if (withSecurityContextDescriptor == null) {
return null;
}
WithSecurityContext withSecurityContext = withSecurityContextDescriptor.getAnnotation();
Class<?> rootDeclaringClass = withSecurityContextDescriptor.getRootDeclaringClass();
return createTestSecurityContext(rootDeclaringClass, withSecurityContext, context);
}
@SuppressWarnings({ "rawtypes", "unchecked" })
private TestSecurityContext createTestSecurityContext(AnnotatedElement annotated,
WithSecurityContext withSecurityContext, TestContext context) {
if (withSecurityContext == null) {
return null;
}
withSecurityContext = AnnotationUtils.synthesizeAnnotation(withSecurityContext, annotated);
WithSecurityContextFactory factory = createFactory(withSecurityContext, context);
Class<? extends Annotation> type = (Class<? extends Annotation>) GenericTypeResolver
.resolveTypeArgument(factory.getClass(), WithSecurityContextFactory.class);
Annotation annotation = findAnnotation(annotated, type);
Supplier<SecurityContext> supplier = () -> {
try {
return factory.createSecurityContext(annotation);
}
catch (RuntimeException ex) {
throw new IllegalStateException("Unable to create SecurityContext using " + annotation, ex);
}
};
TestExecutionEvent initialize = withSecurityContext.setupBefore();
return new TestSecurityContext(supplier, initialize);
}
private Annotation findAnnotation(AnnotatedElement annotated, Class<? extends Annotation> type) {
Annotation findAnnotation = AnnotatedElementUtils.findMergedAnnotation(annotated, type);
if (findAnnotation != null) {
return findAnnotation;
}
Annotation[] allAnnotations = AnnotationUtils.getAnnotations(annotated);
for (Annotation annotationToTest : allAnnotations) {
WithSecurityContext withSecurityContext = AnnotationUtils.findAnnotation(annotationToTest.annotationType(),
WithSecurityContext.class);
if (withSecurityContext != null) {
return annotationToTest;
}
}
return null;
}
private WithSecurityContextFactory<? extends Annotation> createFactory(WithSecurityContext withSecurityContext,
TestContext testContext) {
Class<? extends WithSecurityContextFactory<? extends Annotation>> clazz = withSecurityContext.factory();
try {
return testContext.getApplicationContext().getAutowireCapableBeanFactory().createBean(clazz);
}
catch (IllegalStateException ex) {
return BeanUtils.instantiateClass(clazz);
}
catch (Exception ex) {
throw new RuntimeException(ex);
}
}
/**
* Clears out the {@link TestSecurityContextHolder} and the
* {@link SecurityContextHolder} after each test method.
*/
@Override
public void afterTestMethod(TestContext testContext) {
this.securityContextHolderStrategyConverter.convert(testContext).clearContext();
}
/**
* Returns {@code 10000}.
*/
@Override
public int getOrder() {
return 10000;
}
static class TestSecurityContext {
private final Supplier<SecurityContext> securityContextSupplier;
private final TestExecutionEvent testExecutionEvent;
TestSecurityContext(Supplier<SecurityContext> securityContextSupplier, TestExecutionEvent testExecutionEvent) {
this.securityContextSupplier = securityContextSupplier;
this.testExecutionEvent = testExecutionEvent;
}
Supplier<SecurityContext> getSecurityContextSupplier() {
return this.securityContextSupplier;
}
TestExecutionEvent getTestExecutionEvent() {
return this.testExecutionEvent;
}
}
}
| 9,008 | 40.136986 | 134 | java |
null | spring-security-main/test/src/main/java/org/springframework/security/test/context/support/WithAnonymousUserSecurityContextFactory.java | /*
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.test.context.support;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.context.SecurityContextHolderStrategy;
/**
* A {@link WithSecurityContextFactory} that runs with an
* {@link AnonymousAuthenticationToken}. .
*
* @author Rob Winch
* @since 4.1
* @see WithUserDetails
*/
final class WithAnonymousUserSecurityContextFactory implements WithSecurityContextFactory<WithAnonymousUser> {
private SecurityContextHolderStrategy securityContextHolderStrategy = SecurityContextHolder
.getContextHolderStrategy();
@Override
public SecurityContext createSecurityContext(WithAnonymousUser withUser) {
List<GrantedAuthority> authorities = AuthorityUtils.createAuthorityList("ROLE_ANONYMOUS");
Authentication authentication = new AnonymousAuthenticationToken("key", "anonymous", authorities);
SecurityContext context = this.securityContextHolderStrategy.createEmptyContext();
context.setAuthentication(authentication);
return context;
}
@Autowired(required = false)
void setSecurityContextHolderStrategy(SecurityContextHolderStrategy securityContextHolderStrategy) {
this.securityContextHolderStrategy = securityContextHolderStrategy;
}
}
| 2,303 | 38.724138 | 110 | java |
null | spring-security-main/test/src/main/java/org/springframework/security/test/context/support/WithSecurityContext.java | /*
* Copyright 2002-2014 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.test.context.support;
import java.lang.annotation.Annotation;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.test.context.TestContext;
/**
* <p>
* An annotation to determine what {@link SecurityContext} to use. The {@link #factory()}
* attribute must be provided with an instance of
* {@link WithUserDetailsSecurityContextFactory}.
* </p>
*
* <p>
* Typically this annotation will be used as an meta-annotation as done with
* {@link WithMockUser} and {@link WithUserDetails}.
* </p>
*
* <p>
* If you would like to create your own implementation of
* {@link WithSecurityContextFactory} you can do so by implementing the interface. You can
* also use {@link Autowired} and other Spring semantics on the
* {@link WithSecurityContextFactory} implementation.
* </p>
*
* @author Rob Winch
* @since 4.0
*/
@Target({ ElementType.ANNOTATION_TYPE })
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Documented
public @interface WithSecurityContext {
/**
* The {@link WithUserDetailsSecurityContextFactory} to use to create the
* {@link SecurityContext}. It can contain {@link Autowired} and other Spring
* annotations.
* @return
*/
Class<? extends WithSecurityContextFactory<? extends Annotation>> factory();
/**
* Determines when the {@link SecurityContext} is setup. The default is before
* {@link TestExecutionEvent#TEST_METHOD} which occurs during
* {@link org.springframework.test.context.TestExecutionListener#beforeTestMethod(TestContext)}
* @return the {@link TestExecutionEvent} to initialize before
* @since 5.1
*/
TestExecutionEvent setupBefore() default TestExecutionEvent.TEST_METHOD;
}
| 2,650 | 33.428571 | 96 | java |
null | spring-security-main/test/src/main/java/org/springframework/security/test/context/support/TestExecutionEvent.java | /*
* Copyright 2002-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.test.context.support;
import org.springframework.test.context.TestContext;
/**
* Represents the events on the methods of
* {@link org.springframework.test.context.TestExecutionListener}
*
* @author Rob Winch
* @since 5.1
*/
public enum TestExecutionEvent {
/**
* Associated to
* {@link org.springframework.test.context.TestExecutionListener#beforeTestMethod(TestContext)}
* event.
*/
TEST_METHOD,
/**
* Associated to
* {@link org.springframework.test.context.TestExecutionListener#beforeTestExecution(TestContext)}
* event.
*/
TEST_EXECUTION
}
| 1,235 | 26.466667 | 99 | java |
null | spring-security-main/test/src/main/java/org/springframework/security/test/context/support/ReactorContextTestExecutionListener.java | /*
* Copyright 2002-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.test.context.support;
import org.reactivestreams.Subscription;
import reactor.core.CoreSubscriber;
import reactor.core.publisher.Hooks;
import reactor.core.publisher.Mono;
import reactor.core.publisher.Operators;
import reactor.util.context.Context;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.ReactiveSecurityContextHolder;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.test.context.TestSecurityContextHolder;
import org.springframework.test.context.TestContext;
import org.springframework.test.context.TestExecutionListener;
import org.springframework.test.context.support.AbstractTestExecutionListener;
import org.springframework.util.ClassUtils;
/**
* Sets up the Reactor Context with the Authentication from the TestSecurityContextHolder
* and then clears the Reactor Context at the end of the tests.
*
* @author Rob Winch
* @since 5.0
* @see WithSecurityContextTestExecutionListener
* @see org.springframework.security.test.context.annotation.SecurityTestExecutionListeners
*/
public class ReactorContextTestExecutionListener extends DelegatingTestExecutionListener {
private static final String HOOKS_CLASS_NAME = "reactor.core.publisher.Hooks";
private static final String CONTEXT_OPERATOR_KEY = SecurityContext.class.getName();
public ReactorContextTestExecutionListener() {
super(createDelegate());
}
private static TestExecutionListener createDelegate() {
if (!ClassUtils.isPresent(HOOKS_CLASS_NAME, ReactorContextTestExecutionListener.class.getClassLoader())) {
return new AbstractTestExecutionListener() {
};
}
return new DelegateTestExecutionListener();
}
/**
* Returns {@code 11000}.
*/
@Override
public int getOrder() {
return 11000;
}
private static class DelegateTestExecutionListener extends AbstractTestExecutionListener {
@Override
public void beforeTestMethod(TestContext testContext) {
SecurityContext securityContext = TestSecurityContextHolder.getContext();
Hooks.onLastOperator(CONTEXT_OPERATOR_KEY,
Operators.lift((s, sub) -> new SecuritySubContext<>(sub, securityContext)));
}
@Override
public void afterTestMethod(TestContext testContext) {
Hooks.resetOnLastOperator(CONTEXT_OPERATOR_KEY);
}
private static class SecuritySubContext<T> implements CoreSubscriber<T> {
private static String CONTEXT_DEFAULTED_ATTR_NAME = SecuritySubContext.class.getName()
.concat(".CONTEXT_DEFAULTED_ATTR_NAME");
private final CoreSubscriber<T> delegate;
private final SecurityContext securityContext;
SecuritySubContext(CoreSubscriber<T> delegate, SecurityContext securityContext) {
this.delegate = delegate;
this.securityContext = securityContext;
}
@Override
public Context currentContext() {
Context context = this.delegate.currentContext();
if (context.hasKey(CONTEXT_DEFAULTED_ATTR_NAME)) {
return context;
}
context = context.put(CONTEXT_DEFAULTED_ATTR_NAME, Boolean.TRUE);
Authentication authentication = this.securityContext.getAuthentication();
if (authentication == null) {
return context;
}
Context toMerge = ReactiveSecurityContextHolder.withSecurityContext(Mono.just(this.securityContext));
return toMerge.putAll(context.readOnly());
}
@Override
public void onSubscribe(Subscription s) {
this.delegate.onSubscribe(s);
}
@Override
public void onNext(T t) {
this.delegate.onNext(t);
}
@Override
public void onError(Throwable ex) {
this.delegate.onError(ex);
}
@Override
public void onComplete() {
this.delegate.onComplete();
}
}
}
}
| 4,362 | 30.615942 | 108 | java |
null | spring-security-main/test/src/main/java/org/springframework/security/test/context/support/WithMockUser.java | /*
* Copyright 2002-2014 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.test.context.support;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.springframework.core.annotation.AliasFor;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.test.context.TestContext;
import org.springframework.test.web.servlet.MockMvc;
/**
* When used with {@link WithSecurityContextTestExecutionListener} this annotation can be
* added to a test method to emulate running with a mocked user. In order to work with
* {@link MockMvc} The {@link SecurityContext} that is used will have the following
* properties:
*
* <ul>
* <li>The {@link SecurityContext} created with be that of
* {@link SecurityContextHolder#createEmptyContext()}</li>
* <li>It will be populated with an {@link UsernamePasswordAuthenticationToken} that uses
* the username of either {@link #value()} or {@link #username()},
* {@link GrantedAuthority} that are specified by {@link #roles()}, and a password
* specified by {@link #password()}.
* </ul>
*
* @see WithUserDetails
*
* @author Rob Winch
* @since 4.0
*/
@Target({ ElementType.METHOD, ElementType.TYPE })
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Documented
@WithSecurityContext(factory = WithMockUserSecurityContextFactory.class)
public @interface WithMockUser {
/**
* Convenience mechanism for specifying the username. The default is "user". If
* {@link #username()} is specified it will be used instead of {@link #value()}
* @return
*/
String value() default "user";
/**
* The username to be used. Note that {@link #value()} is a synonym for
* {@link #username()}, but if {@link #username()} is specified it will take
* precedence.
* @return
*/
String username() default "";
/**
* <p>
* The roles to use. The default is "USER". A {@link GrantedAuthority} will be created
* for each value within roles. Each value in roles will automatically be prefixed
* with "ROLE_". For example, the default will result in "ROLE_USER" being used.
* </p>
* <p>
* If {@link #authorities()} is specified this property cannot be changed from the
* default.
* </p>
* @return
*/
String[] roles() default { "USER" };
/**
* <p>
* The authorities to use. A {@link GrantedAuthority} will be created for each value.
* </p>
*
* <p>
* If this property is specified then {@link #roles()} is not used. This differs from
* {@link #roles()} in that it does not prefix the values passed in automatically.
* </p>
* @return
*/
String[] authorities() default {};
/**
* The password to be used. The default is "password".
* @return
*/
String password() default "password";
/**
* Determines when the {@link SecurityContext} is setup. The default is before
* {@link TestExecutionEvent#TEST_METHOD} which occurs during
* {@link org.springframework.test.context.TestExecutionListener#beforeTestMethod(TestContext)}
* @return the {@link TestExecutionEvent} to initialize before
* @since 5.1
*/
@AliasFor(annotation = WithSecurityContext.class)
TestExecutionEvent setupBefore() default TestExecutionEvent.TEST_METHOD;
}
| 4,163 | 33.7 | 96 | java |
null | spring-security-main/test/src/main/java/org/springframework/security/test/context/support/WithSecurityContextFactory.java | /*
* Copyright 2002-2014 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.test.context.support;
import java.lang.annotation.Annotation;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.test.context.TestSecurityContextHolder;
/**
* An API that works with WithUserTestExcecutionListener for creating a
* {@link SecurityContext} that is populated in the {@link TestSecurityContextHolder}.
*
* @param <A>
* @author Rob Winch
* @since 4.0
* @see WithSecurityContext
* @see WithMockUser
* @see WithUserDetails
*/
public interface WithSecurityContextFactory<A extends Annotation> {
/**
* Create a {@link SecurityContext} given an Annotation.
* @param annotation the {@link Annotation} to create the {@link SecurityContext}
* from. Cannot be null.
* @return the {@link SecurityContext} to use. Cannot be null.
*/
SecurityContext createSecurityContext(A annotation);
}
| 1,526 | 32.195652 | 86 | java |
null | spring-security-main/test/src/main/java/org/springframework/security/test/context/support/DelegatingTestExecutionListener.java | /*
* Copyright 2002-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.test.context.support;
import org.springframework.test.context.TestContext;
import org.springframework.test.context.TestExecutionListener;
import org.springframework.test.context.support.AbstractTestExecutionListener;
import org.springframework.util.Assert;
/**
* @author Rob Winch
* @since 5.0
*/
class DelegatingTestExecutionListener extends AbstractTestExecutionListener {
private final TestExecutionListener delegate;
DelegatingTestExecutionListener(TestExecutionListener delegate) {
Assert.notNull(delegate, "delegate cannot be null");
this.delegate = delegate;
}
@Override
public void beforeTestClass(TestContext testContext) throws Exception {
this.delegate.beforeTestClass(testContext);
}
@Override
public void prepareTestInstance(TestContext testContext) throws Exception {
this.delegate.prepareTestInstance(testContext);
}
@Override
public void beforeTestMethod(TestContext testContext) throws Exception {
this.delegate.beforeTestMethod(testContext);
}
@Override
public void beforeTestExecution(TestContext testContext) throws Exception {
this.delegate.beforeTestExecution(testContext);
}
@Override
public void afterTestExecution(TestContext testContext) throws Exception {
this.delegate.afterTestExecution(testContext);
}
@Override
public void afterTestMethod(TestContext testContext) throws Exception {
this.delegate.afterTestMethod(testContext);
}
@Override
public void afterTestClass(TestContext testContext) throws Exception {
this.delegate.afterTestClass(testContext);
}
}
| 2,205 | 29.219178 | 78 | java |
null | spring-security-main/test/src/main/java/org/springframework/security/test/context/support/WithUserDetailsSecurityContextFactory.java | /*
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.test.context.support;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanNotOfRequiredTypeException;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.context.SecurityContextHolderStrategy;
import org.springframework.security.core.userdetails.ReactiveUserDetailsService;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.util.Assert;
import org.springframework.util.ClassUtils;
import org.springframework.util.StringUtils;
/**
* A {@link WithSecurityContextFactory} that works with {@link WithUserDetails} .
*
* @author Rob Winch
* @since 4.0
* @see WithUserDetails
*/
final class WithUserDetailsSecurityContextFactory implements WithSecurityContextFactory<WithUserDetails> {
private static final boolean reactorPresent;
private SecurityContextHolderStrategy securityContextHolderStrategy = SecurityContextHolder
.getContextHolderStrategy();
private BeanFactory beans;
static {
reactorPresent = ClassUtils.isPresent("reactor.core.publisher.Mono",
WithUserDetailsSecurityContextFactory.class.getClassLoader());
}
@Autowired
WithUserDetailsSecurityContextFactory(BeanFactory beans) {
this.beans = beans;
}
@Override
public SecurityContext createSecurityContext(WithUserDetails withUser) {
String beanName = withUser.userDetailsServiceBeanName();
UserDetailsService userDetailsService = findUserDetailsService(beanName);
String username = withUser.value();
Assert.hasLength(username, "value() must be non empty String");
UserDetails principal = userDetailsService.loadUserByUsername(username);
Authentication authentication = UsernamePasswordAuthenticationToken.authenticated(principal,
principal.getPassword(), principal.getAuthorities());
SecurityContext context = this.securityContextHolderStrategy.createEmptyContext();
context.setAuthentication(authentication);
return context;
}
@Autowired(required = false)
void setSecurityContextHolderStrategy(SecurityContextHolderStrategy securityContextHolderStrategy) {
this.securityContextHolderStrategy = securityContextHolderStrategy;
}
private UserDetailsService findUserDetailsService(String beanName) {
if (reactorPresent) {
UserDetailsService reactive = findAndAdaptReactiveUserDetailsService(beanName);
if (reactive != null) {
return reactive;
}
}
return StringUtils.hasLength(beanName) ? this.beans.getBean(beanName, UserDetailsService.class)
: this.beans.getBean(UserDetailsService.class);
}
UserDetailsService findAndAdaptReactiveUserDetailsService(String beanName) {
try {
ReactiveUserDetailsService reactiveUserDetailsService = StringUtils.hasLength(beanName)
? this.beans.getBean(beanName, ReactiveUserDetailsService.class)
: this.beans.getBean(ReactiveUserDetailsService.class);
return new ReactiveUserDetailsServiceAdapter(reactiveUserDetailsService);
}
catch (NoSuchBeanDefinitionException | BeanNotOfRequiredTypeException ex) {
return null;
}
}
private final class ReactiveUserDetailsServiceAdapter implements UserDetailsService {
private final ReactiveUserDetailsService userDetailsService;
private ReactiveUserDetailsServiceAdapter(ReactiveUserDetailsService userDetailsService) {
this.userDetailsService = userDetailsService;
}
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
return this.userDetailsService.findByUsername(username).block();
}
}
}
| 4,721 | 38.35 | 106 | java |
null | spring-security-main/test/src/main/java/org/springframework/security/test/context/support/WithAnonymousUser.java | /*
* Copyright 2002-2015 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.test.context.support;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.springframework.core.annotation.AliasFor;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.test.context.TestContext;
/**
* When used with {@link WithSecurityContextTestExecutionListener} this annotation can be
* added to a test method to emulate running with an anonymous user. The
* {@link SecurityContext} that is used will contain an
* {@link AnonymousAuthenticationToken}. This is useful when a user wants to run a
* majority of tests as a specific user and wishes to override a few methods to be
* anonymous. For example:
*
* <pre>
* <code>
* @WithMockUser
* public class SecurityTests {
* @Test
* @WithAnonymousUser
* public void runAsAnonymous() {
* // ... run as an anonymous user ...
* }
*
* // ... lots of tests ran with a default user ...
* }
* </code> </pre>
*
* @author Rob Winch
* @since 4.1
*/
@Target({ ElementType.METHOD, ElementType.TYPE })
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Documented
@WithSecurityContext(factory = WithAnonymousUserSecurityContextFactory.class)
public @interface WithAnonymousUser {
/**
* Determines when the {@link SecurityContext} is setup. The default is before
* {@link TestExecutionEvent#TEST_METHOD} which occurs during
* {@link org.springframework.test.context.TestExecutionListener#beforeTestMethod(TestContext)}
* @return the {@link TestExecutionEvent} to initialize before
* @since 5.1
*/
@AliasFor(annotation = WithSecurityContext.class)
TestExecutionEvent setupBefore() default TestExecutionEvent.TEST_METHOD;
}
| 2,620 | 34.418919 | 96 | java |
null | spring-security-main/test/src/main/java/org/springframework/security/test/context/support/WithMockUserSecurityContextFactory.java | /*
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.test.context.support;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.context.SecurityContextHolderStrategy;
import org.springframework.security.core.userdetails.User;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
/**
* A {@link WithSecurityContextFactory} that works with {@link WithMockUser}.
*
* @author Rob Winch
* @since 4.0
* @see WithMockUser
*/
final class WithMockUserSecurityContextFactory implements WithSecurityContextFactory<WithMockUser> {
private SecurityContextHolderStrategy securityContextHolderStrategy = SecurityContextHolder
.getContextHolderStrategy();
@Override
public SecurityContext createSecurityContext(WithMockUser withUser) {
String username = StringUtils.hasLength(withUser.username()) ? withUser.username() : withUser.value();
Assert.notNull(username, () -> withUser + " cannot have null username on both username and value properties");
List<GrantedAuthority> grantedAuthorities = new ArrayList<>();
for (String authority : withUser.authorities()) {
grantedAuthorities.add(new SimpleGrantedAuthority(authority));
}
if (grantedAuthorities.isEmpty()) {
for (String role : withUser.roles()) {
Assert.isTrue(!role.startsWith("ROLE_"), () -> "roles cannot start with ROLE_ Got " + role);
grantedAuthorities.add(new SimpleGrantedAuthority("ROLE_" + role));
}
}
else if (!(withUser.roles().length == 1 && "USER".equals(withUser.roles()[0]))) {
throw new IllegalStateException("You cannot define roles attribute " + Arrays.asList(withUser.roles())
+ " with authorities attribute " + Arrays.asList(withUser.authorities()));
}
User principal = new User(username, withUser.password(), true, true, true, true, grantedAuthorities);
Authentication authentication = UsernamePasswordAuthenticationToken.authenticated(principal,
principal.getPassword(), principal.getAuthorities());
SecurityContext context = this.securityContextHolderStrategy.createEmptyContext();
context.setAuthentication(authentication);
return context;
}
@Autowired(required = false)
void setSecurityContextHolderStrategy(SecurityContextHolderStrategy securityContextHolderStrategy) {
this.securityContextHolderStrategy = securityContextHolderStrategy;
}
}
| 3,474 | 42.987342 | 112 | java |
null | spring-security-main/test/src/main/java/org/springframework/security/test/context/support/WithUserDetails.java | /*
* Copyright 2002-2014 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.test.context.support;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.springframework.core.annotation.AliasFor;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.test.context.TestContext;
import org.springframework.test.web.servlet.MockMvc;
/**
* When used with {@link WithSecurityContextTestExecutionListener} this annotation can be
* added to a test method to emulate running with a {@link UserDetails} returned from the
* {@link UserDetailsService}. In order to work with {@link MockMvc} The
* {@link SecurityContext} that is used will have the following properties:
*
* <ul>
* <li>The {@link SecurityContext} created with be that of
* {@link SecurityContextHolder#createEmptyContext()}</li>
* <li>It will be populated with an {@link UsernamePasswordAuthenticationToken} that uses
* the username of {@link #value()}.
* </ul>
*
* @see WithMockUser
*
* @author Rob Winch
* @since 4.0
*/
@Target({ ElementType.METHOD, ElementType.TYPE })
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Documented
@WithSecurityContext(factory = WithUserDetailsSecurityContextFactory.class)
public @interface WithUserDetails {
/**
* The username to look up in the {@link UserDetailsService}
* @return
*/
String value() default "user";
/**
* The bean name for the {@link UserDetailsService} to use. If this is not provided,
* then the lookup is done by type and expects only a single
* {@link UserDetailsService} bean to be exposed.
* @return the bean name for the {@link UserDetailsService} to use.
* @since 4.1
*/
String userDetailsServiceBeanName() default "";
/**
* Determines when the {@link SecurityContext} is setup. The default is before
* {@link TestExecutionEvent#TEST_METHOD} which occurs during
* {@link org.springframework.test.context.TestExecutionListener#beforeTestMethod(TestContext)}
* @return the {@link TestExecutionEvent} to initialize before
* @since 5.1
*/
@AliasFor(annotation = WithSecurityContext.class)
TestExecutionEvent setupBefore() default TestExecutionEvent.TEST_METHOD;
}
| 3,252 | 36.825581 | 96 | java |
null | spring-security-main/test/src/main/java/org/springframework/security/test/context/annotation/SecurityTestExecutionListeners.java | /*
* Copyright 2002-2015 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.test.context.annotation;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.springframework.context.ApplicationContext;
import org.springframework.security.test.context.support.ReactorContextTestExecutionListener;
import org.springframework.security.test.context.support.WithSecurityContextTestExecutionListener;
import org.springframework.test.context.TestExecutionListeners;
/**
* There are many times a user may want to use Spring Security's test support (i.e.
* WithMockUser) but have no need for any other {@link TestExecutionListeners} (i.e. no
* need to setup an {@link ApplicationContext}). This annotation is a meta annotation that
* only enables Spring Security's {@link TestExecutionListeners}.
*
* @author Rob Winch
* @since 4.0.2
* @see WithSecurityContextTestExecutionListener
* @see ReactorContextTestExecutionListener
*/
@Documented
@Inherited
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@TestExecutionListeners(inheritListeners = false,
listeners = { WithSecurityContextTestExecutionListener.class, ReactorContextTestExecutionListener.class })
public @interface SecurityTestExecutionListeners {
}
| 2,008 | 38.392157 | 108 | java |
null | spring-security-main/test/src/main/java/org/springframework/security/test/aot/hint/WithSecurityContextTestRuntimeHints.java | /*
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.test.aot.hint;
import java.util.Arrays;
import java.util.stream.Stream;
import org.springframework.aot.hint.MemberCategory;
import org.springframework.aot.hint.RuntimeHints;
import org.springframework.core.annotation.MergedAnnotation;
import org.springframework.core.annotation.MergedAnnotations;
import org.springframework.security.test.context.support.WithSecurityContext;
import org.springframework.test.context.aot.TestRuntimeHintsRegistrar;
import static org.springframework.core.annotation.MergedAnnotations.SearchStrategy.SUPERCLASS;
/**
* {@link TestRuntimeHintsRegistrar} implementation that register runtime hints for
* {@link WithSecurityContext#factory()} classes.
*
* @author Marcus da Coregio
* @since 6.0
*/
class WithSecurityContextTestRuntimeHints implements TestRuntimeHintsRegistrar {
@Override
public void registerHints(RuntimeHints hints, Class<?> testClass, ClassLoader classLoader) {
Stream.concat(getClassAnnotations(testClass), getMethodAnnotations(testClass))
.filter(MergedAnnotation::isPresent)
.map((withSecurityContext) -> withSecurityContext.getClass("factory"))
.forEach((factory) -> registerDeclaredConstructors(hints, factory));
}
private Stream<MergedAnnotation<WithSecurityContext>> getClassAnnotations(Class<?> testClass) {
return MergedAnnotations.search(SUPERCLASS).from(testClass).stream(WithSecurityContext.class);
}
private Stream<MergedAnnotation<WithSecurityContext>> getMethodAnnotations(Class<?> testClass) {
return Arrays.stream(testClass.getDeclaredMethods())
.map((method) -> MergedAnnotations.from(method, SUPERCLASS).get(WithSecurityContext.class));
}
private void registerDeclaredConstructors(RuntimeHints hints, Class<?> factory) {
hints.reflection().registerType(factory, MemberCategory.INVOKE_DECLARED_CONSTRUCTORS);
}
}
| 2,484 | 39.080645 | 97 | java |
null | spring-security-main/test/src/main/java/org/springframework/security/test/aot/hint/WebTestUtilsTestRuntimeHints.java | /*
* Copyright 2002-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.test.aot.hint;
import org.springframework.aot.hint.MemberCategory;
import org.springframework.aot.hint.RuntimeHints;
import org.springframework.security.web.FilterChainProxy;
import org.springframework.security.web.context.SecurityContextHolderFilter;
import org.springframework.security.web.context.SecurityContextPersistenceFilter;
import org.springframework.security.web.csrf.CsrfFilter;
import org.springframework.test.context.aot.TestRuntimeHintsRegistrar;
import org.springframework.util.ClassUtils;
/**
* {@link TestRuntimeHintsRegistrar} implementation that register runtime hints for
* {@link org.springframework.security.test.web.support.WebTestUtils}.
*
* @author Marcus da Coregio
* @since 6.0
*/
class WebTestUtilsTestRuntimeHints implements TestRuntimeHintsRegistrar {
@Override
public void registerHints(RuntimeHints hints, Class<?> testClass, ClassLoader classLoader) {
if (!ClassUtils.isPresent("jakarta.servlet.Filter", classLoader)) {
return;
}
registerFilterChainProxyHints(hints);
registerSecurityContextRepositoryHints(hints);
registerCsrfTokenRepositoryHints(hints);
}
private void registerFilterChainProxyHints(RuntimeHints hints) {
hints.reflection().registerType(FilterChainProxy.class, MemberCategory.INVOKE_DECLARED_METHODS);
}
private void registerCsrfTokenRepositoryHints(RuntimeHints hints) {
hints.reflection().registerType(CsrfFilter.class, MemberCategory.DECLARED_FIELDS);
}
private void registerSecurityContextRepositoryHints(RuntimeHints hints) {
hints.reflection().registerType(SecurityContextPersistenceFilter.class, MemberCategory.DECLARED_FIELDS);
hints.reflection().registerType(SecurityContextHolderFilter.class, MemberCategory.DECLARED_FIELDS);
}
}
| 2,395 | 38.278689 | 106 | java |
null | spring-security-main/taglibs/src/test/java/org/springframework/security/taglibs/TldTests.java | /*
* Copyright 2002-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.taglibs;
import java.io.File;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.junit.jupiter.api.Test;
import org.w3c.dom.Document;
import static org.assertj.core.api.Assertions.assertThat;
public class TldTests {
// SEC-2324
@Test
public void testTldVersionIsCorrect() throws Exception {
String SPRING_SECURITY_VERSION = "springSecurityVersion";
String version = System.getProperty(SPRING_SECURITY_VERSION);
File securityTld = new File("src/main/resources/META-INF/security.tld");
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
Document document = documentBuilder.parse(securityTld);
String tlibVersion = document.getElementsByTagName("tlib-version").item(0).getTextContent();
assertThat(version).startsWith(tlibVersion);
}
}
| 1,585 | 34.244444 | 94 | java |
null | spring-security-main/taglibs/src/test/java/org/springframework/security/taglibs/csrf/CsrfInputTagTests.java | /*
* Copyright 2002-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.taglibs.csrf;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.security.web.csrf.CsrfToken;
import org.springframework.security.web.csrf.DefaultCsrfToken;
import static org.assertj.core.api.Assertions.assertThat;
/**
* @author Nick Williams
*/
public class CsrfInputTagTests {
public CsrfInputTag tag;
@BeforeEach
public void setUp() {
this.tag = new CsrfInputTag();
}
@Test
public void handleTokenReturnsHiddenInput() {
CsrfToken token = new DefaultCsrfToken("X-Csrf-Token", "_csrf", "abc123def456ghi789");
String value = this.tag.handleToken(token);
assertThat(value).as("The returned value should not be null.").isNotNull();
assertThat(value).withFailMessage("The output is not correct.")
.isEqualTo("<input type=\"hidden\" name=\"_csrf\" value=\"abc123def456ghi789\" />");
}
@Test
public void handleTokenReturnsHiddenInputDifferentTokenValue() {
CsrfToken token = new DefaultCsrfToken("X-Csrf-Token", "csrfParameter", "fooBarBazQux");
String value = this.tag.handleToken(token);
assertThat(value).as("The returned value should not be null.").isNotNull();
assertThat(value).withFailMessage("The output is not correct.")
.isEqualTo("<input type=\"hidden\" name=\"csrfParameter\" value=\"fooBarBazQux\" />");
}
}
| 1,975 | 33.068966 | 90 | java |
null | spring-security-main/taglibs/src/test/java/org/springframework/security/taglibs/csrf/CsrfMetaTagsTagTests.java | /*
* Copyright 2002-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.taglibs.csrf;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.security.web.csrf.CsrfToken;
import org.springframework.security.web.csrf.DefaultCsrfToken;
import static org.assertj.core.api.Assertions.assertThat;
/**
* @author Nick Williams
*/
public class CsrfMetaTagsTagTests {
public CsrfMetaTagsTag tag;
@BeforeEach
public void setUp() {
this.tag = new CsrfMetaTagsTag();
}
@Test
public void handleTokenRendersTags() {
CsrfToken token = new DefaultCsrfToken("X-Csrf-Token", "_csrf", "abc123def456ghi789");
String value = this.tag.handleToken(token);
assertThat(value).as("The returned value should not be null.").isNotNull();
assertThat(value).withFailMessage("The output is not correct.")
.isEqualTo("<meta name=\"_csrf_parameter\" content=\"_csrf\" />"
+ "<meta name=\"_csrf_header\" content=\"X-Csrf-Token\" />"
+ "<meta name=\"_csrf\" content=\"abc123def456ghi789\" />");
}
@Test
public void handleTokenRendersTagsDifferentToken() {
CsrfToken token = new DefaultCsrfToken("csrfHeader", "csrfParameter", "fooBarBazQux");
String value = this.tag.handleToken(token);
assertThat(value).as("The returned value should not be null.").isNotNull();
assertThat(value).withFailMessage("The output is not correct.")
.isEqualTo("<meta name=\"_csrf_parameter\" content=\"csrfParameter\" />"
+ "<meta name=\"_csrf_header\" content=\"csrfHeader\" />"
+ "<meta name=\"_csrf\" content=\"fooBarBazQux\" />");
}
}
| 2,187 | 34.290323 | 88 | java |
null | spring-security-main/taglibs/src/test/java/org/springframework/security/taglibs/csrf/AbstractCsrfTagTests.java | /*
* Copyright 2002-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.taglibs.csrf;
import java.io.UnsupportedEncodingException;
import jakarta.servlet.jsp.JspException;
import jakarta.servlet.jsp.tagext.Tag;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.mock.web.MockPageContext;
import org.springframework.mock.web.MockServletContext;
import org.springframework.security.web.csrf.CsrfToken;
import org.springframework.security.web.csrf.DefaultCsrfToken;
import static org.assertj.core.api.Assertions.assertThat;
/**
* @author Nick Williams
*/
public class AbstractCsrfTagTests {
public MockTag tag;
private MockHttpServletRequest request;
private MockHttpServletResponse response;
@BeforeEach
public void setUp() {
MockServletContext servletContext = new MockServletContext();
this.request = new MockHttpServletRequest(servletContext);
this.response = new MockHttpServletResponse();
MockPageContext pageContext = new MockPageContext(servletContext, this.request, this.response);
this.tag = new MockTag();
this.tag.setPageContext(pageContext);
}
@Test
public void noCsrfDoesNotRender() throws JspException, UnsupportedEncodingException {
this.tag.handleReturn = "shouldNotBeRendered";
int returned = this.tag.doEndTag();
assertThat(returned).as("The returned value is not correct.").isEqualTo(Tag.EVAL_PAGE);
assertThat(this.response.getContentAsString()).withFailMessage("The output value is not correct.")
.isEqualTo("");
}
@Test
public void hasCsrfRendersReturnedValue() throws JspException, UnsupportedEncodingException {
CsrfToken token = new DefaultCsrfToken("X-Csrf-Token", "_csrf", "abc123def456ghi789");
this.request.setAttribute(CsrfToken.class.getName(), token);
this.tag.handleReturn = "fooBarBazQux";
int returned = this.tag.doEndTag();
assertThat(returned).as("The returned value is not correct.").isEqualTo(Tag.EVAL_PAGE);
assertThat(this.response.getContentAsString()).withFailMessage("The output value is not correct.")
.isEqualTo("fooBarBazQux");
assertThat(this.tag.token).as("The token is not correct.").isSameAs(token);
}
@Test
public void hasCsrfRendersDifferentValue() throws JspException, UnsupportedEncodingException {
CsrfToken token = new DefaultCsrfToken("X-Csrf-Token", "_csrf", "abc123def456ghi789");
this.request.setAttribute(CsrfToken.class.getName(), token);
this.tag.handleReturn = "<input type=\"hidden\" />";
int returned = this.tag.doEndTag();
assertThat(returned).as("The returned value is not correct.").isEqualTo(Tag.EVAL_PAGE);
assertThat(this.response.getContentAsString()).withFailMessage("The output value is not correct.")
.isEqualTo("<input type=\"hidden\" />");
assertThat(this.tag.token).as("The token is not correct.").isSameAs(token);
}
private static class MockTag extends AbstractCsrfTag {
private CsrfToken token;
private String handleReturn;
@Override
protected String handleToken(CsrfToken token) {
this.token = token;
return this.handleReturn;
}
}
}
| 3,788 | 35.432692 | 100 | java |
null | spring-security-main/taglibs/src/test/java/org/springframework/security/taglibs/authz/AuthenticationTagTests.java | /*
* Copyright 2004, 2005, 2006 Acegi Technology Pty Limited
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.taglibs.authz;
import jakarta.servlet.jsp.JspException;
import jakarta.servlet.jsp.tagext.Tag;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;
import org.springframework.mock.web.MockPageContext;
import org.springframework.mock.web.MockServletContext;
import org.springframework.security.authentication.TestingAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.context.SecurityContextHolderStrategy;
import org.springframework.security.core.context.SecurityContextImpl;
import org.springframework.security.core.userdetails.User;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.GenericWebApplicationContext;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
/**
* Tests {@link AuthenticationTag}.
*
* @author Ben Alex
*/
public class AuthenticationTagTests {
private final MyAuthenticationTag authenticationTag = new MyAuthenticationTag();
private final Authentication auth = new TestingAuthenticationToken(
new User("rodUserDetails", "koala", true, true, true, true, AuthorityUtils.NO_AUTHORITIES), "koala",
AuthorityUtils.NO_AUTHORITIES);
@AfterEach
public void tearDown() {
SecurityContextHolder.clearContext();
}
@Test
public void testOperationWhenPrincipalIsAUserDetailsInstance() throws JspException {
SecurityContextHolder.getContext().setAuthentication(this.auth);
this.authenticationTag.setProperty("name");
assertThat(this.authenticationTag.doStartTag()).isEqualTo(Tag.SKIP_BODY);
assertThat(this.authenticationTag.doEndTag()).isEqualTo(Tag.EVAL_PAGE);
assertThat(this.authenticationTag.getLastMessage()).isEqualTo("rodUserDetails");
}
@Test
public void testOperationWhenPrincipalIsAString() throws JspException {
SecurityContextHolder.getContext().setAuthentication(
new TestingAuthenticationToken("rodAsString", "koala", AuthorityUtils.NO_AUTHORITIES));
this.authenticationTag.setProperty("principal");
assertThat(this.authenticationTag.doStartTag()).isEqualTo(Tag.SKIP_BODY);
assertThat(this.authenticationTag.doEndTag()).isEqualTo(Tag.EVAL_PAGE);
assertThat(this.authenticationTag.getLastMessage()).isEqualTo("rodAsString");
}
@Test
public void testNestedPropertyIsReadCorrectly() throws JspException {
SecurityContextHolder.getContext().setAuthentication(this.auth);
this.authenticationTag.setProperty("principal.username");
assertThat(this.authenticationTag.doStartTag()).isEqualTo(Tag.SKIP_BODY);
assertThat(this.authenticationTag.doEndTag()).isEqualTo(Tag.EVAL_PAGE);
assertThat(this.authenticationTag.getLastMessage()).isEqualTo("rodUserDetails");
}
@Test
public void testOperationWhenPrincipalIsNull() throws JspException {
SecurityContextHolder.getContext()
.setAuthentication(new TestingAuthenticationToken(null, "koala", AuthorityUtils.NO_AUTHORITIES));
this.authenticationTag.setProperty("principal");
assertThat(this.authenticationTag.doStartTag()).isEqualTo(Tag.SKIP_BODY);
assertThat(this.authenticationTag.doEndTag()).isEqualTo(Tag.EVAL_PAGE);
}
@Test
public void testOperationWhenSecurityContextIsNull() throws Exception {
SecurityContextHolder.getContext().setAuthentication(null);
this.authenticationTag.setProperty("principal");
assertThat(this.authenticationTag.doStartTag()).isEqualTo(Tag.SKIP_BODY);
assertThat(this.authenticationTag.doEndTag()).isEqualTo(Tag.EVAL_PAGE);
assertThat(this.authenticationTag.getLastMessage()).isNull();
}
@Test
public void testSkipsBodyIfNullOrEmptyOperation() throws Exception {
this.authenticationTag.setProperty("");
assertThat(this.authenticationTag.doStartTag()).isEqualTo(Tag.SKIP_BODY);
assertThat(this.authenticationTag.doEndTag()).isEqualTo(Tag.EVAL_PAGE);
}
@Test
public void testThrowsExceptionForUnrecognisedProperty() {
SecurityContextHolder.getContext().setAuthentication(this.auth);
this.authenticationTag.setProperty("qsq");
assertThatExceptionOfType(JspException.class).isThrownBy(() -> {
this.authenticationTag.doStartTag();
this.authenticationTag.doEndTag();
});
}
@Test
public void htmlEscapingIsUsedByDefault() throws Exception {
SecurityContextHolder.getContext().setAuthentication(new TestingAuthenticationToken("<>& ", ""));
this.authenticationTag.setProperty("name");
this.authenticationTag.doStartTag();
this.authenticationTag.doEndTag();
assertThat(this.authenticationTag.getLastMessage()).isEqualTo("<>& ");
}
@Test
public void settingHtmlEscapeToFalsePreventsEscaping() throws Exception {
SecurityContextHolder.getContext().setAuthentication(new TestingAuthenticationToken("<>& ", ""));
this.authenticationTag.setProperty("name");
this.authenticationTag.setHtmlEscape("false");
this.authenticationTag.doStartTag();
this.authenticationTag.doEndTag();
assertThat(this.authenticationTag.getLastMessage()).isEqualTo("<>& ");
}
@Test
public void setSecurityContextHolderStrategyThenUses() throws Exception {
SecurityContextHolderStrategy strategy = mock(SecurityContextHolderStrategy.class);
given(strategy.getContext()).willReturn(new SecurityContextImpl(
new TestingAuthenticationToken("rodAsString", "koala", AuthorityUtils.NO_AUTHORITIES)));
MockServletContext servletContext = new MockServletContext();
GenericWebApplicationContext applicationContext = new GenericWebApplicationContext();
applicationContext.registerBean(SecurityContextHolderStrategy.class, () -> strategy);
applicationContext.refresh();
servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, applicationContext);
this.authenticationTag.setPageContext(new MockPageContext(servletContext));
this.authenticationTag.setProperty("principal");
assertThat(this.authenticationTag.doStartTag()).isEqualTo(Tag.SKIP_BODY);
assertThat(this.authenticationTag.doEndTag()).isEqualTo(Tag.EVAL_PAGE);
assertThat(this.authenticationTag.getLastMessage()).isEqualTo("rodAsString");
verify(strategy).getContext();
}
private class MyAuthenticationTag extends AuthenticationTag {
String lastMessage = null;
String getLastMessage() {
return this.lastMessage;
}
@Override
protected void writeMessage(String msg) {
this.lastMessage = msg;
}
}
}
| 7,314 | 40.5625 | 112 | java |
null | spring-security-main/taglibs/src/test/java/org/springframework/security/taglibs/authz/AccessControlListTagTests.java | /*
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.taglibs.authz;
import java.util.HashMap;
import java.util.Map;
import jakarta.servlet.ServletContext;
import jakarta.servlet.jsp.tagext.Tag;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.mock.web.MockPageContext;
import org.springframework.mock.web.MockServletContext;
import org.springframework.security.access.PermissionEvaluator;
import org.springframework.security.authentication.TestingAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.context.SecurityContextHolderStrategy;
import org.springframework.security.core.context.SecurityContextImpl;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.GenericWebApplicationContext;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
/**
* @author Luke Taylor
* @author Rob Winch
* @since 3.0
*/
@SuppressWarnings("unchecked")
public class AccessControlListTagTests {
AccessControlListTag tag;
PermissionEvaluator pe;
MockPageContext pageContext;
Authentication bob = new TestingAuthenticationToken("bob", "bobspass", "A");
@BeforeEach
@SuppressWarnings("rawtypes")
public void setup() {
SecurityContextHolder.getContext().setAuthentication(this.bob);
this.tag = new AccessControlListTag();
WebApplicationContext ctx = mock(WebApplicationContext.class);
this.pe = mock(PermissionEvaluator.class);
Map beanMap = new HashMap();
beanMap.put("pe", this.pe);
given(ctx.getBeansOfType(PermissionEvaluator.class)).willReturn(beanMap);
given(ctx.getBeanNamesForType(SecurityContextHolderStrategy.class)).willReturn(new String[0]);
MockServletContext servletCtx = new MockServletContext();
servletCtx.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, ctx);
this.pageContext = new MockPageContext(servletCtx, new MockHttpServletRequest(), new MockHttpServletResponse());
this.tag.setPageContext(this.pageContext);
}
@AfterEach
public void clearContext() {
SecurityContextHolder.clearContext();
}
@Test
public void bodyIsEvaluatedIfAclGrantsAccess() throws Exception {
Object domainObject = new Object();
given(this.pe.hasPermission(this.bob, domainObject, "READ")).willReturn(true);
this.tag.setDomainObject(domainObject);
this.tag.setHasPermission("READ");
this.tag.setVar("allowed");
assertThat(this.tag.getDomainObject()).isSameAs(domainObject);
assertThat(this.tag.getHasPermission()).isEqualTo("READ");
assertThat(this.tag.doStartTag()).isEqualTo(Tag.EVAL_BODY_INCLUDE);
assertThat((Boolean) this.pageContext.getAttribute("allowed")).isTrue();
}
@Test
public void securityContextHolderStrategyIsUsedIfConfigured() throws Exception {
SecurityContextHolderStrategy strategy = mock(SecurityContextHolderStrategy.class);
given(strategy.getContext()).willReturn(new SecurityContextImpl(this.bob));
GenericWebApplicationContext context = new GenericWebApplicationContext();
context.registerBean(SecurityContextHolderStrategy.class, () -> strategy);
context.registerBean(PermissionEvaluator.class, () -> this.pe);
context.refresh();
MockServletContext servletCtx = new MockServletContext();
servletCtx.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, context);
this.pageContext = new MockPageContext(servletCtx, new MockHttpServletRequest(), new MockHttpServletResponse());
this.tag.setPageContext(this.pageContext);
Object domainObject = new Object();
given(this.pe.hasPermission(this.bob, domainObject, "READ")).willReturn(true);
this.tag.setDomainObject(domainObject);
this.tag.setHasPermission("READ");
this.tag.setVar("allowed");
assertThat(this.tag.getDomainObject()).isSameAs(domainObject);
assertThat(this.tag.getHasPermission()).isEqualTo("READ");
assertThat(this.tag.doStartTag()).isEqualTo(Tag.EVAL_BODY_INCLUDE);
assertThat((Boolean) this.pageContext.getAttribute("allowed")).isTrue();
verify(strategy).getContext();
}
@Test
public void childContext() throws Exception {
ServletContext servletContext = this.pageContext.getServletContext();
WebApplicationContext wac = (WebApplicationContext) servletContext
.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
servletContext.removeAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
servletContext.setAttribute("org.springframework.web.servlet.FrameworkServlet.CONTEXT.dispatcher", wac);
Object domainObject = new Object();
given(this.pe.hasPermission(this.bob, domainObject, "READ")).willReturn(true);
this.tag.setDomainObject(domainObject);
this.tag.setHasPermission("READ");
this.tag.setVar("allowed");
assertThat(this.tag.getDomainObject()).isSameAs(domainObject);
assertThat(this.tag.getHasPermission()).isEqualTo("READ");
assertThat(this.tag.doStartTag()).isEqualTo(Tag.EVAL_BODY_INCLUDE);
assertThat((Boolean) this.pageContext.getAttribute("allowed")).isTrue();
}
// SEC-2022
@Test
public void multiHasPermissionsAreSplit() throws Exception {
Object domainObject = new Object();
given(this.pe.hasPermission(this.bob, domainObject, "READ")).willReturn(true);
given(this.pe.hasPermission(this.bob, domainObject, "WRITE")).willReturn(true);
this.tag.setDomainObject(domainObject);
this.tag.setHasPermission("READ,WRITE");
this.tag.setVar("allowed");
assertThat(this.tag.getDomainObject()).isSameAs(domainObject);
assertThat(this.tag.getHasPermission()).isEqualTo("READ,WRITE");
assertThat(this.tag.doStartTag()).isEqualTo(Tag.EVAL_BODY_INCLUDE);
assertThat((Boolean) this.pageContext.getAttribute("allowed")).isTrue();
verify(this.pe).hasPermission(this.bob, domainObject, "READ");
verify(this.pe).hasPermission(this.bob, domainObject, "WRITE");
verifyNoMoreInteractions(this.pe);
}
// SEC-2023
@Test
public void hasPermissionsBitMaskSupported() throws Exception {
Object domainObject = new Object();
given(this.pe.hasPermission(this.bob, domainObject, 1)).willReturn(true);
given(this.pe.hasPermission(this.bob, domainObject, 2)).willReturn(true);
this.tag.setDomainObject(domainObject);
this.tag.setHasPermission("1,2");
this.tag.setVar("allowed");
assertThat(this.tag.getDomainObject()).isSameAs(domainObject);
assertThat(this.tag.getHasPermission()).isEqualTo("1,2");
assertThat(this.tag.doStartTag()).isEqualTo(Tag.EVAL_BODY_INCLUDE);
assertThat((Boolean) this.pageContext.getAttribute("allowed")).isTrue();
verify(this.pe).hasPermission(this.bob, domainObject, 1);
verify(this.pe).hasPermission(this.bob, domainObject, 2);
verifyNoMoreInteractions(this.pe);
}
@Test
public void hasPermissionsMixedBitMaskSupported() throws Exception {
Object domainObject = new Object();
given(this.pe.hasPermission(this.bob, domainObject, 1)).willReturn(true);
given(this.pe.hasPermission(this.bob, domainObject, "WRITE")).willReturn(true);
this.tag.setDomainObject(domainObject);
this.tag.setHasPermission("1,WRITE");
this.tag.setVar("allowed");
assertThat(this.tag.getDomainObject()).isSameAs(domainObject);
assertThat(this.tag.getHasPermission()).isEqualTo("1,WRITE");
assertThat(this.tag.doStartTag()).isEqualTo(Tag.EVAL_BODY_INCLUDE);
assertThat((Boolean) this.pageContext.getAttribute("allowed")).isTrue();
verify(this.pe).hasPermission(this.bob, domainObject, 1);
verify(this.pe).hasPermission(this.bob, domainObject, "WRITE");
verifyNoMoreInteractions(this.pe);
}
@Test
public void bodyIsSkippedIfAclDeniesAccess() throws Exception {
Object domainObject = new Object();
given(this.pe.hasPermission(this.bob, domainObject, "READ")).willReturn(false);
this.tag.setDomainObject(domainObject);
this.tag.setHasPermission("READ");
this.tag.setVar("allowed");
assertThat(this.tag.doStartTag()).isEqualTo(Tag.SKIP_BODY);
assertThat((Boolean) this.pageContext.getAttribute("allowed")).isFalse();
}
}
| 9,021 | 43.009756 | 114 | java |
null | spring-security-main/taglibs/src/test/java/org/springframework/security/taglibs/authz/AbstractAuthorizeTagTests.java | /*
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.taglibs.authz;
import java.io.IOException;
import java.util.Collections;
import jakarta.servlet.ServletContext;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.mock.web.MockServletContext;
import org.springframework.security.access.expression.SecurityExpressionHandler;
import org.springframework.security.authentication.TestingAuthenticationToken;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.context.SecurityContextHolderStrategy;
import org.springframework.security.core.context.SecurityContextImpl;
import org.springframework.security.web.WebAttributes;
import org.springframework.security.web.access.WebInvocationPrivilegeEvaluator;
import org.springframework.security.web.access.expression.DefaultWebSecurityExpressionHandler;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.GenericWebApplicationContext;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
/**
* @author Rob Winch
*
*/
public class AbstractAuthorizeTagTests {
private AbstractAuthorizeTag tag;
private MockHttpServletRequest request;
private MockHttpServletResponse response;
private MockServletContext servletContext;
@BeforeEach
public void setup() {
this.tag = new AuthzTag();
this.request = new MockHttpServletRequest();
this.response = new MockHttpServletResponse();
this.servletContext = new MockServletContext();
}
@AfterEach
public void teardown() {
SecurityContextHolder.clearContext();
}
@Test
public void privilegeEvaluatorFromRequest() throws IOException {
WebApplicationContext wac = mock(WebApplicationContext.class);
this.servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, wac);
given(wac.getBeanNamesForType(SecurityContextHolderStrategy.class)).willReturn(new String[0]);
String uri = "/something";
WebInvocationPrivilegeEvaluator expected = mock(WebInvocationPrivilegeEvaluator.class);
this.tag.setUrl(uri);
this.request.setAttribute(WebAttributes.WEB_INVOCATION_PRIVILEGE_EVALUATOR_ATTRIBUTE, expected);
this.tag.authorizeUsingUrlCheck();
verify(expected).isAllowed(eq(""), eq(uri), eq("GET"), any());
}
@Test
public void privilegeEvaluatorFromRequestUsesSecurityContextHolderStrategy() throws IOException {
SecurityContextHolderStrategy strategy = mock(SecurityContextHolderStrategy.class);
given(strategy.getContext()).willReturn(new SecurityContextImpl(
new TestingAuthenticationToken("user", "password", AuthorityUtils.NO_AUTHORITIES)));
GenericWebApplicationContext wac = new GenericWebApplicationContext();
wac.registerBean(SecurityContextHolderStrategy.class, () -> strategy);
wac.refresh();
this.servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, wac);
String uri = "/something";
WebInvocationPrivilegeEvaluator expected = mock(WebInvocationPrivilegeEvaluator.class);
this.tag.setUrl(uri);
this.request.setAttribute(WebAttributes.WEB_INVOCATION_PRIVILEGE_EVALUATOR_ATTRIBUTE, expected);
this.tag.authorizeUsingUrlCheck();
verify(expected).isAllowed(eq(""), eq(uri), eq("GET"), any());
verify(strategy).getContext();
}
@Test
public void privilegeEvaluatorFromChildContext() throws IOException {
String uri = "/something";
WebInvocationPrivilegeEvaluator expected = mock(WebInvocationPrivilegeEvaluator.class);
this.tag.setUrl(uri);
WebApplicationContext wac = mock(WebApplicationContext.class);
given(wac.getBeansOfType(WebInvocationPrivilegeEvaluator.class))
.willReturn(Collections.singletonMap("wipe", expected));
given(wac.getBeanNamesForType(SecurityContextHolderStrategy.class)).willReturn(new String[0]);
this.servletContext.setAttribute("org.springframework.web.servlet.FrameworkServlet.CONTEXT.dispatcher", wac);
this.tag.authorizeUsingUrlCheck();
verify(expected).isAllowed(eq(""), eq(uri), eq("GET"), any());
}
@Test
@SuppressWarnings("rawtypes")
public void expressionFromChildContext() throws IOException {
SecurityContextHolder.getContext().setAuthentication(new TestingAuthenticationToken("user", "pass", "USER"));
DefaultWebSecurityExpressionHandler expected = new DefaultWebSecurityExpressionHandler();
this.tag.setAccess("permitAll");
WebApplicationContext wac = mock(WebApplicationContext.class);
given(wac.getBeansOfType(SecurityExpressionHandler.class))
.willReturn(Collections.<String, SecurityExpressionHandler>singletonMap("wipe", expected));
given(wac.getBeanNamesForType(SecurityContextHolderStrategy.class)).willReturn(new String[0]);
this.servletContext.setAttribute("org.springframework.web.servlet.FrameworkServlet.CONTEXT.dispatcher", wac);
assertThat(this.tag.authorize()).isTrue();
}
private class AuthzTag extends AbstractAuthorizeTag {
@Override
protected ServletRequest getRequest() {
return AbstractAuthorizeTagTests.this.request;
}
@Override
protected ServletResponse getResponse() {
return AbstractAuthorizeTagTests.this.response;
}
@Override
protected ServletContext getServletContext() {
return AbstractAuthorizeTagTests.this.servletContext;
}
}
}
| 6,420 | 39.898089 | 111 | java |
null | spring-security-main/taglibs/src/test/java/org/springframework/security/taglibs/authz/AuthorizeTagTests.java | /*
* Copyright 2004, 2005, 2006 Acegi Technology Pty Limited
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.taglibs.authz;
import jakarta.servlet.jsp.JspException;
import jakarta.servlet.jsp.tagext.Tag;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.mock.web.MockPageContext;
import org.springframework.mock.web.MockServletContext;
import org.springframework.security.access.PermissionEvaluator;
import org.springframework.security.authentication.TestingAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.access.WebInvocationPrivilegeEvaluator;
import org.springframework.security.web.access.expression.DefaultWebSecurityExpressionHandler;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.StaticWebApplicationContext;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.BDDMockito.given;
/**
* @author Francois Beausoleil
* @author Luke Taylor
*/
@ExtendWith(MockitoExtension.class)
public class AuthorizeTagTests {
@Mock
private PermissionEvaluator permissionEvaluator;
private JspAuthorizeTag authorizeTag;
private MockHttpServletRequest request = new MockHttpServletRequest();
private final TestingAuthenticationToken currentUser = new TestingAuthenticationToken("abc", "123",
"ROLE SUPERVISOR", "ROLE_TELLER");
@BeforeEach
public void setUp() {
SecurityContextHolder.getContext().setAuthentication(this.currentUser);
StaticWebApplicationContext ctx = new StaticWebApplicationContext();
BeanDefinitionBuilder webExpressionHandler = BeanDefinitionBuilder
.rootBeanDefinition(DefaultWebSecurityExpressionHandler.class);
webExpressionHandler.addPropertyValue("permissionEvaluator", this.permissionEvaluator);
ctx.registerBeanDefinition("expressionHandler", webExpressionHandler.getBeanDefinition());
ctx.registerSingleton("wipe", MockWebInvocationPrivilegeEvaluator.class);
MockServletContext servletCtx = new MockServletContext();
servletCtx.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, ctx);
this.authorizeTag = new JspAuthorizeTag();
this.authorizeTag.setPageContext(new MockPageContext(servletCtx, this.request, new MockHttpServletResponse()));
}
@AfterEach
public void tearDown() {
SecurityContextHolder.clearContext();
}
// access attribute tests
@Test
public void taglibsDocumentationHasPermissionOr() throws Exception {
Object domain = new Object();
this.request.setAttribute("domain", domain);
this.authorizeTag.setAccess("hasPermission(#domain,'read') or hasPermission(#domain,'write')");
given(this.permissionEvaluator.hasPermission(eq(this.currentUser), eq(domain), anyString())).willReturn(true);
assertThat(this.authorizeTag.doStartTag()).isEqualTo(Tag.EVAL_BODY_INCLUDE);
}
@Test
public void skipsBodyIfNoAuthenticationPresent() throws Exception {
SecurityContextHolder.clearContext();
this.authorizeTag.setAccess("permitAll");
assertThat(this.authorizeTag.doStartTag()).isEqualTo(Tag.SKIP_BODY);
}
@Test
public void skipsBodyIfAccessExpressionDeniesAccess() throws Exception {
this.authorizeTag.setAccess("denyAll");
assertThat(this.authorizeTag.doStartTag()).isEqualTo(Tag.SKIP_BODY);
}
@Test
public void showsBodyIfAccessExpressionAllowsAccess() throws Exception {
this.authorizeTag.setAccess("permitAll");
assertThat(this.authorizeTag.doStartTag()).isEqualTo(Tag.EVAL_BODY_INCLUDE);
}
@Test
public void requestAttributeIsResolvedAsElVariable() throws JspException {
this.request.setAttribute("blah", "blah");
this.authorizeTag.setAccess("#blah == 'blah'");
assertThat(this.authorizeTag.doStartTag()).isEqualTo(Tag.EVAL_BODY_INCLUDE);
}
// url attribute tests
@Test
public void skipsBodyWithUrlSetIfNoAuthenticationPresent() throws Exception {
SecurityContextHolder.clearContext();
this.authorizeTag.setUrl("/something");
assertThat(this.authorizeTag.doStartTag()).isEqualTo(Tag.SKIP_BODY);
}
@Test
public void skipsBodyIfUrlIsNotAllowed() throws Exception {
this.authorizeTag.setUrl("/notallowed");
assertThat(this.authorizeTag.doStartTag()).isEqualTo(Tag.SKIP_BODY);
}
@Test
public void evaluatesBodyIfUrlIsAllowed() throws Exception {
this.authorizeTag.setUrl("/allowed");
this.authorizeTag.setMethod("GET");
assertThat(this.authorizeTag.doStartTag()).isEqualTo(Tag.EVAL_BODY_INCLUDE);
}
@Test
public void skipsBodyIfMethodIsNotAllowed() throws Exception {
this.authorizeTag.setUrl("/allowed");
this.authorizeTag.setMethod("POST");
assertThat(this.authorizeTag.doStartTag()).isEqualTo(Tag.SKIP_BODY);
}
public static class MockWebInvocationPrivilegeEvaluator implements WebInvocationPrivilegeEvaluator {
@Override
public boolean isAllowed(String uri, Authentication authentication) {
return "/allowed".equals(uri);
}
@Override
public boolean isAllowed(String contextPath, String uri, String method, Authentication authentication) {
return "/allowed".equals(uri) && (method == null || "GET".equals(method));
}
}
}
| 6,236 | 37.263804 | 113 | java |
null | spring-security-main/taglibs/src/main/java/org/springframework/security/taglibs/package-info.java | /*
* Copyright 2002-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Security related tag libraries that can be used in JSPs and templates.
*/
package org.springframework.security.taglibs;
| 751 | 34.809524 | 75 | java |
null | spring-security-main/taglibs/src/main/java/org/springframework/security/taglibs/TagLibConfig.java | /*
* Copyright 2002-2014 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.taglibs;
import jakarta.servlet.jsp.tagext.Tag;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
* internal configuration class for taglibs.
*
* Not for public use.
*
* @author Luke Taylor
*/
public final class TagLibConfig {
static Log logger = LogFactory.getLog("spring-security-taglibs");
static final boolean DISABLE_UI_SECURITY;
static final String SECURED_UI_PREFIX;
static final String SECURED_UI_SUFFIX;
static {
String db = System.getProperty("spring.security.disableUISecurity");
String prefix = System.getProperty("spring.security.securedUIPrefix");
String suffix = System.getProperty("spring.security.securedUISuffix");
SECURED_UI_PREFIX = (prefix != null) ? prefix : "<span class=\"securityHiddenUI\">";
SECURED_UI_SUFFIX = (suffix != null) ? suffix : "</span>";
DISABLE_UI_SECURITY = "true".equals(db);
if (DISABLE_UI_SECURITY) {
logger.warn("***** UI security is disabled. All unauthorized content will be displayed *****");
}
}
private TagLibConfig() {
}
/**
* Returns EVAL_BODY_INCLUDE if the authorized flag is true or UI security has been
* disabled. Otherwise returns SKIP_BODY.
* @param authorized whether the user is authorized to see the content or not
*/
public static int evalOrSkip(boolean authorized) {
return (authorized || DISABLE_UI_SECURITY) ? Tag.EVAL_BODY_INCLUDE : Tag.SKIP_BODY;
}
public static boolean isUiSecurityDisabled() {
return DISABLE_UI_SECURITY;
}
public static String getSecuredUiPrefix() {
return SECURED_UI_PREFIX;
}
public static String getSecuredUiSuffix() {
return SECURED_UI_SUFFIX;
}
}
| 2,310 | 29.012987 | 98 | java |
null | spring-security-main/taglibs/src/main/java/org/springframework/security/taglibs/csrf/CsrfMetaTagsTag.java | /*
* Copyright 2002-2014 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.taglibs.csrf;
import org.springframework.security.web.csrf.CsrfToken;
/**
* A JSP tag that prints out a meta tags holding the CSRF form field name and token value
* for use in JavaScrip code. See the JSP Tab Library documentation for more information.
*
* @author Nick Williams
* @since 3.2.2
*/
public class CsrfMetaTagsTag extends AbstractCsrfTag {
@Override
public String handleToken(CsrfToken token) {
return "<meta name=\"_csrf_parameter\" content=\"" + token.getParameterName() + "\" />"
+ "<meta name=\"_csrf_header\" content=\"" + token.getHeaderName() + "\" />"
+ "<meta name=\"_csrf\" content=\"" + token.getToken() + "\" />";
}
}
| 1,324 | 33.868421 | 89 | java |
null | spring-security-main/taglibs/src/main/java/org/springframework/security/taglibs/csrf/AbstractCsrfTag.java | /*
* Copyright 2002-2014 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.taglibs.csrf;
import java.io.IOException;
import jakarta.servlet.jsp.JspException;
import jakarta.servlet.jsp.tagext.TagSupport;
import org.springframework.security.web.csrf.CsrfToken;
/**
* An abstract tag for handling CSRF operations.
*
* @author Nick Williams
* @since 3.2.2
*/
abstract class AbstractCsrfTag extends TagSupport {
@Override
public int doEndTag() throws JspException {
CsrfToken token = (CsrfToken) this.pageContext.getRequest().getAttribute(CsrfToken.class.getName());
if (token != null) {
try {
this.pageContext.getOut().write(this.handleToken(token));
}
catch (IOException ex) {
throw new JspException(ex);
}
}
return EVAL_PAGE;
}
protected abstract String handleToken(CsrfToken token);
}
| 1,414 | 26.745098 | 102 | java |
null | spring-security-main/taglibs/src/main/java/org/springframework/security/taglibs/csrf/CsrfInputTag.java | /*
* Copyright 2002-2014 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.taglibs.csrf;
import org.springframework.security.web.csrf.CsrfToken;
/**
* A JSP tag that prints out a hidden form field for the CSRF token. See the JSP Tab
* Library documentation for more information.
*
* @author Nick Williams
* @since 3.2.2
*/
public class CsrfInputTag extends AbstractCsrfTag {
@Override
public String handleToken(CsrfToken token) {
return "<input type=\"hidden\" name=\"" + token.getParameterName() + "\" value=\"" + token.getToken() + "\" />";
}
}
| 1,147 | 30.888889 | 114 | java |
null | spring-security-main/taglibs/src/main/java/org/springframework/security/taglibs/authz/package-info.java | /*
* Copyright 2002-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* JSP Security tag library implementation.
*/
package org.springframework.security.taglibs.authz;
| 727 | 33.666667 | 75 | java |
null | spring-security-main/taglibs/src/main/java/org/springframework/security/taglibs/authz/AuthenticationTag.java | /*
* Copyright 2004, 2005, 2006 Acegi Technology Pty Limited
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.taglibs.authz;
import java.io.IOException;
import jakarta.servlet.ServletContext;
import jakarta.servlet.jsp.JspException;
import jakarta.servlet.jsp.PageContext;
import jakarta.servlet.jsp.tagext.Tag;
import jakarta.servlet.jsp.tagext.TagSupport;
import org.springframework.beans.BeanWrapperImpl;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.context.SecurityContextHolderStrategy;
import org.springframework.security.web.context.support.SecurityWebApplicationContextUtils;
import org.springframework.security.web.util.TextEscapeUtils;
import org.springframework.web.util.TagUtils;
/**
* An {@link jakarta.servlet.jsp.tagext.Tag} implementation that allows convenient access
* to the current <code>Authentication</code> object.
* <p>
* Whilst JSPs can access the <code>SecurityContext</code> directly, this tag avoids
* handling <code>null</code> conditions.
*
* @author Thomas Champagne
*/
public class AuthenticationTag extends TagSupport {
private SecurityContextHolderStrategy securityContextHolderStrategy = SecurityContextHolder
.getContextHolderStrategy();
private String var;
private String property;
private int scope;
private boolean scopeSpecified;
private boolean htmlEscape = true;
public AuthenticationTag() {
init();
}
// resets local state
private void init() {
this.var = null;
this.scopeSpecified = false;
this.scope = PageContext.PAGE_SCOPE;
}
public void setVar(String var) {
this.var = var;
}
public void setProperty(String operation) {
this.property = operation;
}
public void setScope(String scope) {
this.scope = TagUtils.getScope(scope);
this.scopeSpecified = true;
}
public void setPageContext(PageContext pageContext) {
super.setPageContext(pageContext);
ServletContext servletContext = pageContext.getServletContext();
ApplicationContext context = SecurityWebApplicationContextUtils
.findRequiredWebApplicationContext(servletContext);
String[] names = context.getBeanNamesForType(SecurityContextHolderStrategy.class);
if (names.length == 1) {
SecurityContextHolderStrategy strategy = context.getBean(SecurityContextHolderStrategy.class);
this.securityContextHolderStrategy = strategy;
}
}
@Override
public int doStartTag() throws JspException {
return super.doStartTag();
}
@Override
public int doEndTag() throws JspException {
Object result = null;
// determine the value by...
if (this.property != null) {
SecurityContext context = this.securityContextHolderStrategy.getContext();
if ((context == null) || !(context instanceof SecurityContext) || (context.getAuthentication() == null)) {
return Tag.EVAL_PAGE;
}
Authentication auth = context.getAuthentication();
if (auth.getPrincipal() == null) {
return Tag.EVAL_PAGE;
}
try {
BeanWrapperImpl wrapper = new BeanWrapperImpl(auth);
result = wrapper.getPropertyValue(this.property);
}
catch (BeansException ex) {
throw new JspException(ex);
}
}
if (this.var != null) {
/*
* Store the result, letting an IllegalArgumentException propagate back if the
* scope is invalid (e.g., if an attempt is made to store something in the
* session without any HttpSession existing).
*/
if (result != null) {
this.pageContext.setAttribute(this.var, result, this.scope);
}
else {
if (this.scopeSpecified) {
this.pageContext.removeAttribute(this.var, this.scope);
}
else {
this.pageContext.removeAttribute(this.var);
}
}
}
else {
if (this.htmlEscape) {
writeMessage(TextEscapeUtils.escapeEntities(String.valueOf(result)));
}
else {
writeMessage(String.valueOf(result));
}
}
return EVAL_PAGE;
}
protected void writeMessage(String msg) throws JspException {
try {
this.pageContext.getOut().write(String.valueOf(msg));
}
catch (IOException ioe) {
throw new JspException(ioe);
}
}
/**
* Set HTML escaping for this tag, as boolean value.
*/
public void setHtmlEscape(String htmlEscape) {
this.htmlEscape = Boolean.parseBoolean(htmlEscape);
}
/**
* Return the HTML escaping setting for this tag, or the default setting if not
* overridden.
*/
protected boolean isHtmlEscape() {
return this.htmlEscape;
}
}
| 5,203 | 28.235955 | 109 | java |
null | spring-security-main/taglibs/src/main/java/org/springframework/security/taglibs/authz/JspAuthorizeTag.java | /*
* Copyright 2002-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.taglibs.authz;
import java.io.IOException;
import java.util.List;
import jakarta.servlet.ServletContext;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;
import jakarta.servlet.jsp.JspException;
import jakarta.servlet.jsp.PageContext;
import jakarta.servlet.jsp.tagext.Tag;
import org.springframework.expression.BeanResolver;
import org.springframework.expression.ConstructorResolver;
import org.springframework.expression.EvaluationContext;
import org.springframework.expression.MethodResolver;
import org.springframework.expression.OperatorOverloader;
import org.springframework.expression.PropertyAccessor;
import org.springframework.expression.TypeComparator;
import org.springframework.expression.TypeConverter;
import org.springframework.expression.TypeLocator;
import org.springframework.expression.TypedValue;
import org.springframework.security.access.expression.SecurityExpressionHandler;
import org.springframework.security.taglibs.TagLibConfig;
import org.springframework.security.web.FilterInvocation;
/**
* A JSP {@link Tag} implementation of {@link AbstractAuthorizeTag}.
*
* @author Rossen Stoyanchev
* @since 3.1.0
* @see AbstractAuthorizeTag
*/
public class JspAuthorizeTag extends AbstractAuthorizeTag implements Tag {
private Tag parent;
protected PageContext pageContext;
protected String id;
private String var;
private boolean authorized;
/**
* Invokes the base class {@link AbstractAuthorizeTag#authorize()} method to decide if
* the body of the tag should be skipped or not.
* @return {@link Tag#SKIP_BODY} or {@link Tag#EVAL_BODY_INCLUDE}
*/
@Override
public int doStartTag() throws JspException {
try {
this.authorized = super.authorize();
if (!this.authorized && TagLibConfig.isUiSecurityDisabled()) {
this.pageContext.getOut().write(TagLibConfig.getSecuredUiPrefix());
}
if (this.var != null) {
this.pageContext.setAttribute(this.var, this.authorized, PageContext.PAGE_SCOPE);
}
return TagLibConfig.evalOrSkip(this.authorized);
}
catch (IOException ex) {
throw new JspException(ex);
}
}
@Override
protected EvaluationContext createExpressionEvaluationContext(SecurityExpressionHandler<FilterInvocation> handler) {
return new PageContextVariableLookupEvaluationContext(super.createExpressionEvaluationContext(handler));
}
/**
* Default processing of the end tag returning EVAL_PAGE.
* @return EVAL_PAGE
* @see Tag#doEndTag()
*/
@Override
public int doEndTag() throws JspException {
try {
if (!this.authorized && TagLibConfig.isUiSecurityDisabled()) {
this.pageContext.getOut().write(TagLibConfig.getSecuredUiSuffix());
}
}
catch (IOException ex) {
throw new JspException(ex);
}
return EVAL_PAGE;
}
public String getId() {
return this.id;
}
public void setId(String id) {
this.id = id;
}
@Override
public Tag getParent() {
return this.parent;
}
@Override
public void setParent(Tag parent) {
this.parent = parent;
}
public String getVar() {
return this.var;
}
public void setVar(String var) {
this.var = var;
}
@Override
public void release() {
this.parent = null;
this.id = null;
}
@Override
public void setPageContext(PageContext pageContext) {
this.pageContext = pageContext;
}
@Override
protected ServletRequest getRequest() {
return this.pageContext.getRequest();
}
@Override
protected ServletResponse getResponse() {
return this.pageContext.getResponse();
}
@Override
protected ServletContext getServletContext() {
return this.pageContext.getServletContext();
}
private final class PageContextVariableLookupEvaluationContext implements EvaluationContext {
private EvaluationContext delegate;
private PageContextVariableLookupEvaluationContext(EvaluationContext delegate) {
this.delegate = delegate;
}
@Override
public TypedValue getRootObject() {
return this.delegate.getRootObject();
}
@Override
public List<ConstructorResolver> getConstructorResolvers() {
return this.delegate.getConstructorResolvers();
}
@Override
public List<MethodResolver> getMethodResolvers() {
return this.delegate.getMethodResolvers();
}
@Override
public List<PropertyAccessor> getPropertyAccessors() {
return this.delegate.getPropertyAccessors();
}
@Override
public TypeLocator getTypeLocator() {
return this.delegate.getTypeLocator();
}
@Override
public TypeConverter getTypeConverter() {
return this.delegate.getTypeConverter();
}
@Override
public TypeComparator getTypeComparator() {
return this.delegate.getTypeComparator();
}
@Override
public OperatorOverloader getOperatorOverloader() {
return this.delegate.getOperatorOverloader();
}
@Override
public BeanResolver getBeanResolver() {
return this.delegate.getBeanResolver();
}
@Override
public void setVariable(String name, Object value) {
this.delegate.setVariable(name, value);
}
@Override
public Object lookupVariable(String name) {
Object result = this.delegate.lookupVariable(name);
if (result == null) {
result = JspAuthorizeTag.this.pageContext.findAttribute(name);
}
return result;
}
}
}
| 5,866 | 24.620087 | 117 | java |
null | spring-security-main/taglibs/src/main/java/org/springframework/security/taglibs/authz/AbstractAuthorizeTag.java | /*
* Copyright 2004-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.taglibs.authz;
import java.io.IOException;
import java.util.Map;
import jakarta.servlet.ServletContext;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.context.ApplicationContext;
import org.springframework.core.GenericTypeResolver;
import org.springframework.expression.EvaluationContext;
import org.springframework.expression.Expression;
import org.springframework.expression.ParseException;
import org.springframework.security.access.expression.ExpressionUtils;
import org.springframework.security.access.expression.SecurityExpressionHandler;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.context.SecurityContextHolderStrategy;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.WebAttributes;
import org.springframework.security.web.access.WebInvocationPrivilegeEvaluator;
import org.springframework.security.web.context.support.SecurityWebApplicationContextUtils;
import org.springframework.util.StringUtils;
/**
* A base class for an <authorize> tag that is independent of the tag rendering
* technology (JSP, Facelets). It treats tag attributes as simple strings rather than
* strings that may contain expressions with the exception of the "access" attribute,
* which is always expected to contain a Spring EL expression.
* <p>
* Subclasses are expected to extract tag attribute values from the specific rendering
* technology, evaluate them as expressions if necessary, and set the String-based
* attributes of this class.
*
* @author Francois Beausoleil
* @author Luke Taylor
* @author Rossen Stoyanchev
* @author Rob Winch
* @since 3.1.0
*/
public abstract class AbstractAuthorizeTag {
private String access;
private String url;
private String method = "GET";
/**
* This method allows subclasses to provide a way to access the ServletRequest
* according to the rendering technology.
*/
protected abstract ServletRequest getRequest();
/**
* This method allows subclasses to provide a way to access the ServletResponse
* according to the rendering technology.
*/
protected abstract ServletResponse getResponse();
/**
* This method allows subclasses to provide a way to access the ServletContext
* according to the rendering technology.
*/
protected abstract ServletContext getServletContext();
/**
* Make an authorization decision by considering all <authorize> tag attributes.
* The following are valid combinations of attributes:
* <ul>
* <li>access</li>
* <li>url, method</li>
* </ul>
* The above combinations are mutually exclusive and evaluated in the given order.
* @return the result of the authorization decision
* @throws IOException
*/
public boolean authorize() throws IOException {
if (StringUtils.hasText(getAccess())) {
return authorizeUsingAccessExpression();
}
if (StringUtils.hasText(getUrl())) {
return authorizeUsingUrlCheck();
}
return false;
}
/**
* Make an authorization decision based on a Spring EL expression. See the
* "Expression-Based Access Control" chapter in Spring Security for details on what
* expressions can be used.
* @return the result of the authorization decision
* @throws IOException
*/
public boolean authorizeUsingAccessExpression() throws IOException {
if (getContext().getAuthentication() == null) {
return false;
}
SecurityExpressionHandler<FilterInvocation> handler = getExpressionHandler();
Expression accessExpression;
try {
accessExpression = handler.getExpressionParser().parseExpression(getAccess());
}
catch (ParseException ex) {
throw new IOException(ex);
}
return ExpressionUtils.evaluateAsBoolean(accessExpression, createExpressionEvaluationContext(handler));
}
/**
* Allows the {@code EvaluationContext} to be customized for variable lookup etc.
*/
protected EvaluationContext createExpressionEvaluationContext(SecurityExpressionHandler<FilterInvocation> handler) {
FilterInvocation f = new FilterInvocation(getRequest(), getResponse(), (request, response) -> {
throw new UnsupportedOperationException();
});
return handler.createEvaluationContext(getContext().getAuthentication(), f);
}
/**
* Make an authorization decision based on the URL and HTTP method attributes. True is
* returned if the user is allowed to access the given URL as defined.
* @return the result of the authorization decision
* @throws IOException
*/
public boolean authorizeUsingUrlCheck() throws IOException {
String contextPath = ((HttpServletRequest) getRequest()).getContextPath();
Authentication currentUser = getContext().getAuthentication();
return getPrivilegeEvaluator().isAllowed(contextPath, getUrl(), getMethod(), currentUser);
}
public String getAccess() {
return this.access;
}
public void setAccess(String access) {
this.access = access;
}
public String getUrl() {
return this.url;
}
public void setUrl(String url) {
this.url = url;
}
public String getMethod() {
return this.method;
}
public void setMethod(String method) {
this.method = (method != null) ? method.toUpperCase() : null;
}
private SecurityContext getContext() {
ApplicationContext appContext = SecurityWebApplicationContextUtils
.findRequiredWebApplicationContext(getServletContext());
String[] names = appContext.getBeanNamesForType(SecurityContextHolderStrategy.class);
if (names.length == 1) {
SecurityContextHolderStrategy strategy = appContext.getBean(SecurityContextHolderStrategy.class);
return strategy.getContext();
}
return SecurityContextHolder.getContext();
}
@SuppressWarnings({ "unchecked", "rawtypes" })
private SecurityExpressionHandler<FilterInvocation> getExpressionHandler() throws IOException {
ApplicationContext appContext = SecurityWebApplicationContextUtils
.findRequiredWebApplicationContext(getServletContext());
Map<String, SecurityExpressionHandler> handlers = appContext.getBeansOfType(SecurityExpressionHandler.class);
for (SecurityExpressionHandler handler : handlers.values()) {
if (FilterInvocation.class.equals(
GenericTypeResolver.resolveTypeArgument(handler.getClass(), SecurityExpressionHandler.class))) {
return handler;
}
}
throw new IOException("No visible WebSecurityExpressionHandler instance could be found in the application "
+ "context. There must be at least one in order to support expressions in JSP 'authorize' tags.");
}
private WebInvocationPrivilegeEvaluator getPrivilegeEvaluator() throws IOException {
WebInvocationPrivilegeEvaluator privEvaluatorFromRequest = (WebInvocationPrivilegeEvaluator) getRequest()
.getAttribute(WebAttributes.WEB_INVOCATION_PRIVILEGE_EVALUATOR_ATTRIBUTE);
if (privEvaluatorFromRequest != null) {
return privEvaluatorFromRequest;
}
ApplicationContext ctx = SecurityWebApplicationContextUtils
.findRequiredWebApplicationContext(getServletContext());
Map<String, WebInvocationPrivilegeEvaluator> wipes = ctx.getBeansOfType(WebInvocationPrivilegeEvaluator.class);
if (wipes.size() == 0) {
throw new IOException(
"No visible WebInvocationPrivilegeEvaluator instance could be found in the application "
+ "context. There must be at least one in order to support the use of URL access checks in 'authorize' tags.");
}
return (WebInvocationPrivilegeEvaluator) wipes.values().toArray()[0];
}
}
| 8,310 | 36.949772 | 118 | java |
null | spring-security-main/taglibs/src/main/java/org/springframework/security/taglibs/authz/AccessControlListTag.java | /*
* Copyright 2004, 2005, 2006 Acegi Technology Pty Limited
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.taglibs.authz;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import jakarta.servlet.ServletContext;
import jakarta.servlet.jsp.JspException;
import jakarta.servlet.jsp.PageContext;
import jakarta.servlet.jsp.tagext.Tag;
import jakarta.servlet.jsp.tagext.TagSupport;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.security.access.PermissionEvaluator;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.context.SecurityContextHolderStrategy;
import org.springframework.security.taglibs.TagLibConfig;
import org.springframework.security.web.context.support.SecurityWebApplicationContextUtils;
/**
* An implementation of {@link Tag} that allows its body through if all authorizations are
* granted to the request's principal.
* <p>
* One or more comma separate numeric are specified via the {@code hasPermission}
* attribute. The tag delegates to the configured {@link PermissionEvaluator} which it
* obtains from the {@code ApplicationContext}.
* <p>
* For this class to operate it must be able to access the application context via the
* {@code WebApplicationContextUtils} and attempt to locate the
* {@code PermissionEvaluator} instance. There cannot be more than one of these present
* for the tag to function.
*
* @author Ben Alex
* @author Luke Taylor
* @author Rob Winch
*/
public class AccessControlListTag extends TagSupport {
protected static final Log logger = LogFactory.getLog(AccessControlListTag.class);
private SecurityContextHolderStrategy securityContextHolderStrategy = SecurityContextHolder
.getContextHolderStrategy();
private ApplicationContext applicationContext;
private Object domainObject;
private PermissionEvaluator permissionEvaluator;
private String hasPermission = "";
private String var;
@Override
public int doStartTag() throws JspException {
if ((null == this.hasPermission) || "".equals(this.hasPermission)) {
return skipBody();
}
initializeIfRequired();
if (this.domainObject == null) {
logger.debug("domainObject resolved to null, so including tag body");
// Of course they have access to a null object!
return evalBody();
}
Authentication authentication = this.securityContextHolderStrategy.getContext().getAuthentication();
if (authentication == null) {
logger.debug("SecurityContextHolder did not return a non-null Authentication object, so skipping tag body");
return skipBody();
}
List<Object> requiredPermissions = parseHasPermission(this.hasPermission);
for (Object requiredPermission : requiredPermissions) {
if (!this.permissionEvaluator.hasPermission(authentication, this.domainObject, requiredPermission)) {
return skipBody();
}
}
return evalBody();
}
private List<Object> parseHasPermission(String hasPermission) {
String[] requiredPermissions = hasPermission.split(",");
List<Object> parsedPermissions = new ArrayList<>(requiredPermissions.length);
for (String permissionToParse : requiredPermissions) {
Object parsedPermission = permissionToParse;
try {
parsedPermission = Integer.parseInt(permissionToParse);
}
catch (NumberFormatException ex) {
}
parsedPermissions.add(parsedPermission);
}
return parsedPermissions;
}
private int skipBody() {
if (this.var != null) {
this.pageContext.setAttribute(this.var, Boolean.FALSE, PageContext.PAGE_SCOPE);
}
return TagLibConfig.evalOrSkip(false);
}
private int evalBody() {
if (this.var != null) {
this.pageContext.setAttribute(this.var, Boolean.TRUE, PageContext.PAGE_SCOPE);
}
return TagLibConfig.evalOrSkip(true);
}
/**
* Allows test cases to override where application context obtained from.
* @param pageContext so the <code>ServletContext</code> can be accessed as required
* by Spring's <code>WebApplicationContextUtils</code>
* @return the Spring application context (never <code>null</code>)
*/
protected ApplicationContext getContext(PageContext pageContext) {
ServletContext servletContext = pageContext.getServletContext();
return SecurityWebApplicationContextUtils.findRequiredWebApplicationContext(servletContext);
}
public Object getDomainObject() {
return this.domainObject;
}
public String getHasPermission() {
return this.hasPermission;
}
private void initializeIfRequired() throws JspException {
if (this.applicationContext != null) {
return;
}
this.applicationContext = getContext(this.pageContext);
this.permissionEvaluator = getBeanOfType(PermissionEvaluator.class);
String[] names = this.applicationContext.getBeanNamesForType(SecurityContextHolderStrategy.class);
if (names.length == 1) {
SecurityContextHolderStrategy strategy = this.applicationContext
.getBean(SecurityContextHolderStrategy.class);
this.securityContextHolderStrategy = strategy;
}
}
private <T> T getBeanOfType(Class<T> type) throws JspException {
Map<String, T> map = this.applicationContext.getBeansOfType(type);
for (ApplicationContext context = this.applicationContext.getParent(); context != null; context = context
.getParent()) {
map.putAll(context.getBeansOfType(type));
}
if (map.size() == 0) {
return null;
}
if (map.size() == 1) {
return map.values().iterator().next();
}
throw new JspException("Found incorrect number of " + type.getSimpleName() + " instances in "
+ "application context - you must have only have one!");
}
public void setDomainObject(Object domainObject) {
this.domainObject = domainObject;
}
public void setHasPermission(String hasPermission) {
this.hasPermission = hasPermission;
}
public void setVar(String var) {
this.var = var;
}
}
| 6,543 | 33.624339 | 111 | java |
null | spring-security-main/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/core/OpenSamlInitializationServiceTests.java | /*
* Copyright 2002-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.saml2.core;
import org.junit.jupiter.api.Test;
import org.opensaml.core.config.ConfigurationService;
import org.opensaml.core.xml.config.XMLObjectProviderRegistry;
import org.springframework.security.saml2.Saml2Exception;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
/**
* Tests for {@link OpenSamlInitializationService}
*
* @author Josh Cummings
*/
public class OpenSamlInitializationServiceTests {
@Test
public void initializeWhenInvokedMultipleTimesThenInitializesOnce() {
OpenSamlInitializationService.initialize();
XMLObjectProviderRegistry registry = ConfigurationService.get(XMLObjectProviderRegistry.class);
assertThat(registry.getParserPool()).isNotNull();
assertThatExceptionOfType(Saml2Exception.class)
.isThrownBy(() -> OpenSamlInitializationService.requireInitialize((r) -> {
})).withMessageContaining("OpenSAML was already initialized previously");
}
}
| 1,642 | 34.717391 | 97 | java |
null | spring-security-main/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/core/Saml2ResponseValidatorResultTests.java | /*
* Copyright 2002-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.saml2.core;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
/**
* Tests for verifying {@link Saml2ResponseValidatorResult}
*
* @author Josh Cummings
*/
public class Saml2ResponseValidatorResultTests {
private static final Saml2Error DETAIL = new Saml2Error("error", "description");
@Test
public void successWhenInvokedThenReturnsSuccessfulResult() {
Saml2ResponseValidatorResult success = Saml2ResponseValidatorResult.success();
assertThat(success.hasErrors()).isFalse();
}
@Test
public void failureWhenInvokedWithDetailReturnsFailureResultIncludingDetail() {
Saml2ResponseValidatorResult failure = Saml2ResponseValidatorResult.failure(DETAIL);
assertThat(failure.hasErrors()).isTrue();
assertThat(failure.getErrors()).containsExactly(DETAIL);
}
@Test
public void failureWhenInvokedWithMultipleDetailsReturnsFailureResultIncludingAll() {
Saml2ResponseValidatorResult failure = Saml2ResponseValidatorResult.failure(DETAIL, DETAIL);
assertThat(failure.hasErrors()).isTrue();
assertThat(failure.getErrors()).containsExactly(DETAIL, DETAIL);
}
@Test
public void concatErrorWhenInvokedThenReturnsCopyContainingAll() {
Saml2ResponseValidatorResult failure = Saml2ResponseValidatorResult.failure(DETAIL);
Saml2ResponseValidatorResult added = failure.concat(DETAIL);
assertThat(added.hasErrors()).isTrue();
assertThat(added.getErrors()).containsExactly(DETAIL, DETAIL);
assertThat(failure).isNotSameAs(added);
}
@Test
public void concatResultWhenInvokedThenReturnsCopyContainingAll() {
Saml2ResponseValidatorResult failure = Saml2ResponseValidatorResult.failure(DETAIL);
Saml2ResponseValidatorResult merged = failure.concat(failure).concat(failure);
assertThat(merged.hasErrors()).isTrue();
assertThat(merged.getErrors()).containsExactly(DETAIL, DETAIL, DETAIL);
assertThat(failure).isNotSameAs(merged);
}
@Test
public void concatErrorWhenNullThenIllegalArgument() {
// @formatter:off
assertThatIllegalArgumentException()
.isThrownBy(() -> Saml2ResponseValidatorResult.failure(DETAIL)
.concat((Saml2Error) null)
);
// @formatter:on
}
@Test
public void concatResultWhenNullThenIllegalArgument() {
// @formatter:off
assertThatIllegalArgumentException()
.isThrownBy(() -> Saml2ResponseValidatorResult.failure(DETAIL)
.concat((Saml2ResponseValidatorResult) null)
);
// @formatter:on
}
}
| 3,180 | 32.135417 | 94 | java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.