【发布时间】:2018-06-06 00:09:00
【问题描述】:
我准备并扩展了这个运行良好的existing spring example。您可以简单地使用“用户”和“密码”登录,然后您会被转发到用户/索引。
使用这个控制器
@Controller
public class LoginController {
@GetMapping("/login")
public String login() {
return "login";
}
@GetMapping("/login-error")
public String loginError(Model model) {
model.addAttribute("loginError", true);
return "login";
}
}
但是一旦我运行使用 WebClient 的示例测试,相同的登录就会导致异常:
com.gargoylesoftware.htmlunit.FailingHttpStatusCodeException: 405 Request method 'POST' not supported for http://localhost:8080/login
这很奇怪,因为应用程序本身运行良好。
编辑:这是导致问题的测试方法
@And("^the user clicks the login button$")
public void theUserClicksTheLoginButton() throws IOException {
page = page.getElementById("login").click();
}
没想到WebClient的click方法是使用POST,而不是真正执行html中的输入字段。
<form th:action="@{/login}" method="post">
<label for="username">Username</label>:
<input type="text" id="username" name="username" autofocus="autofocus" /> <br />
<label for="password">Password</label>:
<input type="password" id="password" name="password" /> <br />
<input type="submit" id="login" value="Log in" />
</form>
编辑 2:
好吧,也许我应该澄清一下我的问题。
我知道应该通过 POST 进行登录,而我的 @Controller 只提供 @GetMapping 但这没关系,因为 spring security 正在处理 POST 请求,正如我在登录时在标题中看到的那样:
我的问题是为什么它在运行应用程序时工作正常,以及为什么在使用 WebClient 时它没有相同的行为。
【问题讨论】:
-
你在使用 Spring Security 吗?
-
是的,我愿意 -> 查看 build.gradle 和
org.springframework.security.samples.config.SecurityConfig的依赖项 -
Spring Security 提供了一个登录控制器,可以通过覆盖
configure(HttpSecurity http)方法来设置。 -
这应该是为了测试目的,让应用程序的行为与正常运行应用程序的方式相同?
-
这在 SecurityConfig.java link987654323@ 中已经完成了
标签: java spring-mvc spring-boot htmlunit spring-mvc-test