java - 使用java从Oauth2 rest api获取访问令牌
问题描述
我需要调用 Oauth2 ResT API 服务来通过它从 JSON 文件中获取访问令牌和 expire_in 值。
下面是一个示例 CURL,我需要使用 JAVA 调用它我是 JAVA 的初学者,所以无法弄清楚如何做到这一点,但我可以使用 shell 脚本来做到这一点。
curl -u 'ClientId:Clientaccesskey' https://oauth2.url/oauth/token -X POST -d 'response_type=token&client_id=ClientId&username=user&password=userpassword&scope=process&grant_type=password'
上述 curl 命令返回的 JSON 示例——
{"access_token":"accessTokentobefetched","token_type":"bearer","refresh_token":"refreshToken","expires_in":7199,"scope":"process","jti":"somehexadecimalvaliu"}
在 shell 脚本中,我们可以使用 AWK 命令和其他命令获取访问令牌和其他字段的值。
所以我需要在 JAVA 中调用这个 CURL 命令并从 JSON 文件中获取访问令牌和其他键的值。
欢迎任何可以帮助我开始的帮助,因为我是 JAVA 和学习的新手。
解决方案
您可以使用很多库来帮助您从 Java 发出常规的 HTTP POST 请求,但由于您似乎需要发送纯text/plain
正文内容 - 我建议您使用okhttp3。这是一个相当轻量级且易于使用的 HTTP 客户端。
您需要将以下依赖项添加到您的 pom.xml,从 https://mvnrepository.com/artifact/com.squareup.okhttp3/okhttp/4.7.2获取:
<!-- https://mvnrepository.com/artifact/com.squareup.okhttp3/okhttp -->
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>4.7.2</version>
</dependency>
如果您使用的是 gradle,只需访问前面提到的 URL,并获取 gradle 等效依赖项声明。
这是一个完整的类,它说明了如何使用 okhttp3 客户端执行 POST 请求,并提取返回值。此示例希望您使用spring-boot-starter-web
依赖项(这将包括示例中使用的 jackson 和 tomcat 库)。
package com.example.demo;
import com.fasterxml.jackson.databind.ObjectMapper;
import okhttp3.*;
import org.apache.tomcat.util.codec.binary.Base64;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
@Component
public class TokenRequester {
public String getAccessToken() throws IOException {
// Create a new HTTP client
OkHttpClient client = new OkHttpClient().newBuilder().build();
// Create the request body
MediaType mediaType = MediaType.parse("text/plain");
RequestBody body = RequestBody.create(mediaType, "response_type=token&client_id=ClientId&username=user&password=userpassword&scope=process&grant_type=password");
// Build the request object, with method, headers
Request request = new Request.Builder()
.url("https://oauth2.url/oauth/token")
.method("POST", body)
.addHeader("Authorization", createAuthHeaderString("ClientId", "Clientaccesskey"))
.addHeader("Content-Type", "text/plain")
.build();
// Perform the request, this potentially throws an IOException
Response response = client.newCall(request).execute();
// Read the body of the response into a hashmap
Map<String,Object> responseMap = new ObjectMapper().
readValue(response.body().byteStream(), HashMap.class);
// Read the value of the "access_token" key from the hashmap
String accessToken = (String)responseMap.get("access_token");
// Return the access_token value
return accessToken;
}
// Just a helper metod to create the basic auth header
private String createAuthHeaderString(String username, String password) {
String auth = username + ":" + password;
byte[] encodedAuth = Base64.encodeBase64(auth.getBytes(StandardCharsets.US_ASCII));
String authHeader = "Basic " + new String(encodedAuth);
return authHeader;
}
}
您可能需要在这里调整一些东西。我可以要求你提供 curl 命令的详细输出,以便确定编码 - 但是试试这个,看看你得到了什么?
推荐阅读
- php - WordPress - 自定义帖子类型类别的简码
- apache-spark - 如何在 selectExpr 中执行多个表达式
- python - PANDAS:删除索引值并在 Excel 中将一个单元格中的值拆分为不同的行
- alexa - 如何从 Alexa Skill 中的用户随机输入中提取自定义插槽
- ios - SwiftUI:在填充的水平图像中制作 y 偏移的永久动画
- c# - Visual Studio 2019:禁用自动格式化
- python-3.x - Python 比较两个或多个整数值并打印出较高的值,包括。变量名
- r - R如何将年份合并为时期
- javascript - 如何以 Angular 6 及更高版本将画布内容下载为 svg(.svg 扩展名)图像/文件
- r - 在R中将两个不同的数据表合并为一个