I'm building a small Node/React app where I'm trying to implement OAuth2 Google to request the Google Analytics API. I'm using Passport.js to handle the authentification.
I'm able to get the Token correctly:
router.get(
"/auth/google/callback",
passport.authenticate("google", { failureRedirect: "/error", session: false }),
function(req, res) {
var token = req.user.token;
res.redirect("http://localhost:5000/?token=" + token);
}
);
However, when trying to call the Google Analytics management API I have the following error Error: Login Required
.
router.get('/getData', function(req, res) {
googleAccounts.management.profiles.list(
{
accountId: '~all',
webPropertyId: '~all'
},
(err, data) => {
if (err) {
console.error('Error: ' + err)
res.send('An error occurred')
} else if (data) {
Console.log(data)
}
}
)
})
How do I login? What step I'm missing?
You aren’t sending the access token, unless you’re using the gapi’s inbuilt auth, you have to send the access token manually in a HTTP authorization header.
Please use the following snippet to achieve the same.
function listViews() {
gapi.client.setToken({
access_token: <access-token>
})
... rest of the function