Google oauth2 api client is not working properly

匆匆过客 提交于 2019-11-30 17:09:55

问题


Hi guys I have some code in my grails 2.3.4's controller's action that uses google java client libraries to access the OAuth2 api. But when I create an instance of GoogleAuthorizationCodeFlow I get redirect_uri_mismatch error. The url google gives me is this http://localhost:60720/Callback, while I have defined the callback url in the google api console as this http://localhost:8080/<myAppName>/<controllerName>/<actionName>. When I copy paste my redirected url manually in the address bar replacing the one google gave me, my application works well.

I've registered the application as web application not installed application in api console. What can I do? Please help. If I couldn't solve this problem then I'll revert to the REST Api.

ResourceLocator grailsResourceLocator



JsonFactory jsonFactory = JacksonFactory.defaultInstance

File clientSecretsFile = grailsResourceLocator.findResourceForURI("/configs/clientSecrets.json").file

GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(jsonFactory, new InputStreamReader(new FileInputStream(clientSecretsFile)))

HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport()

FileDataStoreFactory dataStoreFactory = new FileDataStoreFactory(new File(System.getProperty("user.home"), ".store/oauth2_sample"))

List<String> SCOPES = ["https://www.googleapis.com/auth/userinfo.profile", "https://www.googleapis.com/auth/userinfo.email"]

GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(httpTransport, jsonFactory, clientSecrets, SCOPES).setDataStoreFactory(dataStoreFactory).build()

Credential credential = new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver()).authorize("user")

Please help.... Thanks...


回答1:


Okey I've found the solution.

When you create new LocalServerReceiver() use instead new LocalServerReceiver.Builder().setPort(9089).build()

I've chosen some empty port in this case 9089. Actually LocalServerReceiver is a http server that listens to google and google sends code param to this server. Now all you have to do is create a new entry in your Redirected URIs which is in this case as follows: http://localhost:9089/Callback. Note the port number is same as I've used in the code while building the server using LocalServerReceiver.Builder() class.

And voila!!! you got the access_token and refresh_token from the google.

Happy coding... Happy Java clients...



来源:https://stackoverflow.com/questions/21002827/google-oauth2-api-client-is-not-working-properly

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