Requesting access token to Zoom API via Oauth - error 'missing grant type' - json

I'm trying to receive an access token from the Zoom api via Oauth. No matter what form I try and send the body as, 'Content-Type': 'application/json' or Content-Type:application/x-www-form-urlencoded, it always errors to { reason: 'Missing grant type', error: 'invalid_request' }.
var options = {
method: "POST",
url: "https://zoom.us/oauth/token",
body: JSON.stringify({
grant_type: "authorization_code",
code: process.env.AUTH_CODE,
}),
redirect_uri: "https://zoom.us",
};
var header = {
headers: {
Authorization:
"Basic " +
Buffer.from(process.env.ID + ":" + process.env.SECRET).toString("base64"),
},
"Content-Type": "application/json",
};
var tokCall = () =>
axios
.post("https://zoom.us/oauth/token", options, header)
.then((response) => {
console.log(response);
})
.catch((error) => {
console.log(error.response);
});
tokCall();
I'm fairly certain the answer lies in either the data type in which Oauth is receiving the data, or where/if it's receiving the body at all. Any suggestions would be gratefully received.

The error is being thrown because you're sending the data as the body of the post request when the Request Access Token Zoom API is expecting to find them as query parameters which you might know as query strings.
Reference
https://marketplace.zoom.us/docs/guides/auth/oauth#local-test
Image of page from link to highlight the use of query parameters and content-type requirement for API call
Change
var options = {
method: "POST",
url: "https://zoom.us/oauth/token",
body: JSON.stringify({
grant_type: "authorization_code",
code: process.env.AUTH_CODE,
}),
redirect_uri: "https://zoom.us",
};
to
var options = {
method: "POST",
url: "https://zoom.us/oauth/token",
params: {
grant_type: "authorization_code",
code: process.env.AUTH_CODE,
redirect_uri: "<must match redirect uri used during the app setup on zoom>"
},
};
The Content-Type header should be set to application/x-www-form-urlencoded as this is a requirement of the zoom API itself.
BTW, axios requires you to name the body field/object of your request as data and also there's no need for JSON.stringify() method since axios does that for you under-the-hood

Though it's a late answer, I'd like to share it since it took me some time to complete this using Axios.
So to make Zoom authorization, you need to do:
Base64 encode the secret and client id
const base64EncodedBody =
Buffer.from(`${ZOOM_CLIENT_ID}:${ZOOM_CLIENT_SECRET}`).toString('base64');
URI encode the grant_type, code and redirect_uri
const data =
encodeURI(`grant_type=authorization_code&code=${code}&redirect_uri=${redirectUri}`);
Send the request
const response = await axios.post('https://zoom.us/oauth/token', data, {
headers: {
Authorization: `Basic ${base64EncodedBody}`,
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': Buffer.byteLength(data),
},
});

Related

Angular login authentication with json rest api

I am trying to make a login authentication in angular, in which when we are entering email id and password we are getting a token. So for authentication, we have to send that header in the api get request but i am not able to do it.
My code is shown below
onSubmit(form:NgForm) {
this.http.post('https://pikreview.com/rest/user.php?f=authenticate',
JSON.stringify({
email: "a#gmail.com",
password: "12345"
})
).subscribe(res => {
localStorage.setItem('token', res.token);
var authToken = localStorage.getItem('token');
console.log("token is " + authToken);
var headers: HttpHeaders = new HttpHeaders({
'token': `${authToken}`,
'Access-Control-Allow-Credentials': true,
});
var req = new HttpRequest('GET',
'https://www.pikreview.com/rest/user.php', {
headers: headers,
withCredentials: true
}
);
this.http.request(req).subscribe(data => {
console.log(data);
})
}, error => {
console.log("something went wrong");
});
}
And one thing i have seen that whenever i pass token header there is something set-cookie generated which has token value on authentication page but on profile page it is not getting the same token and i think therefore it is showing invalid token.So,if anyone knows something about it and can solve my problem,please reply as soon as possible.
You just simple call the api with ur custom header, use HttpHeaders like this:
const httpOptions = {
headers: new HttpHeaders({
'Authorization': "YOUR_TOKEN"
})
}
this.http.get('http://localhost:5000/getUser',httpOptions)

