Cannot send authorization bearer token throught axios - node.js

When I check in postman and sent the request to an api endpoint with the token works good:
But when I make the same request in expressjs to the api it sent me an unauthorized response:
Request:
try {
const response1 = await axios.get(`https://url/payment/pse/banks`,{headers: {
'Content-Type': 'application/json',
'Authorization':`Bearer ${token}`
}})
console.log("lista",response1.data);
} catch (error) {
console.log(error.response.data)
}
Response:
{
success: false,
titleResponse: 'Unauthorized.',
textResponse: 'Unauthorized.',
lastAction: '',
data: { token: '' }
}
What am I doing wrong?

Related

HttpClient Angular POST fails with Google FCM Server, how do I fix?

I am able to successfully send FCM messages via a POST and HTTP v1 Firebase API to my app using Postman but when I use the same POST in Angular HttpRequest it fails:
Error
Here are my imports:
import { Injectable } from '#angular/core';
import { HttpClient , HttpResponse, HttpHeaders} from '#angular/common/http';
import { Observable } from 'rxjs';
import { map } from "rxjs/operators";
Here is my code in the service:
sendFCMMessage(accessToken : string, data: object) {
console.log('sendFCMMessage');
console.log(accessToken);
console.log(data);
const authString : string = 'Bearer '+ accessToken;
console.log(authString);
const url = 'https://fcm.googleapis.com/v1/projects/***-notifications/messages:send';
const httpOptions = { headers: new HttpHeaders({
'Content-Type': 'application/json',
'Authorization': authString
})};
const body =
{
"message":{
"token":"wwrwjeriwe8***",
"notification":{
"body":"The Knicks are winning!",
"title":"Sports App"
}
}
};
return this.http.post(url,body,httpOptions).pipe(map(res => res));
}
I then subscribe to the response and get the error pasted above. Does anyone know why I am getting this error and how to fix? I am able to send FCM messages perfectly in Postman using the same exact POST url, body and header.
Thanks
Http response status code 401 means unauthorized, so it seems that your bearer token header is not present in your request.
return this.http.post<any>(
url,
{
message: {
token: 'wwrwjeriwe8***',
notification: {
body: 'The Knicks are winning!',
title: 'Sports App',
},
},
},
{
headers: {
'Content-Type': 'application/json',
'Authorization': authString,
},
}
);

Axios login request: Unauthorized, request status code 401

I'm trying to get an authorization token by making a request to an api using axios:
axios({
method: 'post',
url: 'http://62.110.134.187/api/signin',
headers: { 'content-type': 'application/x-www-form-urlencoded' },
auth: {
username: usr,
password: pwd
}
}).then(function (response) {
console.log(response)
}).catch(function (error) {
console.log('Error: ' + error)
})
I'm getting always status code 401(Unauthorized):
Error: Request failed with status code 401
Where I'm doing wrong?
The fact is that making the same request using python works fine:
payload = "username=%s&password=%s" % (usr,pwd)
headers = {'content-type': 'application/x-www-form-urlencoded'}
response = requests.request("POST", url_login, data=payload, headers=headers)
print(response.text)
data = response.json()
token = data["token"]
By sending username and password in auth: {} in axios, you are doing the basic-authentication, basically sending Authorization: basic <base64(user:pass)> header.
As per working python program, you need to send the username and password as part of the request body. You need to serialize the body params for url-encoded content type as well.
e.g.
const querystring = require('querystring');
axios({
method: 'post',
url: 'http://62.110.134.187/api/signin',
headers: { 'content-type': 'application/x-www-form-urlencoded' },
data: querystring.stringify({
username: usr,
password: pwd
})
}).then(function (response) {
console.log(response)
}).catch(function (error) {
console.log('Error: ' + error)
})

Request API node js using bearer token

I tried doing the following:
request({
url: 'https://vdms-dev.clientsolve.com/evoDMDev/api_event.php',
headers: {
'Authorization': 'Bearer 71D50F9987529'
}
}, function(err, res) {
console.log(res);
});
The log is showing undefined but when I try it on Postman it seems to be working fine.
Any help would be appreciated!
Since your are calling https host (https://evodms-dev.clientsolve.com/evoDMSDev/api/api_event_all.php), request client will throws an error while doing SSL handshake,
thats why you got response as undefined. Inorder to check the exact error response log the error console.error("Error Response : ", err)
Checkout this working snippet with error handling.err
Note: Now you will get Invalid Bearer Token error, Enter valid Bearer token
const request = require('request');
request({
url: 'https://evodms-dev.clientsolve.com/evoDMSDev/api/api_event_all.php',
headers: {
'Authorization': 'Bearer 71D50F9987529'
},
rejectUnauthorized: false
}, function(err, res) {
if(err) {
console.error(err);
} else {
console.log(res.body);
}
});

Instagram API Subscription endpoint asks for access token even though it is provided

I am sending a POST request to the Instagram API subscriptions endpoint to add a user subscription, but am getting the error:
error: StatusCodeError: 400 -
{"meta":
{"code":400,
"error_type":"OAuthParameterException",
"error_message":"Missing client_id or access_token URL parameter."}}
I have provided both the client_id and the access_token in my request.
Here is the request code.
let access_token = user[0].access_token
let options = {
method: 'POST',
uri: `https://api.instagram.com/v1/subscriptions/`,
body: {
access_token: access_token,
client_id: instaConfig.client_id,
client_secret: instaConfig.client_secret,
object: 'user',
aspect: 'media',
verify_token: 'myVerifyToken',
callback_url: `${callback_url}`
},
headers: {
'User-Agent': 'Request-Promise'
},
// Automatically parses the JSON string in the response
json: true
}
// rp = require('request-promise')
rp(options)
.then((response) => {
console.log('subscriptions response: ' + util.inspect(response, { showHidden: true, depth: null }))
})
.catch((err) => {
console.log('error: ' + err)
})
It wouldn't read from body. It needs to be passed from query param or headers.

Aurelia fetch-client throws 401 for post requests

I'm facing an issue while trying to make httpPost request.
It always returns 401 Unauthorized error.
We are using token based authentication from our server(Apache Tomcat7) with SpringSecurity plugin for generating authToken.
Below is how I configured HttpClient.
In constructor, I made httpClient configuration.
#inject(HttpClient)
export default class UtilService {
constructor(http) {
// Configure the HttpClient globally ( in entire app)
http.configure(_http => {
_http
.useStandardConfiguration()
.withBaseUrl(config.baseUrl)
.withDefaults({
credentials: "same-origin",
headers: {
"Content-Type": "application/x-www-form-urlencoded",
"X-Requested-With": "Fetch",
"Accept": "*/*",
"Authorization": "Bearer "+localStorage[config.tokenName]
}
})
.withInterceptor({
responseError(error) {
if (error.status && error.status === 401) {
console.log("error recorded:"+error)
}
throw error;
}
});
});
this.http = http;
}
}
And calling function:
profileInfo(url, paramsObj) {
// url = http://localhost:8082/xyz/api/v1/profileInfo
// paramsObj = {access_token : localStorage[config.tokenName]};
return this.http.fetch(url, {
method: "POST",
body: $.param(paramsObj)
}).catch(err=>{
console.log("failure:"+err);
throw err
});
}
I always get 401 (Unauthorized).
Any help would be appreciated.

Resources