Authorisation in Drchrono - node.js

For authorization at DRchrono, I had created a GET request at https://drchrono.com/o/authorize/ with a redirect URL and clientId, as soon as I click on authorize I redirect to my redirect URL with code value in params,
then I made a POST request on https://drchrono.com/o/token/ via postman with this
{
"code":"x4xzqXXjlBWeeQxEzjyE8thFTIW0eT",
"grant_type": "authorization_code",
"redirect_uri": "",
"client_id": " ",
"client_secret": ""
}
client_id and client_secret value taken from DrChrono API management page.
After making a post instead of getting the access token, I get "400 bad requests" in response.
I am not getting what that thing I am missing.
for doing all this thing I followed DRchrono official document :
https://drchrono.com/api-docs/v4?application=4217#section/Authorization/Initial-authorization
Can anyone help me with this??

My issue got resolved by making these 2 changes:
while making the post request we have to pass
Content-Type=application/x-www-form-urlencoded
in header
const Header = {
"Content-Type": "application/x-www-form-urlencoded",
};
we also need to convert our json object into x-www-form-urlencoded, like this:
var postData = {
code:query.code,
grant_type: "authorization_code",
redirect_uri: " ",
client_id: " ",
client_secret: " ",
};
var encodedData = "";
for (key in postData) {
encodedData += encodeURIComponent(key)+"="+encodeURIComponent(postData[key])+"&";
}
and then finally pass Header, encodedData value in post request
request.post("https://drchrono.com/o/token/", (data = encodedData), {
headers: Header,
}) .then((res) => {
console.log("RESPONSE RECEIVED: ", res.data);
})
This article helped me for testing the Authentication from postman: http://drchronoapi.wpengine.com/connecting-to-drchronos-api-via-postman/
Hope this helps to others who faced similar issue :)

Related

Instagram API: Invalid Platform App when fetching access token

I'm trying to log in using Instagram Basic Display API.
I'm trying to get the access_token, and I'm using axios:
const { code } = queryParams;
const url = `https://instagram.com/oauth/access_token`;
const result = await axios.request({
url,
method: 'POST',
data: {
'client_id': INSTAGRAM_CLIENT_ID,
'client_secret': INSTAGRAM_CLIENT_SECRET,
'grant_type': 'authorization_code',
'redirect_uri': 'https://localhost:3000/auth/instagram/token',
code,
},
});
I'm getting a 400 error, with the message invalid platform app. All the values sent exist and are correct.
My redirect_uri doesn't exist though, but it's added to the authorized URL list. It doesn't exist because I don't have https in my local server.
I had this same issue. The official example given by Instagram using curl uses the -F tag, which means that they are posting the data as the application/x-www-form-urlencoded content-type.
Every other post format I tried is ignored. Changing your code to post as a form and it should work.
There is a very good answer on this post
const querystring = require('querystring');
//Make Object with params const data = {
client_id: 'xxxxxxx',
client_secret: 'xxxxxxxxxxx',
grant_type: 'authorization_code',
redirect_uri: 'https://example.com/auth',
code: 'xxxx' }
//Make the Call
axios.post("https://api.instagram.com/oauth/access_token",
querystring.stringify(data)) .then(function (response) {
console.log("OK", response.data); }) .catch(function (error) {
console.log(error); });

Client must be authenticated to access this resource. jira rest api

I've created a project using node module passport-atlassian-oauth2 and i get the accessToken successfully. But when I do a request to create an issue I get the error
Client must be authenticated to access this resource.
Below is my code for create issue jira api.
Could you help please?
var bodyData = {
"fields": {
"project": {
"key": "FLUX"
},
"summary": "REST ye merry gentlemen.",
"description": "Creating of an issue using project keys and issue type names using the REST API",
"issuetype": {
"name": "Bug"
}
}
};
var baseUrl = 'https://alamrezoanul.atlassian.net';
var options = {
method: 'POST',
url: `${baseUrl}/rest/api/3/issue`,
data: JSON.stringify(bodyData),
headers: { 'Authorization': 'Bearer ' + jiraTokens.accessToken, 'Content-Type': 'application/json' },
json: true };
axios(options)
.then((response2) => {
console.log("response2.data: ", response2.data);
})
.catch((error) => {
console.log("error: ", error);
})
Hi I encountered the same issue today. You need to fetch the cloud id of https://alamrezoanul.atlassian.net and then instead of doing var baseUrl = 'https://alamrezoanul.atlassian.net'; use var baseUrl = 'https://api.atlassian.com/ex/jira/{cloud id}';.
You can fetch the cloud id by doing a authenticated GET request to https://api.atlassian.com/oauth/token/accessible-resources.
You might want to check the audience in your authorised tokens.
https://developer.atlassian.com/cloud/jira/platform/oauth-2-authorization-code-grants-3lo-for-apps/#implementing-oauth-2-0--3lo-
Setup says:
audience: (required) Set this to api.atlassian.com.
You may need to set to alamrezoanul.atlassian.net
Same issue I have fixed instead username and password use email and api token link to generate token
Below code I am using in my project
public String getEncodedAuth() {
String username = "user#gmail.com";//enter your mail
String auth_header = username + ":" + "<API token>";
String encodedAuth = Base64.getEncoder().encodeToString(auth_header.getBytes());
return encodedAuth;
}
public void getIssue(String issueId) {
Response response = RestAssured.given()
.header("Authorization", "Basic " + getEncodedAuth())
.contentType(ContentType.JSON)
.pathParam("issueIdOrKey", issueId)
.queryParam("fields", "attachment")
.when()
.get("https://user.atlassian.net/rest/agile/1.0/issue/{issueIdOrKey}");
response.prettyPrint();
}

Microsoft-Graph token using request is to small

I'm trying to get the access token for my Microsoft-Graph application using request to send a POST request.
The problem is that the token i get as a response is only 1188 characters long. While the token i get when i use Postman is 1461 characters long. Every time i send a request it generates a brand new token, but the one i get through request in nodejs is always 1188 and the one in postman is always 1461.
I have tried different things such as generating a new app api id in Microsoft Azure, but it keeps giving the same results.
This is my code, i took out sensitive information though by replacing it with the word CENSORED.
I'm using the EXACT same request parameters in Postman
const endpoint = "https://login.microsoftonline.com/CENSORED/oauth2/token";
const requestParams = {
client_id: "CENSORED",
client_secret: "CENSORED",
resource: "https://graph.windows.net",
grant_type: "client_credentials"
};
let accessToken = await
request.post({
url: endpoint,
form: requestParams
}, function (err, response, body) {
if (err) {
console.log("error");
} else {
console.log("Body=" + body);
let parsedBody = JSON.parse(body);
if (parsedBody.error_description) {
console.log("Error=" + parsedBody.error_description);
} else {
getCalendarEvents(parsedBody.access_token);
}
}
});
Postman returns an 1461 characters long access token and nodejs request only returns a 1188 characters long access token.
This is what i'm using in Nodejs: https://www.npmjs.com/package/request
The resource https://graph.windows.net is for the legacy Azure AD Graph API. This is a completely separate API from the Microsoft Graph. For the Microsoft Graph, the resource should be https://graph.microsoft.com:
const endpoint = "https://login.microsoftonline.com/{tenant}/oauth2/token";
const requestParams = {
client_id: "{clientid}",
client_secret: "{clientsecret}",
resource: "https://graph.microsoft.com",
grant_type: "client_credentials"
};
Apparently the resource parameter should be https://graph.microsoft.com instead of https://graph.windows.net.

Sending post request from axios with "Content-Type" : "application/x-www-form-urlencoded" gives an 401 Unauthorized response