"Problems parsing JSON" while sending a http request to a graphql api

I'm trying to send a http request to Githubs graphql api(v4). My guess is that the format of my query is wrong. The code below is used to send a POST request to the api.
app.get('/fetch-data', function(req, res, next) {
const access_token = settings.dev.TOKEN;
const query = {query: { viewer: { 'login': 'muckbuck' } }};
const options = {
uri: 'https://api.github.com/graphql',
method: 'POST',
headers: {
'Accept': 'application/json',
'Authorization': "Bearer " + access_token,
'User-Agent': 'request',
'contentType': "application/graphql",
},
data: query
};
function callback(error, response, body) {
console.log(response.body)
if (!error && response.statusCode == 200) {
console.log(body);
console.log('lol');
}
}
request(options, callback);
});
The error message that I get:
{"message":"Problems parsing JSON","documentation_url":"https://developer.github.com/v3"}
I believe your GraphQL is malformed in that the query key is supposed to contain a string, not a complex structure. See also this example from the GitHub API documentation.
You may also want to set Content-Type to application/json as is recommended by the GraphQL introduction. application/graphql does not seem to be a registered media type and appears to alter the behaviour of GraphQL.

Smooch Pre-Create App User API requires scope app and userId, but also doesnt allow userId with scope app

There appears to be a conflict between the validation of the request and the requirements of the request. The API call requires that the scope be set to 'app'. It also requires a userId. However, when the two are combined you get the below messages indicating you cannot combine the two.
API https://docs.smooch.io/rest/#pre-create-app-user
REQUEST
{ host: 'api.smooch.io',
path: '/v1/appusers',
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${token}`
}
Example body.
{
scope: 'app',
userId: 'some_userId',
credentialRequired: true,
email: 'test#email.com',
properties: { picture: 'https://s.gravatar.com/avatar/.....' }
}
RESPONSE BODY
{"error":{"code":"bad_request","description":"Invalid JWT body. Cannot use userId param with app scope"}}
RESPONSE HEADERS
{ connection: 'close',
server: 'nginx',
date: 'Tue, 21 Feb 2017 14:47:50 GMT',
'content-type': 'application/json; charset=utf-8',
'content-length': '105',
'x-powered-by': 'Express',
vary: 'X-HTTP-Method-Override',
etag: 'W/"69-huba/v8EazhrDAoySthrKw"',
via: '1.1 vegur' },
statusCode: 400,
statusMessage: 'Bad Request' }
I think you might be confusing two separate concepts - the JWT payload vs the HTTP request body.
scope is defined in the payload of your JWT credential (Bearer ${token} in your code sample). More information about JWTs and scopes can be found here.
userId should be specified in the HTTP request body.
I'm not sure what language you're using, but here's an example in Node.js:
var jwt = require('jsonwebtoken');
var token = jwt.sign({ scope: 'app' }, SECRET, { headers : { kid: KEY_ID } });
var request = require('request');
request.post({
url: 'https://api.smooch.io/v1/appusers',
headers: {
'Authorization': `Bearer ${token}`
},
json: {
userId: 'some_userId',
credentialRequired: true,
email: 'test#email.com',
properties: { picture: 'https://s.gravatar.com/avatar/.....' }
}
});

Connecting to HTTPS web services API with node.js v4.2.6?

I'm looking at connecting to an https web api, I've obtained my token, and my username by receiving an email about it, and there isn't really any sample code to connect to the webservice using node; however there are examples for Java and C#, and based on those this is what I came up with...
/* WEB API: https://www.careeronestop.org/Developers/WebAPI/technical-information.aspx?frd=true */
// UserID: ...
// Token Key: ...==
// Your agreement will expire three years from today on 12/8/2019 and all Web API services will be discontinued,
// unless you renew.
var https = require('https');
var username = '...';
var tokenKey = "...==";
var options = {
host: 'api.careeronestop.org',
port: 443,
path: '/v1/jobsearch/' + username + '/Computer%20Programmer/15904/200/2',
method: 'GET',
headers: {
'Content-Type' : 'application/json',
'Authorization' : '' + new Buffer(tokenKey.toString('base64'))
}
};
var req = https.request(options, function(res) {
console.log(res.statusCode);
res.on('data', function(d) {
process.stdout.write(d);
});
});
req.end();
req.on('error', function(e) {
console.error(e);
});
Unfortunately however, it returns a 401 Unauthorized, so is there anything that needs added to this to get it working? Some headers maybe?
I used this form to submit a request and then looked in the Chrome debugger network tab to see exactly what request was sent.
The authorization header is supposed to look like this:
Authorization: Bearer 901287340912874309123784
You also want this:
Accept: application/json
So, assuming tokenKey is already a string since it appears to have been sent to you in an email, you can change your code to this:
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
'Authorization': 'Bearer ' + tokenKey
}

React-Native Fetch "POST" request throwing "SyntaxError: Unexpected end of JSON input" in Android

this is my function
don't know where is the problem
fetchData() {
fetch(REQUEST_URL, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
Request : 'menu',
active : '1',
})
}).then((response) => response.json())
.then((responseData) => {
this.setState({
menu: responseData.Response,
});
})
.catch((error) => {
console.warn('error',error);
})
.done();
}
please point out the problem in function
The error occcurs because your response cannot be casted to JSON format. This issue might happen because of wrong header, response body, or other various reasons based on your server. The way to go - since apparently the responses are not consistent - is to perform additional validation of server response before trying to cast the response to JSON.
You can do this by replacing:
.then((response) => response.json())
with
.then((response) => {
// In this case, we check the content-type of the response
if (response.headers.get('content-type').match(/application\/json/)) {
return response.json();
}
return response;
// You can also try "return response.text();"
})
The error will be occcurs because your response can not be casted to be JSON
format.
there are three type of php mysqli api formate
1 formData
2 xml
3 json
i think you are use Formdata api but you are request in json see formdata
example
1) json Request.. example
var Request = {
security:1,
token: token,
email: this.state.username,
password: this.state.password
};
console.log(JSON.stringify(Request));
fetch(API.login, {
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/json"
},
body: JSON.stringify(Request)
})
.then(res => res.json())
.then(res => {
console.log("Login RESPONCE::: ", res);
}
2)Formdata Example use form data i think your error will be solve
let formdata = new FormData()
formdata.append("Api variable",your post variable)
formdata.append("name",this.state.name)
formdata.append("email, this.state.email)
formdata.append("password",this.state.password)
fetch('http://192.168.1.116/Restaurants/Registration.php', {
method: 'POST',
headers: {
'Content-Type': 'multipart/form-data'
},
body:formdata
}).then(res => res.json())
.then(res => {
console.log('Data RESPONCE::', res);
}
then((response) => response.json())
^^^^^^^^^^^^^ I think this is the problem
Responses with status code not equal to 2xx will not go into catch when you use fetch API, therefore you may JSON.parse something such as a HTML page or plain text stream.
You should check if response.ok === true before you parse response as JSON.
The likely cause of this error is your server not returning something that's not valid JSON (likely not JSON at all, like a 404 page or similar).
If you set the request Content-Type to application/json, likely it will send a preflight request to check CORS.
In my React app (not React-Native), I got cross domain issue. My server doesn't support preflight request, and so the response looks like:
{
body: null,
status: 0,
ok: false,
}
which is causing response.json() failed even though I got the expected JSON response in Chrome Dev Tools.
In my case, I change request Content-Type to application/x-www-form-urlencoded which does not require a preflight request. It works as expected.
It might not help in your case but I hope it give you some insight.
Log responseData. It might be possible that API is returning invalid data.