【问题标题】:Google API - Redirect URI mismatch errorGoogle API - 重定向 URI 不匹配错误
【发布时间】:2014-08-07 11:56:38
【问题描述】:

我正在我的网络应用程序上实现 google+ 登录。 我通过引用此link 进行了尝试。

我的 google+ 登录按钮如下:

<div id="signinButton">
    <span class="g-signin"
    data-scope="https://www.googleapis.com/auth/plus.login"
    data-clientid=[MY_CLIENT_ID] 
    data-accesstype="offline"
    data-cookiepolicy="single_host_origin"
    data-callback="signInCallback"> </span>
</div>

我已经复制了我网页上面链接中给出的js。

获得授权码后,我将其转发到我的 servlet,下面是我形成 url 以获取 tokenResponse 的实现。 注意:我没有将谷歌库用于服务器端实现。

这是我的 url 形成代码:

String httpsURL = "https://accounts.google.com/o/oauth2/token";

     String query = "code="+code; 
     query += "&";
     query += "client_id=[MY_CLIENT_ID]&";
     query += "client_secret=[CLIENT_SECRET]&";
     query += "redirect_uri=https://localhost:8443/oauth2callback&";
     query += "grant_type=authorization_code";

     try{
     URL myurl = new URL(httpsURL);
     HttpsURLConnection con = (HttpsURLConnection)myurl.openConnection();
     con.setRequestMethod("POST");
     con.setRequestProperty("Content-length", String.valueOf(query.length()));
     con.setRequestProperty("Content-Type","application/x-www-form-urlencoded"); 
     con.setDoOutput(true); 
     con.setDoInput(true); 
     con.connect();
     OutputStreamWriter wr = new OutputStreamWriter(con.getOutputStream());
     wr.write(query);
     wr.flush();
     InputStream is;
     if (con.getResponseCode() == 200) {
         is = con.getInputStream();
     } else {
         is = con.getErrorStream();
     }
     //URLConnection con = url.openConnection();
     //conn.setDoOutput(true);
     // Get the response
     BufferedReader rd = new BufferedReader(new InputStreamReader(is));
     String line;
     while ((line = rd.readLine()) != null)
     {
         System.out.println("-----" + line);
     }
     wr.close();
     rd.close();
     }catch(Exception e){
        e.printStackTrace();
     }

在开发者控制台上,我的重定向 uri 与上面代码示例中给出的相同。

执行完这一切后,每次我得到这个:“error”:“redirect_uri_mismatch”。

这方面有很多问题,但都没有解决我的问题。

任何建议将不胜感激。提前致谢。

【问题讨论】:

    标签: java oauth-2.0 google-plus


    【解决方案1】:

    问题在于您使用的是 Google+ 登录,它使用您的重定向 URI。相反,它使用了一个神奇的 URI postmessage

    您不需要将postmessage 添加到开发者控制台(the directions(步骤 1,第 7c 项)通常说要完全清除此字段),但您确实需要使用当您将代码交换为令牌时(参见step 8 中的示例代码)。

    所以你上面的代码应该更像

     String query = "code="+code; 
     query += "&";
     query += "client_id=[MY_CLIENT_ID]&";
     query += "client_secret=[CLIENT_SECRET]&";
     query += "redirect_uri=postmessage&";
     query += "grant_type=authorization_code";
    

    【讨论】:

    • 非常感谢......我在这上面浪费了很多时间。它现在正在工作。 :)
    • 很高兴为您提供帮助。如果它对您有用,请考虑通过单击答案旁边的复选标记将其从空心切换为绿色,将其作为 StackOverflow 中的答案。您也可以通过点击向上箭头来投票。
    猜你喜欢
    • 2021-12-10
    • 2015-08-09
    • 1970-01-01
    • 2021-11-26
    • 2017-11-28
    • 2017-12-10
    • 1970-01-01
    • 1970-01-01
    • 2016-01-08
    相关资源
    最近更新 更多