Skip to content

Security enabled formLogin() returns 401 instead of 302 - in @SpringBootTest only #30155

Description

@membersound

The following test should pass, as when I run my application, I'm correctly redirected to the /login page. But I cannot assert that in a junit test:

@SpringBootTest
@AutoConfigureMockMvc
public class AuthenticationTest {
	@Autowired
	private WebTestClient webTestClient;

	@Test
	public void testLoginPage() {
		webTestClient.get()
				.uri("/person")
				.exchange()
				.expectStatus().isFound()  //fails due to status = 401 UNAUTHORIZED
				.expectStatus().is3xxRedirection();
	}
}

The full configuration is:

@Configuration
public class ReactiveSecurityConfiguration {
	@Bean
	public SecurityWebFilterChain securityWebFilterChain(ServerHttpSecurity http) {
		return http
				.authorizeExchange()
				.anyExchange().authenticated()
				.and().formLogin()
				.and().httpBasic()
				.and().build();
	}
}

@RestController
public class PersonServlet {
	@GetMapping("/person")
	public Mono<Void> person() {
		return Mono.empty();
	}
}

@SpringBootApplication
public class MainApp {
	public static void main(String[] args) {
		SpringApplication.run(MainApp.class, args);
	}
}

artifacts:

   <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.6.4</version>
        <relativePath/>
    </parent>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-webflux</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

Metadata

Metadata

Assignees

No one assigned

    Labels

    for: stackoverflowA question that's better suited to stackoverflow.comstatus: invalidAn issue that we don't feel is valid

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions