简体   繁体   English

使用RestTemplate的Rest API的基本身份验证

[英]Basic authendication for Rest API using RestTemplate

I am using spring mvc(Annotation based) with java. 我正在使用java的spring mvc(基于注解)。 I need to do rest API in my application. 我需要在应用程序中执行rest API。 I am very new to both API and REST. 我对API和REST都很陌生。 What are all the basic configuration need to do in my application for Rest? 我的Rest应用程序需要做哪些基本配置? I plan to use "RestTemplate" How to do the Basic authentication(passing username and password in URL headers) with RestTemplate ? 我计划使用“ RestTemplate”如何使用RestTemplate进行基本身份验证(在URL标头中传递用户名和密码)? Please anyone help me. 请任何人帮助我。

Thanks in advance. 提前致谢。

You have to add authetication header (where Base64 is for example from org.apache.commons.codec.binary.Base64 ): 您必须添加身份验证标头(例如,Base64来自org.apache.commons.codec.binary.Base64 ):

String plainCreds = "yourUsername@yourPassword";
byte[] plainCredsBytes = plainCreds.getBytes();
byte[] base64CredsBytes = Base64.encodeBase64(plainCredsBytes);
String base64Creds = new String(base64CredsBytes);
HttpHeaders headers = new HttpHeaders();
headers.add("Authorization", "Basic " + base64Creds);

and then add it into request: 然后将其添加到请求中:

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

For POST requests you can pass HttpEntity to standard postForObject() method 对于POST请求,您可以将HttpEntity传递给标准的postForObject()方法。

instead of "@" you must put ":" 代替“ @”,您必须输入“:”

String plainCreds = "yourUsername:yourPassword";
byte[] plainCredsBytes = plainCreds.getBytes();
byte[] base64CredsBytes = Base64.encodeBase64(plainCredsBytes);
String base64Creds = new String(base64CredsBytes);
HttpHeaders headers = new HttpHeaders();
headers.add("Authorization", "Basic " + base64Creds);

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM