javascriptgoogle-oauthfeathersjs

Using Google Oauth in FeathersJs with an existing access token


How do I use the Google Oauth in featherjs with an existing access token? The docs do not give an example on this. The only example is through the browser as shown here.

When going through the browser, http://localhost:3030/oauth/google works ok. I can successfully add the user to my DB. Here is my code:

const { LocalStrategy } = require("@feathersjs/authentication-local");
const { expressOauth } = require("@feathersjs/authentication-oauth");
const { OAuthStrategy } = require("@feathersjs/authentication-oauth");
var uniqid = require("uniqid");
const { AuthenticationService, JWTStrategy } = require('@feathersjs/authentication');        

class GoogleStrategy extends OAuthStrategy {
  async getEntityData(profile) {
    const baseData = await super.getEntityData(profile);
    console.log({ profile });

    return {
      ...baseData,
      profilePicture: profile.picture,
      email: profile.email,
      password: uniqid.time(),
    };
  }
}

module.exports = (app) => {
const authentication = new AuthenticationService(app);        
authentication.register("local", new LocalStrategy());
authentication.register('jwt', new JWTStrategy());
authentication.register("google", new GoogleStrategy());

  app.use("/authentication", authentication);
  app.configure(expressOauth());
};

However if I try using an access token,like so

POST http://localhost:3030/authentication
data: {
    "strategy": "google",
    "accessToken": "ya29.A0ARrdaM_UJa6idfZr-4taqwkJ6qGBV1Dp9wbxF-wsult8dNPaVNCVg6Fndmrqv7BhRSwxa5gAKllPvbKtsjyxS39WdmWmqkmE42HOsVZaJWHVEttxbebel3zdpD5BSxWtRiG7NuZLNVedMUaK5AdgIRrJk1u"
}

I do not get the google profile, no user is added to my DB and I get this error:

{
  "name": "GeneralError",
  "message": "401 Unauthorized",
  "code": 500,
  "className": "general-error",
  "data": {},
  "errors": {}
}

I have added "google" to my list of authStrategies in default.json

So my question is what do I need to do?


Solution

  • So I found the solution. Thought I might share. Add this to authentication.js

     //add this method
     async getProfile(authResult) {
        const accessToken = authResult.accessToken;
    
        const { data } = await axios
          .get(
            `https://openidconnect.googleapis.com/v1/userinfo?access_token=${accessToken}`
          )
          .then((res) => {
            return res;
          })
          .catch((error) => console.log("autherr", error));
    
        return data;
    }