gpt4 book ai didi

java - Google oauth java 客户端获取访问 token 失败,出现 “400 Bad Request { ” 错误“: ”invalid_request“}”

转载 作者:行者123 更新时间:2023-12-02 07:23:50 24 4
gpt4 key购买 nike

这个问题是我上一个问题的后续问题

Google oauth java client to get an access token fails with "400 Bad Request { "error" : "invalid_request" }"

我深入研究了 JAVA API,以解决在 google 的 oAuth API 中为 authToken 交换代码的问题,但无法找到答案。因此我选择了一条非常简单的路线。

我创建了以下 JSP

index.jsp

<%@page import="java.net.URLEncoder"%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<a href="https://accounts.google.com/o/oauth2/auth?
scope=https://gdata.youtube.com/&
redirect_uri=<%=URLEncoder.encode("http://localhost:8080/BroadCastr/step2.jsp","UTF-8")%>&
response_type=code&
client_id=X985XXXXXXXX.apps.googleusercontent.com&approval_prompt=force">Connect google account</a>
</body>
</html>

此页面向我提供了一个简单的链接“连接 Google 帐户”,该链接成功地将我带到了 Google 页面,在该页面中我必须“允许”我的应用代表我访问 YouTube

在step2.jsp中

<%@page import="java.net.URLEncoder"%>
<%@page import="java.util.Iterator"%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>

<form id="frm" method="post" action="https://accounts.google.com/o/oauth2/token" enctype="application/x-www-form-urlencoded">
<input type="hidden" name="code" value="<%=URLEncoder.encode(request.getParameter("code"),"UTF-8")%>"/>
<input type="hidden" name="client_id" value="XXXXXXXXXXX.apps.googleusercontent.com"/>
<input type="hidden" name="client_secret" value="XXXXxxxxXXXXXX"/>
<input type="hidden" name="redirect_uri" value="<%=URLEncoder.encode("http://localhost:8080/BroadCastr/step3.jsp","UTF-8")%>"/>
<input type="hidden" name="grant_type" value="authorization_code"/>
<input type="hidden" name="scope" value=""/>
</form>
</body>
</html>
<script>
document.getElementById("frm").submit();
</script>

但最终step2.jsp将自身提交到谷歌的服务器,我得到的只是无用的JSON

{
"error": "invalid_request"
}

我将非常感谢对此的任何帮助。谢谢

最佳答案

在向访问 token 端点发送 POST 时,所需参数不应进行 URL 编码(至少对于 google API 而言)。

此处,redirect_uri 参数经过编码,因此与客户端注册时使用的参数不同,导致 invalid_request

根据上述 JSP 代码,如果 redirect_uri 参数固定, token 服务器响应可能会导致 invalid_grant,如 code也正在被编码。通常,Google 会发出授权码,该授权码对 url 不友好。

删除上面的 coderedirect_uri 参数的编码应该会导致服务器响应包含访问 token 。

关于java - Google oauth java 客户端获取访问 token 失败,出现 “400 Bad Request { ” 错误“: ”invalid_request“}”,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13815041/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com