Google api redirect uri issue while reading google sheet from java

醉酒当歌 提交于 2021-01-28 06:12:26

问题


I am using oauth2 google drive API to read data from a google sheet in Java. I have an working sample on my local machine. But when I deploy it on the remote server, at the time of authentication the API returns a URL which is to be opened in browser. The URL is like below :

https://accounts.google.com/o/oauth2/auth?access_type=online&approval_prompt=auto&client_id=my.client.id&redirect_uri=http://**localhost:58305**/Callback&response_type=code&scope=https://www.googleapis.com/auth/drive

Obviously this URL will not open on remote server as there is no localhost.

My google developers console configuration while generating oauth client id:

  1. Application type : Web Application or Other

  2. Authorized JavaScript origins : My remote server origin

  3. Authorized redirect URIs : My remote server page

The authentication gets successfully done on my local machine when the Application type is Other. The same when deployed on remote server fails to authenticate because of the localhost string inside the authentication URL.

On the other hand when the application type is Web Application it gives me an error page on both localhost and remote server which has error like below even when I have added proper origins in the above options:

Error: redirect_uri_mismatch

The redirect URI in the request, http://localhost:59363/Callback, does not match the ones authorized for the OAuth client. Visit https://console.developers.google.com/apis/credentials/oauthclient/my.client.id?project=my.project.id to update the authorized redirect URIs.

I tried multiple options with the redirect URIs. But it gives same error.

  1. Is there any setting in the authentication where we can change the fix the localhost:59363 part ?
  2. Is application type : web application correct when I have to deploy this on production server as application type : other is for installed apps ?

回答1:


You need to set the redirect uri same as the one which you have provided in google console in your java code.

Take a look at https://developers.google.com/api-client-library/java/google-api-java-client/oauth2#web_server_applications

    @Override
  protected String getRedirectUri(HttpServletRequest req) throws ServletException, IOException {
    GenericUrl url = new GenericUrl(req.getRequestURL().toString());
    url.setRawPath("/oauth2callback");
    return url.build();
  }

You build your redirect url. Currently you are sending that as localhost:58305/Callback

update it and it should work




回答2:


You are using the wrong API credential type.

For your project go to: https://console.cloud.google.com/apis/credentials and choose an OAUTH2 credential (client ID of type: OTHER).



来源:https://stackoverflow.com/questions/45952624/google-api-redirect-uri-issue-while-reading-google-sheet-from-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!