Get token from Javascript


#1

Hi, I am currently trying to get the access token,refresh token and open id from javascript. Currently I have the code sent by hydra to my application in the callback. Now, I am attempting to get the tokens with this:

var request = new XMLHttpRequest();
      request.open('POST', 'MyHydra.com/oauth2/token');
      request.setRequestHeader('Accept', 'application/json');

      var pair = "HydraClient:HydraSecret";
      const encoded = new Buffer(pair).toString('base64');
      request.setRequestHeader('Authorization','Basic ' + encoded);

      request.onreadystatechange = function () {
          if (this.readyState === 4) {
              console.log('Status:', this.status);
              console.log('Headers:', this.getAllResponseHeaders());
              console.log('Body:', this.responseText);
          }
      };
      var params = "code="+this.state.code+"&grant_type=authorization_code&redirect_uri=http://myapp.com/callback&client_id="+HYDRA_CLIENT_ID;
      request.send(params);

At first, I wasn’t sending the Authorization header (my bad) and I was getting status code 400. Now, I set the Auhtorization header but am getting status code 405 (method not allowed), and the petition is sent as OPTIONS. I hydra rejecting OPTIONS requests? should I modify something in hydra to allow these petitions?
Thank you


#2

Please do not do this on your own. OAuth 2 is a open standard and libraries exist for any programming language. Here are some for javascript:

Things marked bold are recommendations.