Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get access token via Google JavaScript oauth2 API

http://api.chan15.info/google-stackoverflow.html

This is the sample code I use to let user login via Google JavaScript API, and it's work, next step is use user id to login to local server via PHP, but use the user id by JavaScript is pretty danger, the real procedure I want is:

  1. login user via JavaScript API
  2. get access_token from JavaScript
  3. pass the access token to PHP
  4. use access token to Google OAuth to get user id again by PHP
  5. login the user by user id

but I don't know how to get access token.

like image 559
Chan Avatar asked Apr 16 '15 22:04

Chan


People also ask

How do I get OAuth token from Google Drive?

Procedure. Go to Google Developers OAuth Playground. Click OAuth 2.0 Configuration and select Use your own OAuth credentials check box, enter the OAuth client ID and client secret you have already created in the OAuth Client ID and OAuth Client secret fields respectively.

How do I get OAuth2 access token node JS?

Register your client app on the authorization server to obtain credentials. Configure the endpoint used to redirect the user to the authorization server to authenticate and seek the user's consent. Configure the endpoint to be used to obtain the authorization token. Use this authorization token to get an access token.

How do I get access token for Google REST API?

Obtain an access token manually You will need to create a JSON Web Token (JWT) and sign it with the private key, then construct an access token request in the appropriate format. After that, your application sends the token request to the Google OAuth 2.0 Authorization Server and an access token gets returned.


1 Answers

After the user is logged in to their Google account using the Javascript Oauth2 API the access token can be found here:

gapi.auth2.getAuthInstance().currentUser.get().getAuthResponse().access_token;

I've used this to pass the token along to a separate curl PHP request as well as CORS. Since Google's JS API is still Beta I had to resort to sending a PHP curl request in the past. If you're planning to store the token for access after the user navigates away I'd also also get the token expiration date and call another function that wipes out the stored token whenever expired or explicitly revoked. But for me it was just easier to pull this right after successful login each time since I only needed to call the PHP function once and in real-time with AJAX as a bandaid.

PS: You might want to change the original category from Java to Javascript

like image 161
paulzmuda Avatar answered Sep 29 '22 05:09

paulzmuda