Authorization header malformed WP JWT Authentication for WP REST API - wordpress-rest-api

I have managed to get the token using user and pass and now I am passing the token using this ajax call in order to create a new post , like this :
$.ajax({
url: "http://apibind.com/wp/wp-json/wp/v2/posts",
type: "POST",
headers: { "Authorization": "Basic xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" },
success: function (data) {
console.log(data);
},
error:function(data){
console.log(data);
}
});
and I get this error : Authorization header malformed . Anyone knows what is wrong with the header?

simple misstake : Bearer instead of Basic (I'm using a token based authorization)

Remove the JWT related plugins from your WordPress(for my case , it's "Simple JWT Login"). They help if you are developing mobile apps for site but they interfere with the rest api call.

Related

Facebook Webhook Test Button not working as expected

I have successfully added my callback url in my webhooks setup. At that time, the callback url was called successfully with proper logs and everything in the server. But when I click on the TEST button for the respective name (leadgen in this case), nothing AT ALL is being received by the server when in fact it should at least log the very first line. Note that I am using post and get.
Additional note: for NetSuite experienced developers, I am using a suitelet as the callback url for the webhook.
Thanks.
Suitelets that are available externally without login will only work if the User-Agent header in the request mimics a browser. See for example SuiteAnswers # 38695.
I ran into a similar issue, and the workaround was to proxy the request using a Google Cloud Function that simply rewrote the User Agent:
const request = require('request');
exports.webhook = (req, res) => {
request.post(
{
url: process.env.NETSUITE_SUITELET_URL,
body: req.body,
json: true,
headers: {
'User-Agent': 'Mozilla/5',
Authorization: req.headers['authorization'],
},
},
function(error, response, body) {
res.send(body);
}
);
};

How to use AccessToken received from Snapchat to fetch UserData?

Following snapkit Login Documentation (WEB), I implemented server side code and am able to obtain Access Token for the user (Section 2.5 at https://docs.snapchat.com/docs/tutorials/login-kit/web/ ).
How do I use this token to actually get user data? There is no mention of what one must do for ex. make a POST / GET request with the Access Token? This I think is the most critical part of the process, and it seems to be missing from the documentation.
I also tried using SCSDKLoginClient.getAccessToken(), I am able to retrieve token from Snapchat for the user who has logged in. However, I can't find any documentation on how to get user data there either. The only mention is that of a callback fetchUserData() but there's no field for Token there either.
Answering my own question as I found the answer after long research, thanks to Snapchat Support.
Once you get the Access token by following documentation, follow below steps to get user info.
(Swap out ACCESS_TOKEN for your own access token.)
Make a POST request to
URL: "https://kit.snapchat.com/v1/me"
Headers = {'Content-Type': 'application/json', 'Authorization': 'Bearer ' + access_token}
jSON_body= {"query":"{me{displayName bitmoji{avatar} externalId}}"}
This should return jSON result like the following with the user information:
{
"data": {
"me": {
"displayName": "DISPLAY_NAME",
"bitmoji": {
"avatar": "URL_BITMOJI_IMAGE"
},
"externalId": "EXTERNAL_ID"
}
},
"errors": []
}

Securing a restful API verifying clients with JWT

I have a RESTful API using JWT for authentication purposes. The first call I receive from a client is the /login call, with the following payload (no headers)
{
"username" : xxxx,
"password": wwww
}
The server verifies if the user is registered and then returns a signed JWT to the client in order to be received in the next calls.
I wonder if this is secure enough. I don't check anywhere if the client sends me a client id / client secret (like in OAuth) so I cannot verify if this call is from my webapp / apps or if it is an external client which I don't know about. I want to know if it makes sense to implement this behavior using JWT and how to implement it.
(I know how to do it with OAuth2 but I don't want to move now from JWT authentication)
Thank you!
If I understood you correctly, you should create a function somewhat similar to this:
function verify(req, res, next) {
const token = req.header('x-auth-token');
if (!token) {
return res.status(401).json({
msg: 'No token, auth denied'
});
}
try {
const decoded = jwt.verify(token, config.get(YOUR_SECRET_GOES_HERE));
req.user = decoded.user;
next();
} catch (err) {
res.status(401).json({
msg: 'Token is not valid'
});
}
}
For all secured API endpoints you should apply it like this:
router.get('/anyuserinfo', verify, (req, res) => ...
And that is it. The function will send 401 response if no token is provided.
I think I found another Stackoverflow question that answers mine:
JWT (Json Web Token) Audience "aud" versus Client_Id - What's the difference?
In a nutshell, client_id and client_secret should be sent on headers to the server to be validated before sending a new JWT token.

Error 401 (Unauthorized) When making REST calls using Axios with JWT headers included

I'm developing a small react node application with JWT passport for authentication. I've tested all the endpoint through postman(by passing token with authorization header) and they are working properly.
This is the call im making from the front-end
export const getUsersDetails=()=>{
console.log( localStorage.getItem('jwtToken'));
return (dispatch) => {
return axios.get('http://localhost:3030/users',
{ headers: { 'Authorization': localStorage.getItem('jwtToken') } }
).then((data)=>{
console.log('data comming',data);
dispatch(getUsersData(data));
}).catch((error)=>{
console.log('error comming',error);
dispatch(errorgetUsersData(error));
});
};
}
I have enable CORS by using the the CORS module. this is the how the network calls looks like from the browser
the authorization header looks like
authorization:[object Object], eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.....
Should this be like authorization: eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.....
Is this the reason why im facing this issue? How to overcome this?
I was able to solve a similar issue on a MERN stack, by configuring axios globally in the react application, by adding Bearer and one space, in front of the token that is assigned globally.
axios.defaults.headers.common['Authorization'] =Bearer ${token};
initially, it was without Bearer and i kept getting a 401 status code.
axios.defaults.headers.common['Authorization'] = token;
When you want authorization in your app, it depends on how you have done your back end. If everything is ok trough postman, show how your headers in postman look when you have tasted. I use xsrf token and here is how my request header look:
{headers:
{"Access-Control-Allow-Headers" : "*",
"X-XSRF-TOKEN": this.$cookie.get('XSRF-TOKEN')}
}
Maybe you should just put "Access-Control-Allow-Headers" : "*"

Connection between nativescript and MongoDB (mongoose)

I am new in mobile development world and right now trying to understand few basic things.
I did a simple login nativescript app and from backend side did a login logic with mongoose (MongoDb) and express. But now I don't know how to proceed... How do I connect between backend and app?
Thank you in advance,
Emil
You need to expose an API from your backend, I'll assume you have done this (or can find this out - it's very well documented).
So from the client {N} you will need to access the API, calling whichever end-points you need. If you were using a JWT type approach, you should use the http module in nativescript, which might look something like this:
var http = require("http");
var result;
http.request({
url: "https://myBackend.org/api/post",
method: "POST",
headers: { "Content-Type": "application/json" },
content: JSON.stringify({ username: "ValueOne", password: "ValueTwo" })
}).then(function (response) {
result = response.content.toJSON();
console.log(result); //result.message would have the clients auth token
}, function (e) {
// console.log("Error occurred " + e);
});
You could then store the token (in persistent storage with the application-settings module) and add it to the header of any request to a different API endpoint to interact with your backend as an authenticated user.
Alternatively, you can use one of the cloud backend SDKs, e.g. Azure Mobile Services or Firebase which make your life much easier.