I'm currently working on integrating Celsius Network into our app. I got a partner token from partners#celsius, however, the support told me this token was "read-only". With this token, I'm able to call most API endpoints such as getBalance, gethealth, getInterestedRates, txSummaries. But I'm unable to call send/withdraw or create a new user.
When I try to withdraw my funds I get an 'API Unauthorized Request' error. I tried contacting partners support multiple times, but no one has answered me. Has anyone dealt with this error before?
My Code:
const { Celsius, AUTH_METHODS, ENVIRONMENT } = require('celsius-sdk');
const partnerKey: string = ****;
const apiKey: string = ****;
Celsius({
authMethod: AUTH_METHODS.USER_TOKEN
authMethod: AUTH_METHODS.API_KEY,
partnerKey: partnerKey,
environment: ENVIRONMENT.PRODUCTION
> }).then(celsius => {
const axios = require('axios');
var FormData = require('form-data');
var data = new FormData();
data.append('address', aValidEthAddress);
data.append('amount', '0.00007');
let config = {
method: 'post',
url: 'https://wallet-api.celsius.network/wallet/ETH/withdraw',
headers: {
'X-Cel-Partner-Token': partnerKey,
'X-Cel-Api-Key': apiKey,
...data.getHeaders(),
},
data: data,
};
axios(config)
> .then(function (response) {
console.log(JSON.stringify(response.data));
> })
> .catch(function (error) {
console.log(error);
> });
> });
I tried sending a post request to https://wallet-api.celsius.network/wallet/ETH/withdraw' with the following headers:
headers: {
'X-Cel-Partner-Token': partnerKey,
'X-Cel-Api-Key': apiKey,
...data.getHeaders()
},
I expected to get a success message and the funds to be sent to the address provided as data.address.
Related
So i been trying to get access to the reddit api.
I registered to reddit. verified my mail. opened an app and got my credentials.
Followed this official documentation and also came across to this tutorial
All my efforts have failed and don't get any respond.
I am using nodejs. but also tried in postman and failed.
Tried 2 options using fetch and using axios:
const axios = require('axios');
const fetch = require('node-fetch')
const { URLSearchParams } = require('url')
class RedditApi {
clientId2 = "get ur own credentials by opening an app here https://www.reddit.com/prefs/apps";
clientSecret2 = "get ur own credentials by opening an app here https://www.reddit.com/prefs/apps";
authenticationUrl = `https://www.reddit.com/api/v1/access_token`;
BASE_URL = 'https://www.reddit.com/';
tokenAuth = null;
tokenExpirationTime = null;
currencyObj = null;
constructor(currencyObj) {
this.currencyObj = currencyObj;
console.log("constructor service")
}
async getAuthToken() {
const bodyParams = new URLSearchParams({
grant_type: "https://oauth.reddit.com/grants/installed_client",
device_id: "DO_NOT_TRACK_THIS_DEVICE"
});
console.log(this.clientId2, 'this.clientId');
debugger;
const headersObj = {
'Authorization': `Basic ${Buffer.from(`${this.clientId2}:`).toString('base64')}`,
'Content-Type': 'application/x-www-form-urlencoded',
};
let response = null;
try {
response = await axios.post(this.authenticationUrl,
bodyParams,
{
headers: headersObj
});
debugger;
} catch (error) {
debugger;
console.error(error);
console.log(error.stack);
return null;
}
}
async getAuthToken2() {
try {
// Creating Body for the POST request which are URL encoded
const params = new URLSearchParams()
params.append('grant_type', 'https://www.reddit.com/api/v1/access_token')
params.append('device_id', 'DO_NOT_TRACK_THIS_DEVICE')
// Trigger POST to get the access token
const tokenData = await fetch('https://oauth.reddit.com/grants/installed_client', {
method: 'POST',
body: params,
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': `Basic ${Buffer.from(`${this.clientId2}:`).toString('base64')}` // Put password as empty
}
}).then(res => {
debugger;
return res.text()
})
debugger;
if (!tokenData.error) {
debugger;
res.send(trendingResult)
}
res.status(tokenData.error).send(tokenData.message)
} catch (error) {
debugger;
console.log(error)
}
}
}
module.exports = RedditApi;
when using axios i get this respond: "Request failed with status code 401"
When using fetch i get this respond: "'403 Forbidden\nRequest forbidden by administrative rules.\n\n'"
Anybody knows what is the problem and how can i fix it?
Many thanks!
Hi All,
I got a scenario in which i am supposed to call a REST api that is secured by a AZURE ACTIVE DIRECTORY. Most of the code runs fine and i am able to get the token using myMSALObj.acquireTokenSilent function too.
401 ERROR COMES WHEN I SEND AJAX CALL USING THAT TOKEN, YOU CAN SEE FOLLOWING CODE
User is there in Active Directory for which i get proper token, i dont know why my ajax call fails when i send that token to rest-api, please help
<script type="text/javascript">
const msalConfig = {
auth: {
clientId: "94edf294-08ae-489f-8621-c6d98009afa8",
authority: "https://login.microsoftonline.com/c483b3c4-21a6-4c93-95ea-7436cf318a68",
redirectUri: "https://localhost:44334/",
},
cache: {
cacheLocation: "sessionStorage", // This configures where your cache will be stored
storeAuthStateInCookie: false, // Set this to "true" if you are having issues on IE11 or Edge
}
};
const myMSALObj = new Msal.UserAgentApplication(msalConfig);
function CallApi() {
// Add scopes for the id token to be used at Microsoft identity platform endpoints.
const loginRequest = {
scopes: ["User.Read"],
};
myMSALObj.loginPopup(loginRequest)
.then((loginResponse) => {
const accessTokenRequest = {
scopes: ["api://8c2b0253-f9e8-442c-bccf-b4a8bbe73b59/access_as_user"]
};
myMSALObj.acquireTokenSilent(accessTokenRequest).then((accessTokenResponse) => {
var accessToken = accessTokenResponse.accessToken;
var apiEndpoint = "https://localhost:44387/api/hello";
var bearer = "Bearer " + accessToken;
console.log("accessToken = ", accessToken);
$.ajax({
url: apiEndpoint,
type: "GET",
beforeSend: function (xhr) { xhr.setRequestHeader("Authorization", bearer) }
}).done(function (response) {
alert("SUCCESS");
console.log("response = ", JSON.stringify(response));
}).fail(function (err) {
console.error("Error Occurred");
console.log("error = ", JSON.stringify(err));
});
})
}).catch(function (error) {
console.log(error);
});
}
</script>
Screenshot of a NEW API Code
Screenshot of JWT.ms (Access Token)
New Screenshot of JWT Token
You should not set the client ID in the appsettings.json file to the client id of your api app. It should be the client id of your client app. According to the jwt analysis diagram you provided, I think it should be: 94edf294- 08ae-489f-8621-c6xxxxxxx.
My bad, Following call was missing in my startup.cs file
app.UseAuthentication();
thanks for your help guys
Specially - #Carl Zhao, #Purushothaman #Rass Masood
I am trying to create a folder for a user, and I have been unsuccessful with api call attempts. My code is able to receive the correct access token, so I believe the be bug would be in createFolderTestFunction below.
async function redirectToDashboard() {
console.log("redirect to dashboard");
// var response = await requestTokenSilent();
var response;
if (!response || !response.status == 200) {
response = await requestTokenPopup();
}
if (response.accessToken) {
console.log(response);
createFolderTest(response.accessToken);
// location.href = hostname;
} else {
console.log("Unable to acquire token");
}
}
function createFolderTest(accessToken) {
var options = {
method: "POST",
headers: {
Authorization: accessToken,
"Content-Type": "application/json"
},
mode: "cors",
body: JSON.stringify({
displayName: "#COOLMONDAY"
})
};
var graphEndpoint = "https://outlook.office.com/api/v2.0/me/Inbox/";
fetch(graphEndpoint, options)
.then(resp => {
console.log(resp);
})
.catch(err => {
console.log(err);
});
}
A recommendation would be to get this working in Graph Explorer first. As this eliminates any issues with language being used and access token permissions.
https://developer.microsoft.com/en-us/graph/graph-explorer/preview
The Microsoft Graph endpoint is actually https://graph.microsoft.com/ , you can use the outlook url but moving forward Graph is where we invest in documentation, sdks and tooling.
As per the documentation https://learn.microsoft.com/en-us/graph/api/user-post-mailfolders?view=graph-rest-1.0&tabs=http
You should be using, you're missing 'mailfolders'
POST /me/mailFolders
You could also use our JavaScript SDK which makes mistakes like these a little easier with intellisense and strongly typed objects.
const options = {
authProvider,
};
const client = Client.init(options);
const mailFolder = {
displayName: "displayName-value"
};
let res = await client.api('/me/mailFolders')
.post(mailFolder);
https://learn.microsoft.com/en-us/graph/api/user-post-mailfolders?view=graph-rest-1.0&tabs=javascript
How can i get a particular guild info? It's working if i remove guilds.id, but then it only return list of all guilds i am in.
what is the correct method to get and update guild information using discord api?
This is how i'm getting my access_token:
const key = req.query.code,
options = {
href:`https://discordapp.com/api/oauth2/token`,
code : `code=${key}`,
grant_type : grant_type=authorization_code`,
redirect_uri :`redirect_uri=${redirect}`
};
request({
uri: `${options.href}?${options.grant_type}&${options.code}&${options.redirect_uri}`,
method: 'POST',
headers: {
Authorization: `Basic ${creds}`,
}
}, (err,response, body) => {
if(err) return console.log(err);
console.log(body) // console log access_token
})
Using access_token to make request
//My get request options
const options = {
url: `https://discordapp.com/api/guilds/${guilds.id}`,
method: 'GET',
json: true,
headers: {
authorization: `${token_type} ${access_token}`}
}
//Both of these options arent working
//token_type = bot
//token_type = Bearer
Gives me 401: Unauthorized.
My access_token scope is:
`identify email guilds guilds.join gdm.join rpc connections`
I am trying to make a GET call to the shopify api with request-promise in node.
I keep getting this error :-
'401 - {"errors":"[API] Invalid API key or access ' +
'token (unrecognized login or wrong password)"}'
How should format the options to take an API key and password?
const request = require("request-promise");
const Parse = require('parse/node');
const options = {
method:'GET',
json: true,
uri: 'https://the-bib-wine-company.myshopify.com/admin/api/2019-07/orders.json',
headers: {
'Authorization': <api key and password encode64>
}
}
request(options)
.then(function(response) {
var Test = Parse.Object.extend("Test");
var test = new Test();
test.set('orders', 'success');
test.save();
})
.catch(function(err) {
console.log(err)
})
Answered my own question, if it helps anyone.
auth: {
'user': 'API key',
'pass': 'mypassword'
}