I am sending a POST request to a server to fetch a token through axios with a Content-Type header of x-www-form-urlencoded. I tried the same with postman and it works fine. I'm sending a key value pair of grant_type and client_credentials in the request body.
This is my axios request:
axios.post(`${baseURI}/protocol/openid-connect/token`, data, {
headers : {
"Authorization" : "Basic " + token,
"Content-Type" : "application/x-www-form-urlencoded"
},
withCredentials: true
}).then(response => {
AUTH_TOKEN = response.data.access_token;
console.log(response.data);
}).catch(error => {
console.log(error.response);
})
The data object consists of the client_credentials.The same credentials gives a successful response in postman.
I had this exact same problem until I finally figured out that Axios needed the data object to be reformatted as a query string.
So make yourself a function like this:
function getQueryString(data = {}) {
return Object.entries(data)
.map(([key, value]) => `${encodeURIComponent(key)}=${encodeURIComponent(value)}`)
.join('&');
}
Pretty simple, just URI encoding all the parts of your object and joining them with &.
Then modify your code like this:
axios.post(`${baseURI}/protocol/openid-connect/token`,data, {
headers : {
"Authorization" : "Basic " + token,
"Content-Type" : "application/x-www-form-urlencoded"
},
withCredentials: true,
transformRequest: getQueryString
})
.then(/*...*/);
You can read about the different options, including transformRequest, for the request config here: https://github.com/axios/axios#request-config
(I'm still annoyed that this was necessary and not just handled by Axios but oh well.)
While #binary lobster solution is pretty concise, one might consider using qs library like this:
import qs from 'qs'
axios.post(`${baseURI}/protocol/openid-connect/token`,
qs.stringify(data), {
headers : {
"Authorization" : "Basic " + token,
"Content-Type" : "application/x-www-form-urlencoded"
}
})
.then(/*...*/);
See more information here

error returned in postman to get access token but works in console for NodeJS

I am trying to access the token using authorization code after passing the authentication, it works in my console for nodejs using request-promise module however it doesnt work on postman it says
{
"error": "invalid_grant",
"error_description": "invalid authorization code"
}
however it works in the console for nodeJS
{"access_token":"eyJhbGciOiJIUzI1NiJ9.7DkDzFz89Y-W-HLlwnqA0YmA_mMrR8nZV44eC1gAJjEp2Zmq8SE9q0UmzXuU-hHuXseMNvpqQeRMhHeVTbn8J_ZCQmkkAgZ359CnKvnXe3mZoYAWM4oQbtJFefoa7mwsAEFKScyEaIqi1DqHTItVqZfbCYdzrbee88E2-pWteiE.CHAvVIanJrUlTZZ25LMUTzW7IO4qRGZ_B_wN7c5Kfkk","token_type":"Bearer","refresh_token":"uDhPe4dRJkUYB1rC9VuV","expires_in":2592000,"scope":"openid profile","id_token":"eyJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwczovL2FjY2Vzcy5saW5lLm1lIiwic3ViIjoiVWU4NTUzNTBiNDIzYzI5ZjExYjIwZTgwZTJiZmE4MmQ1IiwiYXVkIjoiMTU1Njc5NDgxOCIsImV4cCI6MTUxNzkzMDc3MCwiaWF0IjoxNTE3OTI3MTcwLCJuYW1lIjoiSm9obiBCb3JqZSIsInBpY3R1cmUiOiJodHRwczovL3Byb2ZpbGUubGluZS1zY2RuLm5ldC8waG1URGV0bUpWTW50NUhCem5YUnhOTEVWWlBCWU9NalF6QVhJcVNBNGVQaDVSSzNRcFRINHVGQXdiUEI5V0pYTW9RWGgxR1Y5UGIwMVQifQ.mYUWJQ-YLrz4zEer5n1J-R3S1W37mDLx6g_mVmmWDTk"}
this is the code using nodeJS
var data = {
grant_type: "authorization_code",
code: qC,
redirect_uri: "https://sample.com/profile", //edited for security
client_id: 1, // edited for security
client_secret: "9" //edited for security
}
var options = {
method: 'POST',
url: 'https://api.line.me/oauth2/v2.1/token',
headers:{
'Content-Type': 'application/x-www-form-urlencoded'
},
// payload: 'grant_type=authorization_code&code="'+queryCode+'"&redirect_uri=https://line-poc-demo.herokuapp.com/profile&client_id=1556794818&client_secret=98760fb0cea2aebdf7848ecf93c19cf4',
form: data
}
//
rp(options)
.then(function (parsedBody) {
// POST succeeded...
console.log('bick dig' + parsedBody);
})
.catch(function (err) {
// POST failed...
console.log('err ' + err);
});
Is there something wrong with my code? Thank you, any help will be appreciated.

Resources