Configuring request to Google My Business API to avoid Unauthenticated error - node.js

I keep getting an unauthenticated error back when submitting my request to the Google My Business API in my Node.js app. The response:
{
"error": {
"code": 401,
"message": "Request is missing required authentication credential. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project.",
"status": "UNAUTHENTICATED"
}
}
For what it's worth, I'm using the request-promise client to make the request. My function is below. I just received the access token, so I'm fairly certain that it's good, and I can see it through the err.options.Authorization log. I know the location ID doesn't exist yet, but I don't think that's what the error is telling me.
const request = require('request-promise');
...
function checkLocation (loc) {
return request({
method: 'GET',
uri: `https://mybusiness.googleapis.com/v4/accounts/${ACCOUNT_ID}/locations/${loc._id}`,
Authorization: `OAuth ${ACCESS_TOKEN}`
})
.then(function (response) {
console.log(response);
})
.catch(function (err) {
console.error(err.error, err.options.Authorization);
});
}
Is my request formatted incorrectly or am I not sending all I need to be?
Update: I left out possibly crucial information that this is through the one time authorization process for server-side apps like outlined here: https://developers.google.com/identity/protocols/OAuth2. My trouble is wrapped up in the sentence on that page, "After an application obtains an access token, it sends the token to a Google API in an HTTP authorization header."

Turned out my header wasn't formatted correctly. The Authorization key should be in a headers object:
{
method: 'GET',
uri: `https://mybusiness.googleapis.com/v4/accounts/${ACCOUNT_ID}/locations/${loc._id}`,
headers: {
Authorization: `OAuth ${ACCESS_TOKEN}`
}
}

Related

'Full authentication is required to access this resource' Clockify API with Node JS

I am unable to add new clients using the Clockify API in Node js. The following axios post request returns the error message: 'Full authentication is required to access this resource'. However, I am able to get a list of clients using the axios.get() method with the same API key, so I'm not sure why the post request says I'm not authenticated. Please let me know what I'm missing
async function addNewClient(clientName) {
return response = await axios.post(`${url}/workspaces/${workspaceId}/clients`, {
data: {
'name': clientName
},
headers: {
'X-Api-Key': CLOCKIFY_API_KEY,
'Content-Type': 'application/json',
},
}).catch(function (error) {
console.log(error.response.data.message);
return
});
}
I had the same issue. Regenerating API_KEY solved it.

I get an authentication code for microsoft graph, but when i try to use it, the response is InvalidAuthenticationToken

I'm trying to access onedrive through the API. I've managed to get an acces_token with files.readwrite scope. When i then try to access https://graph.microsoft.com/v1.0/me. It responds with the error "InvalidAuthenticationToken". What am i doing wrong
I've tried a bunch of different urls for example "https://graph.microsoft.com/v1.0/me/drive/root/children" and have searched stackoverflow, but nothing helped.
router.get('/response', function(req, res, next){
// already got code here.
var code = req.query.code
request.post({
url: 'https://login.microsoftonline.com/common/oauth2/v2.0/token',
headers: { 'Content-Type': 'application/x-www-form-urlencoded'},
form: {
client_id: client_id,
redirect_uri: redirect_uri,
client_secret: client_secret,
code: code,
grant_type: 'authorization_code',
},
},function(error, response, body){
if (error){
console.log(error)
}
//so far so good. The access_token from the response looks okay and the
//scope is correct as well
request.get({
url: 'https://graph.microsoft.com/v1.0/me',
headers: {
'Authorization': "Bearer " + JSON.parse(body).access_token,
},
}, function(er, re, bo) {
//this response is an error message
console.log(bo)
});
});
})
I expected to get a request with information about the onedrive, but i got an error message.
You aren't quite done yet with your authentication flow, the code you are getting back is an Authentication Code, not a Token. This is a very important distinction.
The first step in the oAuth code flow is getting the code, which you did. Then you need to 'trade' this code for an actual token. To do that you need to send another request to the server with this code and ask for your token. This request should go to a different URL. There is a lot of in depth explanation here for the flow you are using now
https://learn.microsoft.com/en-us/azure/active-directory/develop/v2-oauth2-auth-code-flow
And here for the implicit flow, if you meant to use that instead: https://learn.microsoft.com/en-us/azure/active-directory/develop/v2-oauth2-implicit-grant-flow
You might also want to look into using the AdalJS or preview MSAL.js library to handle a lot of the authentication for you, these are libraries made by Microsoft.

