Missing credentials while calling YouTube insert API - node.js

I want to use API key instead of OAuth token to call insert API from YouTube v3 lib. Code snippet is like below:
await google
.youtube("v3")
.videos.insert({
key: "my-youtube-api-key",
part: "id,snippet,status",
notifySubscribers: false,
requestBody: {
snippet: {
title: "Test video title",
description: "Test video description",
},
status: {
privacyStatus: "public",
},
},
media: {
body: fs.createReadStream(filePath),
},
})
.catch((err) => {
console.log("Upload to YouTube failed", err);
return null;
});
However, I am hitting error code 401, message is:
code: 401,
errors: [
{
message: 'Login Required.',
domain: 'global',
reason: 'required',
location: 'Authorization',
debugInfo: 'Authentication error: missing credentials.',
locationType: 'header'
}
]
How can I fix this issue? Isn't API key not supported? Thanks!

As per the docs, it's insufficient to use an API key on Videos.insert endpoint; you'll have to be properly authorized to call this endpoint:
Authorization
This request requires authorization with at least one of the following scopes (read more about authentication and authorization).
Scope
https://www.googleapis.com/auth/youtube.upload
https://www.googleapis.com/auth/youtube
https://www.googleapis.com/auth/youtubepartner
https://www.googleapis.com/auth/youtube.force-ssl

Related

Axios Post Request in NodeJS

I have an API call in POSTMAN, which I am trying to replicate in nodeJS project using Axios, but the result is not the same that of a POSTMAN.
The call looks like this in POSTMAN:
Inside the body element I have: models and values properties and Authorization is of type Bearer .
I get a response result as an array.
Now, I try to do the same using axios, but I get error:
Code
axios.defaults.baseURL = 'http://XXXXXXXXXXXXXXX:8069/api';
axios({
method: 'POST',
url: '/create/res.users',
data: {
models: 'res.users',
values: "{ 'login': 'john#gmail.com', 'name':'john', 'email':'john#gmail.com', 'password': '123123123' }"
},
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': 'Bearer ' + accessToken
},
})
.then(function (response) {
console.log("Register", response);
res.status(200).send({
message: response.data
});
})
.catch(function (error) {
console.log("Error", error.response.data);
res.status(error.response.status).send({
message: error.response.data
});
});
Error
{
"message": {
"name": "odoo.exceptions.RedirectWarning",
"message": "You cannot create a new user from here.\n To create new user please go to configuration panel.\n74\nGo to the configuration panel",
"arguments": [
"You cannot create a new user from here.\n To create new user please go to configuration panel.",
74,
"Go to the configuration panel"
],
"exception_type": "error",
"code": 500,
"description": "Restful API Error"
}
}
By default, axios serializes JavaScript objects to JSON. To send data in the application/x-www-form-urlencoded format instead, This document may help you:
https://github.com/axios/axios#using-applicationx-www-form-urlencoded-format

Unable to retrieve access token from authorisation code for Azure app

