Getting Access Token and Refresh Token by exchanging Authorization code using JavaScript

5,200 views
Skip to first unread message

SS237

unread,
Feb 3, 2013, 11:28:27 PM2/3/13
to google-api-jav...@googlegroups.com
Hi All,

I need to get access token and refresh token by exchanging authorization code , i have succeeded in getting authorization code and allow access but not able to get access token and refresh token ,

Below is my code,

<html>
       <head>
        <script src="https://apis.google.com/js/client.js?onload=load"></script>
     <script>
    function auth() {
   
    var config = {
               'client_id':'some id',
               'scope': 'https://www.googleapis.com/auth/analytics.readonly',
               ' access_type':'offline',
               'approval_prompt': 'force',
               'response_type':'code',
               
               
           };
         gapi.auth.authorize(config, function() {
               var code = gapi.auth.getToken().code;            
               sendRequest(gapi.auth.getToken().code);
                console.log (code);          
           });

    }
   
     function sendRequest(code) {      
          var  restRequest = gapi.client.request({
               'path': "https://accounts.google.com/o/oauth2/token",
               'method':'POST',
               'params': {
                 'code': code,
               'client_id': 'some id', 
               'client_secret':'tsome id',
                'rediredt_uri':'http://localhost:8085',
                'grant_type':'authorization_code',
            
               },
              
               'headers': {
                'Content-type': 'application/json'
                 },
                 
           });
     
         restRequest.execute(function(jsonResponse, rawResponse) { 
          rest = jsonResponse;
         });
    }
     </script>

  <body>
    <button onclick="auth();">Authorize</button>
  </body>
</html>

  I always get "POST 404 (NOT FOUND)" error.And i am stuck with this from many days.

Any help would be appreciated.

Regards,
SS237.

Edu rockcontent

unread,
Mar 20, 2015, 1:38:59 PM3/20/15
to google-api-jav...@googlegroups.com
You can try change the path to :


Tamás Bakonyi

unread,
May 6, 2015, 4:06:43 AM5/6/15
to google-api-jav...@googlegroups.com
Never ever request a refresh token on the client side.

Alexander Ivanov

unread,
May 6, 2015, 10:54:00 AM5/6/15
to google-api-jav...@googlegroups.com
I'm not sure that need to use 
'access_type':'offline'
'approval_prompt': 'force'
'client_secret': 'client_secret'

Because it's client-side API. "Using OAuth 2.0 for Client-side Applications" says:
These applications may access a Google API while the user is present at the application, and this type of application cannot keep a secret.


The simple way to use Google Client JS API is a call gapi.client.request().then()

We strongly recommend that you use promises instead of callbacks.

OK. Let's use.
var request = function requestF(){
    gapi
.client.request({
       
'path': '/analytics/v3/management/accounts',
       
'method': 'GET',
       
'params': {},
       
'headers': {},
       
'body': {}
   
}).then(onFulfilled, onRejected);
}

var onFulfilled = function onFulfilledF(e){
    console
.log('onFulfilled', e);
}

var onRejected = function onRejectedF(e){
    console
.log('onRejected', e);
}

Preparing
var CLIENT_ID = '123456.apps.googleusercontent.com';
var SCOPE = [ 'https://www.googleapis.com/auth/analytics.readonly' ];

var checkAuth = function checkAuthF() {
 gapi
.auth.authorize({
 
'client_id' : CLIENT_ID,
 
'immediate' : true,
 
'response_type' : 'token',
 
'scope' : SCOPE
 
}, handleAuthResult);
};

var handleAuthResult = function handleAuthResultF(authResult) {
 
var btn_auth = document.getElementById('btn_auth');
 
if (authResult && !authResult.error) {
 setTimeout
(checkAuth, (authResult.expires_in - 5 * 60) * 1000);
 btn_auth
.disabled = true;
 btn_auth
.onclick = null;
 request
();
 
} else {
 console
.warn('Authorization failed. User action is required.');
 btn_auth
.disabled = false;
 btn_auth
.onclick = handleAuthClick;
 
}
}

var handleAuthClick = function handleAuthClickF(event) {
 
event.preventDefault();
 gapi
.auth.authorize({
 
'client_id' : CLIENT_ID,
 
'immediate' : false,
 
'response_type' : 'token',
 
'scope' : SCOPE
 
}, handleAuthResult);
}

The code above uses authorize, check login, auto refresh token, UI behavior.

html
<html>
<head>
<script src="./js.js"></script>
<script src="https://apis.google.com/js/client.js?onload=checkAuth"></script>
</head>
<body>
 
<input type="button" value="AUTH" id="btn_auth" disabled />
</body>
</html>

The full app is avaible in attacments.

To JS API ninjas
I could be wrong, please correct me.
index.html
js.js
Reply all
Reply to author
Forward
0 new messages