Java 使用 spring restTemplate 的 REST API 基本身份验证

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21920268/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 11:24:11  来源:igfitidea点击:

Basic authentication for REST API using spring restTemplate

javaspringresttemplatejira-rest-api

提问by shippi

I am completely new in RestTemplate and basically in the REST APIs also. I want to retrieve some data in my application via Jira REST API, but getting back 401 Unauthorised. Found and article on jira rest api documentationbut don't really know how to rewrite this into java as the example uses the command line way with curl. I would appreciate any suggestion or advice how to rewrite:

我是 RestTemplate 的新手,基本上也是 REST API。我想通过 Jira REST API 在我的应用程序中检索一些数据,但返回 401 Unauthorised。找到和关于jira rest api 文档的文章,但并不真正知道如何将其重写为 java,因为示例使用 curl 的命令行方式。我将不胜感激任何关于如何重写的建议或建议:

curl -D- -X GET -H "Authorization: Basic ZnJlZDpmcmVk" -H "Content-Type: application/json" "http://kelpie9:8081/rest/api/2/issue/QA-31"

into java using spring rest template. Where the ZnJlZDpmcmVk is a base64 encoded string of username:password. Thank you very much.

使用spring rest模板进入java。其中 ZnJlZDpmcmVk 是用户名:密码的 base64 编码字符串。非常感谢。

采纳答案by Angular University

Taken from the example on this site, I think this would be the most natural way of doing it, by filling in the header value and passing the header to the template.

取自本网站上示例,我认为这将是最自然的方法,即填写标头值并将标头传递给模板。

This is to fill in the header Authorization:

这是填写标题Authorization

String plainCreds = "willie:p@ssword";
byte[] plainCredsBytes = plainCreds.getBytes();
byte[] base64CredsBytes = Base64.encodeBase64(plainCredsBytes);
String base64Creds = new String(base64CredsBytes);

HttpHeaders headers = new HttpHeaders();
headers.add("Authorization", "Basic " + base64Creds);

And this is to pass the header to the REST template:

这是将标头传递给 REST 模板:

HttpEntity<String> request = new HttpEntity<String>(headers);
ResponseEntity<Account> response = restTemplate.exchange(url, HttpMethod.GET, request, Account.class);
Account account = response.getBody();

回答by Johnny Lim

Reference Spring Boot's TestRestTemplateimplementation as follows:

参考Spring Boot的TestRestTemplate实现如下:

https://github.com/spring-projects/spring-boot/blob/v1.2.2.RELEASE/spring-boot/src/main/java/org/springframework/boot/test/TestRestTemplate.java

https://github.com/spring-projects/spring-boot/blob/v1.2.2.RELEASE/spring-boot/src/main/java/org/springframework/boot/test/TestRestTemplate.java

Especially, see the addAuthentication() method as follows:

特别是,请参阅如下所示的 addAuthentication() 方法:

private void addAuthentication(String username, String password) {
    if (username == null) {
        return;
    }
    List<ClientHttpRequestInterceptor> interceptors = Collections
            .<ClientHttpRequestInterceptor> singletonList(new BasicAuthorizationInterceptor(
                    username, password));
    setRequestFactory(new InterceptingClientHttpRequestFactory(getRequestFactory(),
            interceptors));
}

Similarly, you can make your own RestTemplateeasily

同样,您可以RestTemplate轻松制作自己的

by inheritance like TestRestTemplateas follows:

通过继承TestRestTemplate如下:

https://github.com/izeye/samples-spring-boot-branches/blob/rest-and-actuator-with-security/src/main/java/samples/springboot/util/BasicAuthRestTemplate.java

https://github.com/izeye/samples-spring-boot-branches/blob/rest-and-actuator-with-security/src/main/java/samples/springboot/util/BasicAuthRestTemplate.java

回答by Nidham

Instead of instantiating as follows:

而不是实例化如下:

TestRestTemplate restTemplate = new TestRestTemplate();

Just do it like this:

只需这样做:

TestRestTemplate restTemplate = new TestRestTemplate(user, password);

It works for me, I hope it helps!

它对我有用,我希望它有帮助!

回答by Alex

You may use spring-boot RestTemplateBuilder

您可以使用 spring-boot RestTemplateBuilder

@Bean
RestOperations rest(RestTemplateBuilder restTemplateBuilder) {
    return restTemplateBuilder.basicAuthentication("user", "password").build();
}

See documentation

查看文档

(before SB 2.1.0 it was #basicAuthorization)

(在 SB 2.1.0 之前是#basicAuthorization

回答by Leon

(maybe) the easiest way without importing spring-boot.

(也许)不导入 spring-boot 的最简单方法。

restTemplate.getInterceptors().add(new BasicAuthorizationInterceptor("user", "password"));

回答by YanivJ

As of Spring 5.1 you can use HttpHeaders.setBasicAuth

从 Spring 5.1 开始,您可以使用 HttpHeaders.setBasicAuth

Create Basic Authorization header:

创建基本授权头:

String username = "willie";
String password = ":p@ssword";
HttpHeaders headers = new HttpHeaders();
headers.setBasicAuth(username, password);
...other headers goes here...

Pass the headers to the RestTemplate:

将标头传递给 RestTemplate:

HttpEntity<String> request = new HttpEntity<String>(headers);
ResponseEntity<Account> response = restTemplate.exchange(url, HttpMethod.GET, request, Account.class);
Account account = response.getBody();

Documentation: https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/http/HttpHeaders.html#setBasicAuth-java.lang.String-java.lang.String-

文档:https: //docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/http/HttpHeaders.html#setBasicAuth-java.lang.String-java.lang.String-

回答by attacomsian

There are multiple ways to add the basic HTTP authentication to the RestTemplate.

有多种方法可以将基本 HTTP 身份验证添加到RestTemplate.

1. For a single request

1. 对于单个请求

try {
    // request url
    String url = "https://jsonplaceholder.typicode.com/posts";

    // create auth credentials
    String authStr = "username:password";
    String base64Creds = Base64.getEncoder().encodeToString(authStr.getBytes());

    // create headers
    HttpHeaders headers = new HttpHeaders();
    headers.add("Authorization", "Basic " + base64Creds);

    // create request
    HttpEntity request = new HttpEntity(headers);

    // make a request
    ResponseEntity<String> response = new RestTemplate().exchange(url, HttpMethod.GET, request, String.class);

    // get JSON response
    String json = response.getBody();

} catch (Exception ex) {
    ex.printStackTrace();
}

If you are using Spring 5.1or higher, it is no longer required to manually set the authorization header. Use headers.setBasicAuth()method instead:

如果您使用的是 Spring5.1或更高版本,则不再需要手动设置授权标头。改用headers.setBasicAuth()方法:

// create headers
HttpHeaders headers = new HttpHeaders();
headers.setBasicAuth("username", "password");

2. For a group of requests

2.对于一组请求

@Service
public class RestService {

    private final RestTemplate restTemplate;

    public RestService(RestTemplateBuilder restTemplateBuilder) {
        this.restTemplate = restTemplateBuilder
                .basicAuthentication("username", "password")
                .build();
    }

   // use `restTemplate` instance here
}

3. For each and every request

3. 对于每一个请求

@Bean
RestOperations restTemplateBuilder(RestTemplateBuilder restTemplateBuilder) {
    return restTemplateBuilder.basicAuthentication("username", "password").build();
}

I hope it helps!

我希望它有帮助!