Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Google oauth2 api client is not working properly

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")

Thanks.

like image 275
Manvendra SK Avatar asked Jan 08 '14 17:01

Manvendra SK


1 Answers

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...

like image 191
Manvendra SK Avatar answered Jan 23 '23 03:01

Manvendra SK