Java 如何使用TestRestTemplate进行身份验证
假设我们有以下web安全配置:Java 如何使用TestRestTemplate进行身份验证,java,spring,spring-boot,spring-security,Java,Spring,Spring Boot,Spring Security,假设我们有以下web安全配置: http .and().formLogin() .loginProcessingUrl("/api/authentication") .successHandler(authenticationSuccessHandler) .failureHandler(authenticationFailureHandler) .usernameParameter("j_username") .passwor
http
.and().formLogin()
.loginProcessingUrl("/api/authentication")
.successHandler(authenticationSuccessHandler)
.failureHandler(authenticationFailureHandler)
.usernameParameter("j_username")
.passwordParameter("j_password")
.permitAll()
如何在集成测试中使用TestRestTemplate通过身份验证过程?
TestRestTemplate
提供了一个名为withBasicAuth()
的方法,因此您可以使用
testRestTemplate.withBasicAuth(
"user", "passwd").getForEntity(YOUR_URL, String.class)
如果您使用的是较旧的版本,您可以尝试以下内容
HttpHeaders headers = new HttpHeaders();
String auth = "userid" + ":" + "password";
byte[] encodedAuth = Base64.encode(auth.getBytes(Charset.forName("US-ASCII")));
String authHeader = "Basic " + new String( encodedAuth );
headers.set("Authorization", authHeader );
这样,您就可以自己生成身份验证头了
testrestemplate
提供了一个名为withBasicAuth()
的方法,这样您就可以像
testRestTemplate.withBasicAuth(
"user", "passwd").getForEntity(YOUR_URL, String.class)
如果您使用的是较旧的版本,您可以尝试以下内容
HttpHeaders headers = new HttpHeaders();
String auth = "userid" + ":" + "password";
byte[] encodedAuth = Base64.encode(auth.getBytes(Charset.forName("US-ASCII")));
String authHeader = "Basic " + new String( encodedAuth );
headers.set("Authorization", authHeader );
这样您就可以自己生成身份验证头了不幸的是,我使用的是旧版本的Spring Boot,而这种方法不可用。创建TestRestTemplate实例并指定用户名和密码不会改变任何内容。当我试图访问某个REST端点时,仍然会在响应中得到401HTTP代码。那么构造函数呢?我想您可以将用户名和密码传递给
testrestemplate
以便使用基本身份验证,如newtestrestemplate(“user”,“passwd”)
是的,我说的是使用接受用户名和密码的构造函数。什么也没发生。我仍然得到401错误代码。我将版本升级到1.4.1,并使用您前面提到的“withBasicAuth”方法。不幸的是,我仍然得到401 HTTP代码。您的authenticationManager
是如何配置的?不幸的是,我使用的是旧版本的Spring Boot,而此方法不可用。创建TestRestTemplate实例并指定用户名和密码不会改变任何内容。当我试图访问某个REST端点时,仍然会在响应中得到401HTTP代码。那么构造函数呢?我想您可以将用户名和密码传递给testrestemplate
以便使用基本身份验证,如newtestrestemplate(“user”,“passwd”)
是的,我说的是使用接受用户名和密码的构造函数。什么也没发生。我仍然得到401错误代码。我将版本升级到1.4.1,并使用您前面提到的“withBasicAuth”方法。不幸的是,我仍然得到401 HTTP代码。如何配置您的authenticationManager
?您可以检查:您可以检查: