slack error "invalid_code" after sending request to oauth.access url - javascript

I am trying to authenticate my app with Slack. It was working perfectly fine for a few days, but now it's throwing me an error
invalid_code
const requestBody = qs.stringify({
code: code,
redirect_uri: redirect_uri,
client_id: client_id,
client_secret: client_secret
});
await axios
.post(url, requestBody, config).
then(server => console.log(server)).catch(err => console.log(err))
Response from server:
{ ok: false, error: 'invalid_code' }
The code I get is in this format.
code=303414024726.805164905556.526d546072e9b2408e0743f42ca3bb5843553a6c3b930b1de2c1e31847b25448
I think this is JWT token but I am not sure.
Any help would be appreciated.

This is how i made it work
let slackUrl = `https://slack.com/api/oauth.v2.access`;
let client_id = process.env.SLACK_CLIENT_ID;
let client_secret = process.env.SLACK_CLIENT_SECRET;
let details = {
code,
client_id,
client_secret
}
var formBody = [];
for (var property in details) {
var encodedKey = encodeURIComponent(property);
var encodedValue = encodeURIComponent(details[property]);
formBody.push(encodedKey + "=" + encodedValue);
}
formBody = formBody.join("&");
const _headers = {
'Content-Type': 'application/x-www-form-urlencoded'
};
let config = {
method: 'POST',
url: slackUrl,
data: formBody,
headers: _headers
};
let installation = await axios(config);

Related

How to filnd Path to Sharepoint in NodeJs

I have a code that is supposed to connect to a server, but I am getting a 'Microsoft SharePoint Foundation Error' when I try to run it. What could be causing this error and how can I fix it?
Status 200
OK
`
Microsoft SharePoint Foundation Error.
User: please report details to this Web site's Webmaster.
Webmaster: please see the server's application event log for more details.
`
const adal = require('adal-node');
const clientId = '<myclientID>';
const clientSecret = '<myclientSecret>';
const resource = 'https://<domain>.sharepoint.com/';
const folderName = '';
const context = new adal.AuthenticationContext('https://login.windows.net/common');
context.acquireTokenWithClientCredentials(resource, clientId, clientSecret, function(err, tokenResponse) {
if (err) {
// console.log('Błąd podczas pobierania tokenu dostępu: ' + err);
} else {
upload(tokenResponse.accessToken)
}
});
function upload(accessToken){
const fs = require('fs');
const axios = require('axios');
const filePath = './test.txt';
const sharepointSiteUrl = resource+'teams/<name_my_Sharepoint/';
const fileName = 'test.txt';
const folderName = '';
//add(url='${fileName}',overwrite=true)
const options = {
method: 'POST',
url: sharepointSiteUrl+ "/_api://<myclientID>",
headers: {
'Authorization': `Bearer ${accessToken}`,
'Accept': 'application/json;odata=verbose',
'Content-Type': 'application/json;odata=verbose'
},
data: fs.createReadStream(filePath)
};
axios(options)
.then((response) => {
console.log(response.status);
console.log(response.statusText);
console.log(response.data)
})
.catch((error) => {
console.log("test")
console.error(error);
});}

Spotify API returning data with Javascript/ React

I'm currently trying to incorporate Spotify's API into my project but I'm having problems fetching the data.
My token is returned in the console which is great but my call to return some data doesn't work.
I'm getting an error :
error:
message: "Only valid bearer authentication supported"
status: 400
[[Prototype]]: Object
[[Prototype]]: Object
Here's what I have so far. Maybe its a simple fix.
// Token
const CLIENT_ID = 'HIDDEN';
const CLIENT_SECRET = 'HIDDEN';
let authParameters = {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
body: 'grant_type=client_credentials&client_id=' + CLIENT_ID + '&client_secret=' + CLIENT_SECRET
}
async function getToken() {
let myToken = await fetch('https://accounts.spotify.com/api/token', authParameters)
let tokenReturn = await myToken.json()
console.log(tokenReturn.access_token)
}
// Request
async function searchData() {
const baseUrl = 'https://api.spotify.com/v1/browse/new-releases';
let ArtistParameters = {
method: 'GET',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + tokenReturn
},
}
let artistID = await fetch(baseUrl, ArtistParameters)
let artistList = await artistID.json()
console.log(artistList);
}
useEffect(() => {
getToken()
searchData()
}, [])

How can I redirect to home as soon as i get url?

Currently, I'm trying to use my company SSO(Oauth 2.0) Service,and I pass the url to the oauth service and
then I get the url with a code to get access token from front side, and then I pass the fetch
the code from client side url to backend server with the post, and then I get the code in server
side and redirect to the other url param in server side, i can get the user's information to client and server.
However, the client side URL show the code that i sent , so I want to know how to get rid of it.
and I searched a solution that i can redirect the page to another page, but I do not know how to .
and I want to know what i was doing is right way .
Thank you in advance.i hope it's not bad explanation
this below is what i tried :
client Side
var client_id =
"client_random_id";
var state_val = "RANDOM_STATE";
var redirectURI = "http://localhost:3000";
let api_url =
"https://www.??????/oauth2.0/authorize?response_type=code&client_id=" +
client_id +
"&redirect_uri=" +
redirectURI +
"&state=" +
state_val;
const logout = `https://www.??????/oauth2.0/Logout?client_id=${client_id}&logout_redirect_uri=${redirectURI}`;
const queryParams = new URLSearchParams(window.location.search);
const [userinfo, setuserinfo] = useState();
useEffect(() => {
fetch("http://localhost:5000/create", {
method: "post",
body: queryParams,
})
.then(response => response.json())
.then(json => {
setuserinfo(json);
})
.then("<Redirect to={routes.home.path}/>")
.catch(ex => {});
});
Server Side
app.post("/create", function (req, res) {
const code = req.body.code;
res.redirect(`/callback/?code=${code}`);
});
app.get("/callback", cors(), (req, res) => {
if (req.query.code !== null && req.query.code !== undefined) {
var token_url = "https://www.?????.kr/oauth2.0/token";
var options = {
url: token_url,
method: "POST",
form: {
grant_type: "authorization_code",
client_id: client_id,
client_secret: client_secret,
redirect_uri: redirectURI,
code: req.query.code,
state: req.query.state,
},
};
request(options, function (error1, response1, body1) {
if (!error1 && response1.statusCode == 200) {
var tdata = JSON.parse(body1);
var options2 = {
url: "https://www.??????/oauth2.0/resource",
headers: {
"Content-Type": "application/json",
Authorization: "Bearer " + tdata.access_token,
},
};
request(options2, function (error2, response2, body2) {
if (!error2 && response2.statusCode == 200) {
var rdata = JSON.parse(body2);
res.writeHead(200, { "Content-Type": "text/json;charset=utf-8" });
res.end(body2);
} else {
res.status(response2.statusCode).end();
console.log("error2 = " + response2.statusCode);
}
});
} else {
res.status(response1.statusCode).end();
console.log("error1 = " + response1.statusCode);
}
});
}
});
All you need is to change this part .then("<Redirect to={routes.home.path}/>")
to something like this
.then(() => {
window.location.replace("your url")
})
you could read more about replace here

Making my own API, confused on how to authenticate with server

I'm trying to make a Discord bot that retrieves a player's stats from the Ubisoft Rainbow Six stat website. I've worked with APIs before and I know the basics of Node and making GET requests to certain URLs. I monitored the network activity for a player's profile and found the specific URL that I need to perform a request on but I get a HTTP 400 error. I'm assuming this is because I've never authenticated with the server who I am. So I read up on authentication and the like and figured that all I had to do was include in the request header my username and password for the website(at this point I should mention that the site makes you login to retrieve player's stats). I went on Postman and included my username/password for Basic Auth and OAuth2 and I still get a HTTP 400 error, so there's obviously got to be more that I'm missing. It seems that in the network activity that some of the requests include a token, which I'm assuming is some sort of session token. I'm just completely confused as to what I'm supposed to do, as I'm kind of diving head first into this but I would really appreciate it if someone could provide some resources where I could try to fill in the gaps or help me resolve the issue. Code at the moment using pure JS/Node:
//import
const https = require('https');
const http = require('http');
//https://public-ubiservices.ubi.com/v3/profiles?namesOnPlatform=pope&platformType=uplay
var username = '';
var password = '';
var req_username = '';
//get session_id
function get_session_id(username, password) {
const options = {
host: 'public-ubiservices.ubi.com',
port: 443,
path: '/v3/profiles/sessions',
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Basic' + Buffer.from(username + ':' + password).toString('base64'),
'Ubi-AppId': '',
}
}
const req_session_id = https.request(options, res => {
let res_body = '';
res.on('data', data => {
res_body += data;
})
res.on('end', () => {
res_body = JSON.parse(res_body);
console.log(res_body);
})
});
req_session_id.end();
}
//retrieve player stats
function get_stats(req_username) {
const options = {
host: 'public-ubiservices.ubi.com',
port: 443,
path: `/v3/profiles?namesOnPlatform=${req_username}&platformType=uplay`,
method: 'GET',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Basic' + Buffer.from(username + ':' + password).toString('base64'),
'Ubi-AppId': '',
}
}
const req_get_stats = https.request(options, res => {
let res_body = '';
res.on('data', data => {
res_body += data;
});
res.on('end', () => {
res_body = JSON.parse(res_body);
console.log(res_body);
});
});
req_get_stats.end();
}
get_session_id(username, password);
get_stats(req_username);
try this out:
https://www.npmjs.com/package/r6api.js
heres an example:
const R6API = require('r6api.js');
const r6api = new R6API('email', 'password');
const username = 'Daniel.Nt'
const platform = 'uplay';
const id = await r6api.getId(platform, username).then(el => el[0].userId);
const stats = await r6api.getStats(platform, id).then(el => el[0]);
console.log(`${username} has played ${stats.pvp.general.matches} matches.`);

Missing required parameter To in the post body

I'm not sure if the header or the body are configured incorrectly.
Any thoughts on whether to change the headers or maybe the body is misconfigured?
const axios = require('axios');
const url = '/my_url';
const auth = {
username: username,
password: password
};
const requestbody = {
To: 'phone',
From: 'phone 2'
};
const headers = {
'Content-Type': 'application/x-www-form-urlencoded',
}
const config = {
auth: auth,
headers: headers
}
try {
const response = await axios.post(url, {data: requestbody}, config);
console.log(response);
} catch (error) {
console.error(error);
}
Error like:
message: 'Missing required parameter To in the post body'
you need to stringify parameters and then pass directly
const querystring = require('query-string');
const query = querystring.stringify({
To: 'phone',
From: 'phone 2'
});
let options = {
headers: {
'Authorization': AUTH_HEADER,
'Content-Type': 'application/x-www-form-urlencoded'
}
};
let axios_res = await post(url, query , options);

Categories