How to set jwt token in WWW-Authenticate in hapijs? - node.js

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.

Related

Missing credentials while calling YouTube insert API

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

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

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',
}

Configuring request to Google My Business API to avoid Unauthenticated error

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}`
}
}

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).

Resources