Reddit gives 403 when upvoting via API

I've registered as the Web app as required by the Reddit API for the Oauth access with identity, edit, flair, history, modconfig, modflair, modlog, modposts, modwiki, mysubreddits, privatemessages, read, report, save, submit, subscribe, vote, wikiedit, wikiread scopes.
I'd authorized my app and have exchanged the generated code for the access_token with 3600 seconds validity.
'use strict';
let request = require('request');
const USER_AGENT = 'web:com.example.server:v0.0.1 (by /u/sridharrajs)';
const token = '<my access_token within 3600 seconds validity>';
request({
method: 'POST',
url: 'https://www.reddit.com/api/vote',
headers: {
'User-Agent': USER_AGENT,
'Authorization': `bearer ${token}`,
'Content-Type': 'application/x-www-form-urlencoded'
},
form: {
id: "t1_9qy47p",
dir: "1"
},
json: false
}, function (error, response, body) {
if (error) {
console.log('error', error);
} else if (body.error) {
console.log('body.error', body);
}
return console.log(body);
});
But when I try to upvote a reddit submission using API, I get an error.
{"message": "Forbidden", "error": 403}
The link that I'm trying to upvote is Tim Cook warns of ‘data-industrial complex’ in call for comprehensive US privacy laws
I tried switching both bearer and Bearer as per the answer in Reddit API returns HTTP 403, and tried using different User-Agent as suggested in 403 error when trying to get data from Reddit API. Nothing seem to work.
What am I missing?
Solved. I need to use https://oauth.reddit.com instead of www.reddit.com.
You may now make API requests to reddit's servers on behalf of that user, by including the following header in your HTTP requests:
Authorization: bearer TOKEN
API requests with a bearer token should be made to https://oauth.reddit.com, NOT www.reddit.com.

Authorization for Client Credentials Flow (Bad Request)

Authorization for Client Credentials Flow
Hi I have read other Questions or not working properly the current response is 400 (Bad Request) what I had
The following is my code (Authorization has converted Base64)
const testAuth = () => {
return () => {
Axios({
url: 'https://accounts.spotify.com/api/token',
method: 'post',
params: {
grant_type: 'client_credentials'
},
headers: {
'Authorization': 'Basic MWM3NGFkOGQyNDgzNDI0Y2E4NGVmYWRlNzI1MzI5YzE6MDBmMGFmNDE1ZTZhNDgxOThiOWRlYzFmNmE2NTk5NDQ=',
'Content-Type': 'application/x-www-form-urlencoded'
},
}).then((respond) => {
console.log(respond);
}).catch((error) => {
console.log(error);
});
};
But things that are working with returned tokens as well as using spotify wep api normally by using Postman to send out the same content . Is my code uncorrent or is there any problem? (Authorization in Postman is the same as above)
Thank everyone, I just realized is an error of cors. However, there are many ways for trying still can't solve the 400.
For eaxmple: Chrome extension access-control-expose-headers
Preflighted Requests image
400 Respond image

How to implement JSON web token on front end side?

I am working on a nodejs express application. I used Passport's JSON web token for authentication. I have successfully created a JSON web token and it's working fine in Postman and also verifies when token passes into authorization. But I stuck on front-end side.
app.get('/profile',passport.authenticate('jwt',{session:false}),function(req,res){
// res.json({user:user.req});
// console.log(req.query.token);
res.json('bingo u cant see this without token')
});
How do I send the token in the headers like I did in Postman to this (/profile) route, i.e how to implement token on front end side so that it first checks token?
It depends on the kind what you are using to make your request at the frontend
if you are using ajax, do something like this
$.ajax({
type: 'POST',
url: url,
headers: {
"authToken":"your token" //you could save it in localstorage when recieved
}
//OR
//beforeSend: function(xhr) {
// xhr.setRequestHeader("My-First-Header", "first value");
// xhr.setRequestHeader("My-Second-Header", "second value");
//}
})
and if it's axios try doing it like this
post(url, {
headers: { authToken: token }
})

Resources