1

この質問は私の前の質問に続いてあります

アクセストークンを取得するためのGoogleoauthjavaクライアントは、「400 Bad Request {"error":"invalid_request"}」で失敗します

GoogleのoAuthAPIでauthTokenのコードを交換する問題を解決するために、JAVA APIに飛び込みましたが、答えがわかりませんでした。したがって、私は非常に単純なルートを進めました。

以下の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アカウントに接続」という簡単なリンクが表示され、アプリが自分に代わってYouTubeにアクセスすることを「許可」する必要があるGoogleページに正常に移動できました。

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は自分自身をGoogleのサーバーに送信します。私が得るのは、役に立たないJSONをフォローすることだけです。

{
"error": "invalid_request"
}

私はこれについてどんな助けでも本当に感謝します。ありがとう

4

1 に答える 1

3

アクセストークンのエンドポイントにPOSTを作成するときは、必要なパラメータをURLエンコードしないでください(少なくともGoogle APIに対して)。

ここでは、redirect_uriパラメータがエンコードされているため、クライアント登録時に使用されたものと同じではありませんinvalid_request

上記のJSPコードに基づいて、redirect_uriパラメータが固定されている場合、トークンサーバーの応答は、もエンコードさinvalid_grantれているため、結果になる可能性があります。code通常、Googleは認証コードを発行しますが、これはURLに対応していません。

上記のエンコーディングcoderedirect_uriパラメータを削除すると、アクセストークンを含むサーバー応答が生成されます。

于 2012-12-11T20:31:00.850 に答える