如何使用TestRestTemplate进行身份验证

时间:2018-05-31 09:39:03

标签: java spring spring-boot spring-security

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

http
    .and().formLogin()
      .loginProcessingUrl("/api/authentication")
      .successHandler(authenticationSuccessHandler)
      .failureHandler(authenticationFailureHandler)
      .usernameParameter("j_username")
      .passwordParameter("j_password")
      .permitAll()

如何在集成测试中使用TestRestTemplate传递身份验证过程?

1 个答案:

答案 0 :(得分:0)

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 );

您自己生成身份验证标头

相关问题