Search code examples
actions-on-googlegoogle-homegoogle-smart-home

How to fetch access token from OAuth used in google action for smart home


For my smart home action I used fake auth as shown in codelab- smartwasher application. (For testing purpose ). The app is working fine. I have build my own code to work with my devices(Switches). Now When I am implementing OAuth which uses my own custom OAuth server. I am not able to figure out how to implement it in my code. The OAuth is working as needed when I tested. But I want help in integrating it with google action. I am facing problem fetching access token. The code is as follows:

exports.fakeauth = functions.https.onRequest((request, response) => {
      const responseurl = util.format('%s?code=%s&state=%s',
        decodeURIComponent(request.query.redirect_uri), request.query.code,
        request.query.state);
      console.log('*********'+responseurl);
      return response.redirect(responseurl);
    });

    exports.faketoken = functions.https.onRequest((request, response) => {
      const grantType = request.query.grant_type
        ? request.query.grant_type : request.body.grant_type;
      const secondsInDay = 86400; // 60 * 60 * 24
      const HTTP_STATUS_OK = 200;
      console.log(`Grant type ${grantType}`);

      let obj;
      if (grantType === 'authorization_code') {
        obj = {
          token_type: 'bearer',
          access_token: '123access',
          refresh_token: '123refresh',
          expires_in: secondsInDay,
        };
      } else if (grantType === 'refresh_token') {
        obj = {
          token_type: 'bearer',
          access_token: '123access',
          expires_in: secondsInDay,
        };
      }
      response.status(HTTP_STATUS_OK)
        .json(obj);
        console.log('********** TOKEN **********',response);
    });

The above code executes with fake auth. Why is is not executing when I am implmenting custom OAuth? Do I need to do any changes for clienID and secret in firebase? How to fetch access token returned by OAuth?

Kindly help. I am new to node.js.


Solution

  • The authorization code that will come back in requests will be in the header, as an Authorization field. Here's a way to pull it out using Node.js.

    function getToken(headers) {
      // Authorization: "Bearer 123ABC"
      return headers.authorization.substr(7);
    }