I am doing SSO to Azure AD for my Azure app using passport-azure-ad library. Following is the options object :
const options = {
identityMetadata: process.env.AZUREAD_IDENTITY_METADATA,
clientID: process.env.AZUREAD_AUTH_CLIENT_ID,
responseType: 'code id_token',
responseMode: 'form_post',
redirectUrl: process.env.AZUREAD_REDIRECT_URL,
allowHttpForRedirectUrl: true,
clientSecret: process.env.AZUREAD_AUTH_CLIENT_SECRET,
validateIssuer: false,
issuer: null,
passReqToCallback: true,
useCookieInsteadOfSession: true,
cookieEncryptionKeys: [
{ key: '********************************', iv: '************' },
{ key: '********************************', iv: '************' },
],
scope: ['profile', 'offline_access', 'https://graph.microsoft.com/mail.read'],
loggingLevel: 'info',
nonceLifetime: null,
nonceMaxAmount: 5,
clockSkew: null,
};
After getting authorisation code (req.body.code) from the AD callback, I am using that to retrieve access token for my app using adal-node library. Relevant code snippet -
const authenticationContext = new AuthenticationContext(
`https://login.microsoftonline.com/<tenant>.onmicrosoft.com`,
);
authenticationContext.acquireTokenWithAuthorizationCode(
req.body.code,
process.env.AZUREAD_REDIRECT_URL,
process.env.AZUREAD_AUTH_CLIENT_ID,
process.env.AZUREAD_AUTH_CLIENT_ID,
process.env.AZUREAD_AUTH_CLIENT_SECRET,
function(err, response) {
let message = '';
if (err) {
message = 'error: ' + err.message + '\n';
}
message += 'response: ' + JSON.stringify(response);
if (err) {
console.log(message);
return;
}
...
But this method is resulting in following error:
"error": "invalid_grant",
"error_description": "AADSTS54005: OAuth2 Authorization code was already redeemed, please retry with a new valid code or use an existing refresh token.\r\nTrace ID: 539cdaf3-460d-43fa-b4bb-6f23a8058800\r\nCorrelation ID: 507aafd9-5a4a-4417-b1f8-9fe4a5bc4cd3\r\nTimestamp: 2020-02-28 13:10:27Z",
"error_codes": [
54005
],
Also tried retrieving access token based on documentation (https://learn.microsoft.com/en-us/azure/active-directory/azuread-dev/v1-protocols-oauth-code#use-the-authorization-code-to-request-an-access-token) using Postman, but that also results in same error.
Kindly help me to figure out the mistake here.
Azure AD will no longer accept authorization codes to issue tokens that have already been used.
You need to get a new Authorization code every time. Also, you can change your code to request a refresh token that will be passed to /used by additional resources as the refresh tokens can still be reused.
Reference:
https://social.msdn.microsoft.com/Forums/en-US/4192e141-309a-4dd6-a5c9-f1a8ce32f4ca/aadsts54005-oauth2-authorization-code-was-already-redeemed

Firebase Auth REST API: OAuth sign-in with Twitter gives error 32 "could not authenticate you"

I'm writing a function in Node.js to log a user into Firebase using Twitter credentials, via the REST API (requests are made using the request library). I'm able to use the Twitter credentials to post a tweet, but attempting to sign in to Firebase with /accounts:signInWithIdp is returning the following error:
{ error:
{ code: 400,
message: 'INVALID_IDP_RESPONSE : Failed to fetch resource from https://api.twitter.com/1.1/account/verify_credentials.json?include_email=true, http status: 401, http response: {"errors":[{"code":32,"message":"Could not authenticate you."}]}',
errors: [ [Object] ] } }
This is my code:
loginWithOAuth = (idToken, postBody, onCompletion, onError) => {
var form = {
postBody: querystring.stringify(postBody),
requestUri: 'request uri',
returnIdpCredential: 'false',
returnSecureToken: 'true',
}
request.post({
url: 'https://identitytoolkit.googleapis.com/v1/accounts:signInWithIdp?key=' + firebase_api_key,
body: form,
json: true
}, (error, r, body) => {
// ...
});
}
where postBody is of the form
{
access_token: 'token',
oauth_token_secret: 'token secret',
providerId: 'twitter.com'
}
My Twitter app has permission to access user emails. I've also whitelisted the requestUri in both Firebase and Twitter. Regenerating my app & user keys doesn't make a difference.
What am I missing?
postBody is not a stringified object, it is URL encoded:
var form = {
postBody: 'access_token=[TWITTER_ACCESS_TOKEN]&oauth_token_secret=[TWITTER_TOKEN_SECRET]&providerId=twitter.com',
requestUri: 'request uri',
returnIdpCredential: 'false',
returnSecureToken: 'true',
}

Hapi-Swagger failing with header value

I am using hapi-swagger in our application where one of API trying to use custom header but when I ivoke that API with custom header getting below error
{
"statusCode": 400,
"error": "Bad Request",
"message": "Invalid request headers input"
}
Below the API where I am using headers with validator.
{
method: 'POST',
path: '/v1/testapi',
config: {
description: 'Greet user',
notes: ['Use to greet a user'],
tags: ['api'],
handler: function ( request, h ) {
console.log('sending response...');
return h.response('OK');
},
validate: {
headers: {
name: Joi.string().required()
}
}
}
}
Below are the versions we are using.
"hapi": "17.2.2",
"hapi-swagger": "9.1.1",
"joi": "13.1.2",
I ran into this recently. You need to use the allowUnknown validation option to allow unknown headers (https://github.com/hapijs/hapi/issues/2407#issuecomment-74218465).
validate: {
headers: Joi.object({
name: Joi.string().required()
}).options({ allowUnknown: true })
}
Also note that hapi 17 changed the default behavior for reporting validation errors. If you want to log or return the actual error indicating which headers are failing validation rather than a generic "Bad Request" you can add a custom failAction hander (https://github.com/hapijs/hapi/issues/3706).

How to set jwt token in WWW-Authenticate in hapijs?

I am able to create jwt on successful user login. But when I am using jwt strategy for other routes, I am getting 'WWW-Authenticate →Token' in the header also error comes :
{
"statusCode": 401,
"error": "Unauthorized",
"message": "Missing authentication"
}
{
method: 'GET',
path: '/example',
config: {
auth: {
strategy: 'jwt'
},
handler: function(request,
reply){
returnreply('Success,
youcanaccessasecureroute!');
}
}
}
If anybody knew how I remove this error please reply.

Resources