【问题标题】:Invalid grant in OAuth2 in GAE java apppGAME java应用程序中的OAuth2授权无效
【发布时间】:2012-07-04 21:47:10
【问题描述】:

您好,我正在尝试创建一个 GAE/J 应用程序,我必须在其中从给定代码中检索访问令牌

这是我的 /oauth2callback servlet 代码

public class OAuth2Callback extends HttpServlet{

    public void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws IOException {
    String url = "https://accounts.google.com/o/oauth2/token";

        // FetchOptions opt = FetchOptions.Builder.doNotValidateCertificate();
           URL url1=new URL(url); 
           String param="grant_type=authorization_code&code="+req.getParameter("code")+"&client_id=anonymouns&client_secret=anonymous&redirect_uri=https://www.cloudspokestest.appspot.com/oauth2callback";

   HttpURLConnection connection = 
        (HttpURLConnection)url1.openConnection(); 
             connection.setDoOutput(true); 
             connection.setRequestMethod("POST"); 
             connection.setRequestProperty("Content-type", "application/x-www-form-urlencoded");
             connection.getOutputStream().write( param.getBytes() ); 
          InputStream str= connection.getInputStream();
          BufferedReader reader=new BufferedReader(new InputStreamReader(str));
        String l="";
          while((l=reader.readLine())!=null){
              resp.getWriter().println(l);

          }


    }

}

但在浏览器屏幕上,我收到错误无效授权,响应代码为 400。任何人都可以帮助如何消除此错误。

【问题讨论】:

    标签: java google-app-engine oauth oauth-2.0


    【解决方案1】:

    您最有可能收到此错误,因为您的 url 中的参数值不是 url 编码的。 redirect_uri 的值,可能还有code 的值,必须是 url 编码的。

    您可以使用 java.net.URLEncoder 对值进行编码。

    也永远不要在字符串上使用getBytes(),因为它使用您平台的默认字符编码将字符转换为字节。在另一台机器上运行相同的代码,或更改机器配置可能会产生不同的输出。请始终使用getBytes(charsetname)

    【讨论】:

    • 顺便说一句,new InputStreamReader(str) 也是如此。这也将使用您的默认编码将字节转换为字符。请改用new InputStreamReader(str, charsetname)
    猜你喜欢
    • 2017-03-27
    • 2017-03-06
    • 1970-01-01
    • 2012-12-06
    • 1970-01-01
    • 1970-01-01
    • 2015-03-05
    • 1970-01-01
    • 2023-04-06
    相关资源
    最近更新 更多