问题描述
我正在尝试通过Microsoft graph API读取存储在onedrive中的Excel文件。为此,在此基于控制台的应用程序中,我提供了我的租户ID,客户端机密和客户端ID,这些ID是通过Microsoft azure控制台生成的。通过api后,我将这些信息与身份验证URL一起传递,但是每当我运行代码时,我都会得到状态码400这意味着错误的请求。为什么返回400状态代码?我的方法有任何错误吗?
代码:
Authenticator.java
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonObject;
import com.microsoft.graph.authentication.IAuthenticationProvider;
import com.microsoft.graph.http.IHttpRequest;
public class Authenticator {
public final static String clientId = "XXXXXXXXXXXX";
public final static String clientSecret = "XXXXXXXXXXXXXX";
public final static String tenant = "XXXXXXXXXXXXXX";
private String grantType = "client_credentials";
private String tokenEndpoint = "https://login.microsoftonline.com/" +tenant + "/oauth2/v2.0/token";
private String scope = "https%3A%2F%2Fgraph.microsoft.com%2F.default";
private String accessToken = null;
protected IAuthenticationProvider authenticationProvider = null;
public Authenticator() { }
public IAuthenticationProvider getAuthenticationProvider()
{
if (authenticationProvider == null) {
try {
System.out.println(accessToken);
accessToken = getAccessToken().replace("\"","");
System.out.println(accessToken);
authenticationProvider = new IAuthenticationProvider() {
public void authenticateRequest(final IHttpRequest request) {
request.addHeader("Authorization","Bearer " + accessToken);
}
};
}
catch (Exception e)
{
throw new Error("Could not create authentication provider: " + e.getLocalizedMessage());
}
}
return authenticationProvider;
}
private String getAccessToken()
{
try {
URL url = new URL(tokenEndpoint);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
String line;
StringBuilder jsonString = new StringBuilder();
conn.setRequestProperty("Content-Type","application/x-www-form-urlencoded; charset=UTF-8");
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setInstanceFollowRedirects(false);
conn.connect();
String secret = clientSecret.replace("+","%2B").replace("=","%3D").replace("/","%2F");
OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream(),"UTF-8");
String payload = String.format("grant_type=%1$s&scope=%2$s&client_id=%3$s&client_secret=%4$s",grantType,scope,clientId,secret);
writer.write(payload);
writer.close();
try {
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
while((line = br.readLine()) != null){
jsonString.append(line);
}
br.close();
} catch (Exception e) {
e.printStackTrace();
throw new Error("Error reading authorization response: " + e.getLocalizedMessage());
}
conn.disconnect();
JsonObject res = new GsonBuilder().create().fromJson(jsonString.toString(),JsonObject.class);
return res.get("access_token").toString().replaceAll("\"","");
} catch (Exception e) {
throw new Error("Error retrieving access token: " + e.getLocalizedMessage());
}
}
}
ReadExcel.java
import com.microsoft.graph.authentication.IAuthenticationProvider;
import com.microsoft.graph.models.extensions.IGraphServiceClient;
import com.microsoft.graph.models.extensions.WorkbookRange;
import com.microsoft.graph.requests.extensions.GraphServiceClient;
public class ReadExcel {
public static IGraphServiceClient graphClient;
public static void main(String[] args) {
Authenticator authenticator = new Authenticator();
IAuthenticationProvider authenticationProvider = authenticator
.getAuthenticationProvider();
IGraphServiceClient graphClient = GraphServiceClient.builder().authenticationProvider( authenticationProvider ).buildClient();
WorkbookRange workbookRange = graphClient.me().drive().items("XXXXXXXXXX").workbook().worksheets("Sheet1")
.range("A1:B2")
.buildRequest()
.get();
}
}
错误: java.io.IOException:服务器返回URL的https://login.microsoftonline.com/f8cdef31-a31e-4b4a-93e4-5f571e91255a/oauth2/v2.0/token的HTTP响应代码:400
用于验证图形api的示例代码将受到高度赞赏。预先感谢。
Update-1:
更新了代码,并将“ oauth2-oidc-sdk”用于身份验证。如Micrsoft Graph教程示例代码中所述更新了我的代码。
Github链接:https://github.com/microsoftgraph/console-java-connect-sample
但是出现此错误-
{“错误”:“ invalid_grant”,“错误说明”:“ AADSTS9002313:请求无效。请求格式错误或无效。\ r \ n跟踪ID:c77ba129-89ec-4869-993d-55475fab4800 \ r \ n相关ID:34ce3c6b -b125-4c24-b57f-9716f320462c \ r \ n时间戳:2020-09-16 06:18:36Z“,”错误代码“:[9002313],”时间戳“:” 2020-09-16 06:18:36Z“, “ trace_id”:“ c77ba129-89ec-4869-993d-55475fab4800”,“ correlation_id”:“ 34ce3c6b-b125-4c24-b57f-9716f320462c”,“ error_uri”:“ https://login.microsoftonline.com/error?code = 9002313“}
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)