我想向安全API发送请求。为此,我必须获取并使用身份验证令牌。我使用spring来请求对REST服务的令牌访问。
我有用户名和密码,content-Type,url(api.xxxxxx.com/v1/access/token)。获得将在15分钟后过期的令牌后,我需要从API获取信息。该服务返回JSON。
我没有找到任何有关如何开始的明确信息或代码。
我能够为不需要令牌的api做一个简单的代码
RestTemplate restTemplate = new RestTemplate();
Quote quote = restTemplate.getForObject("http://gturnquist-
quoters.cfapps.io/api/random",Quote.class);
log.info(quote.toString());
答案 0 :(得分:0)
承载令牌认证示例:
首先使用您的凭据发送请求以接收访问令牌:
String username = "" // your username
String password = "" // your password
String userAndPass = username + ":" + password;
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
headers.add("Authorization", "Basic " +
Base64Utility.encode(userAndPass.getBytes()));
HttpEntity<?> entity = new HttpEntity<>(headers);
String authUri = "" // uri to service which you get the token from
ResponseEntity<AuthenticationToken> response =
restTemplate.exchange(authUri, HttpMethod.POST, entity,
AuthenticationToken.class);
String token = response.getBody().getToken();
AuthenticationToken类:(注意我使用lombok生成getter和setter,你可以手动完成)
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
@JsonIgnoreProperties(ignoreUnknown = true)
public class AuthenticationToken {
@JsonProperty(value = "access_token")
String token;
}
现在您可以访问令牌,您可以将授权标头添加到每个其他请求中,如下所示:
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
headers.add("Authorization", "Bearer " + token);
HttpEntity<?> entity = new HttpEntity<>(headers);
ResponseEntity<Quote> response = restTemplate.getForObject(
"http://gturnquist-quoters.cfapps.io/api/random",
HttpMethod.GET, entity, Quote.class);