简体   繁体   中英

Spring Losing Security Context during Testing

I have a Spring Boot integration test like this:

@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@ActiveProfiles("Test")
@RunWith(SpringRunner.class)
public class HelloControllerIT {
    @Autowired
    protected TestRestTemplate template;

    @Test
    public void test1() throws Exception {
        HttpEntity request = //buildJson;
        ResponseEntity response = template.exchange("/put", HttpMethod.PUT, request, Object.class);
        assertThat(response.getStatusCode()).isEqualTo(HttpStatus.CREATED);
    }
}

When the template sends the request, there's a point in my code that looks like this:

SecurityContext context = SecurityContextHolder.getContext();
Authentication authentication = context.getAuthentication();

Here's what the context looks like this: 在此处输入图片说明

I need to set the security context so that it's not anonymous. I can do it like this:

SecurityContext context = SecurityContextHolder.createEmptyContext();
context.setAuthentication(authResult);
SecurityContextHolder.setContext(context);

But when I try to do that before template.exchange I still get anonymousUser. I've tried this:

template.withBasicAuth("User","pass");

It still doesn't work. How do I set the TestRestTemplate security context?

I figured it out. You need to create a class that implements WebSecurityConfigurerAdapter and then set the context there. This was you can avoid any sort of mocking which I was keen on doing to make this a more ETE integration test. Here's that class

public class TestSecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.csrf().disable().authorizeRequests().anyRequest().permitAll().and().securityContext().securityContextRepository(new TestSecurityContextRepository());
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM