gpt4 book ai didi

spring-mvc - Spring Boot 测试 : Cannot Autowire springSecurityFilterChain on Test Class

转载 作者:行者123 更新时间:2023-12-05 07:58:38 33 4
gpt4 key购买 nike

在 spring boot 下设置测试上下文时,我仍在努力处理各种注释。

我一直在引用this article ,对于如何在 Spring Boot 下处理各种上下文,这让人耳目一新。剩下的问题是我似乎无法找到一个注释组合,使 springSecurityFilterChainma​​in application context 中可见(从这里驱动):

@EnableAutoConfiguration
@ComponentScan
public class Application {

public static void main(String[] args) throws Exception {
ApplicationContext ctx = SpringApplication.run(Application.class, args);
}

}

从此处开始的测试应用程序上下文:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {TestPersistenceConfig.class,MvcConfig.class,SecurityConfig.class},loader=AnnotationConfigContextLoader.class)
//@SpringApplicationConfiguration(classes = {TestPersistenceConfig.class,MvcConfig.class,SecurityConfig.class})
@WebAppConfiguration
public class ApplicationIntegrationTest {

MockMvc mockMvc;

@Autowired
private WebApplicationContext wac;

//@Resource(name="springSecurityFilterChain")
@Autowired
private FilterChainProxy springSecurityFilterChain;

@Autowired
private UserDao userDao;

@Autowired
private ClientDao clientDao;

@Autowired
private RoleDao roleDao;


UUID key = UUID.fromString("f3512d26-72f6-4290-9265-63ad69eccc13");


@Before
public void setup() {

// using the web application to initate the mock
mockMvc = MockMvcBuilders.webAppContextSetup(wac).addFilter(springSecurityFilterChain).build();

// our other choice is using another controller config
//mockMvc = MockMvcBuilders.annotationConfigSetup(ExampleApplicationContext.class).build();

// here we should build up the data structure using hibernate
List<Client> clients = new ArrayList<>();

Client clientEN = new Client();
clientEN.setDeviceId("444444444");
clientEN.setLanguage("en-EN");
clientEN.setAgentId("444444444|68:5b:35:8a:7c:d0");
Client clientENDomain = clientDao.save(clientEN);
clients.add(clientENDomain);

List<Role> roles = new ArrayList<>();
Role roleUser = new Role();
roleUser.setRole("user");
Role roleUserDomain = roleDao.save(roleUser);
roles.add(roleUserDomain);

Role roleAdmin = new Role();
roleAdmin.setRole("admin");
Role roleAdminDomain = roleDao.save(roleAdmin);
roles.add(roleAdminDomain);

User user = new User();
user.setLogin("user");
user.setPassword("password");
user.setClients(clients);
user.setRoles(roles);

userDao.save(user);

}

@Test
public void thatViewBootstrapUsesHttpNotFound() throws Exception {

// testing that a correct login into the form will result in a cookie being set
MvcResult result = mockMvc.perform(post("/login")
.param("username", "user").param("password", "password")).andReturn();
Cookie c = result.getResponse().getCookie("my-cookie");

Cookie[] cookies = result.getResponse().getCookies();
for (int i = 0; i <= cookies.length; i++) {
System.out.println("cookie " + i + " name: " + cookies[i].getName());
System.out.println("cookie " + i + " value: " + cookies[i].getValue());
}
//assertThat(c.getValue().length(), greaterThan(10));

// No cookie; 401 Unauthorized
mockMvc.perform(get("/")).andExpect(status().isUnauthorized());

// With cookie; 200 OK
mockMvc.perform(get("/").cookie(c)).andExpect(status().isOk());

// Logout, and ensure we're told to wipe the cookie
result = mockMvc.perform(delete("/session")).andReturn();
c = result.getResponse().getCookie("my-cookie");
assertThat(c.getValue().length(), is(0));
}

}

顺便说一下,@SpringApplicationConfiguration 似乎在任何情况下都不起作用,这与 doco 相反。安全配置如下:

@Configuration
@EnableWebMvcSecurity
@ComponentScan({
"com.touchcorp.touchpoint.security",
"com.touchcorp.touchpoint.service",
"com.touchcorp.touchpoint.model.dao"})
public class SecurityConfig extends WebSecurityConfigurerAdapter {


@Autowired
DeviceUsernamePasswordAuthenticationProvider customAuthenticationProvider;

@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {


auth
.authenticationProvider(customAuthenticationProvider);
}

@Configuration
@Order(1)
public static class ApiWebSecurityConfigurationAdapter extends WebSecurityConfigurerAdapter {
protected void configure(HttpSecurity http) throws Exception {
http
.antMatcher("/api/**")
.authorizeRequests()
.anyRequest().hasRole("ADMIN")
.and()
.httpBasic();
}
}

@Order(2)
@Configuration
public static class FormLoginWebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter {

@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.authorizeRequests()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.failureUrl("/login?error=1")
.permitAll()
.and()
.logout()
.logoutUrl("/logout")
.logoutSuccessUrl("/");
}
}

public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry
.addResourceHandler("/resources/**")
.addResourceLocations("/resources/")
.setCachePeriod(31556926);
}

}

谁能看出为什么 springSecurityFilterChain 是不可见的(“没有找到 FileterChainProxy 类型的 beans”)。谢谢,我正在拉扯我的头发。

我想我对所有注释的目的有点不清楚。 Spring Boot 引用很好,但它并没有真正超出已建立的基线。似乎一旦你必须将 spring security、hibernate 和 mvc 结合在一起,它就开始变得复杂,不清楚要做什么。

最佳答案

我会担心为什么 @SpringApplicationConfiguration 不起作用,因为它在其他地方被广泛使用(例如在 Spring Boot 示例中)并且在那里工作正常。也许是类路径问题?如何链接到其他人可以尝试重现您的问题的完整项目?

您有 2 个不同的应用程序上下文(一个用于测试,一个在您的 Application 中),因此如果它们的行为不同也就不足为奇了。特别是 Application@EnableAutoConfiguration 而你测试(据我们所知)没有,所以有一个区别值得研究。但测试没有明显错误。

这是一个 Autowiring 安全过滤器的测试示例:https://github.com/spring-projects/spring-security-oauth/blob/master/samples/oauth2/sparklr/src/test/java/org/springframework/security/samples/config/ApplicationConfigurationTests.java .有用。这是另一个:https://github.com/cloudfoundry/uaa/blob/master/uaa/src/test/java/org/cloudfoundry/identity/uaa/mock/audit/AuditCheckMvcMockTests.java .

关于spring-mvc - Spring Boot 测试 : Cannot Autowire springSecurityFilterChain on Test Class,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24133006/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com