Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/319.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何使用TestRestTemplate进行身份验证_Java_Spring_Spring Boot_Spring Security - Fatal编程技术网

Java 如何使用TestRestTemplate进行身份验证

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

假设我们有以下web安全配置:

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
?您可以检查:您可以检查: