Getting past Auth1.0a of Twitter API using fetch in JavaScript - javascript

I'm trying to change my banner on Twitter using 'node-fetch' library, but I can't get past Authentification 1.0a which is needed to post something on Twitter. My last try was using headers.Authorization = "OAuth ACCESS_TOKEN ACCESS_SECRET" but it was a failure. So my question is, what is the correct way of using Auth1.0a in 'node-fetch'?
Thank you in advance!
Btw. the ACCESS_TOKEN and ACCESS_SECRET in the code are not mine, but randomly typed in.
fetch(`https://api.twitter.com/1.1/account/update_profile_banner.json`, {
method: 'POST',
body: {
banner: b64,
},
headers: {
Authorization: "OAuth 2123123415-kbZfcGdHqKxTLlazrgQtzhzhKgHhjgtrLZq6789gui th67jz27z7gh3xhr5ghhgjj1gjHNMthtzuthfnOp3hJwhS5frx"
}
}).then(results => results.json()).then(data => console.log(data))

This is a sample Authorization header from their docs:
Authorization: OAuth oauth_consumer_key="xvz1evFS4wEEPTGEFPHBog", oauth_nonce="kYjzVBB8Y0ZFabxSWbWovY3uYSQ2pTgmZeNu2VS4cg",oauth_signature="tnnArxj06cWHq44gCs1OSKk%2FjLY%3D", oauth_signature_method="HMAC-SHA1", oauth_timestamp="1318622958", oauth_token="370773112-GmHxMAgYyLbNEtIKZeRNFsMKPR9EyMZeS9weJAEb", oauth_version="1.0"
As you can see there are many more fields to consider, I suggest you read the docs carefully.
The placement of your Auth header is correct.

Related

Destiny 2 API recieving an auth token from endpoint using POST

Couple things to keep in mind, I'm a fairly beginner computer science student with a couple big projects under my belt. I mostly have been working with java so web is kinda new but seems easy enough to get used to.
I'm trying to send a post request to an endpoint that will return a membership id that I need.
I've been trying to follow along with these two documentation/guides:
https://github.com/Bungie-net/api/wiki/OAuth-Documentation
https://lowlidev.com.au/destiny/authentication-2#/tab-popup
On a side note, I really feel like there aren't many "get started" guides out there for working with the Bungie API but maybe that's intentional to prevent people from doing stupid stuff with people's accounts.
Anyways, I have successfully done the first part which is authorizing my app (registered on the bungie developers site) with the user's account using my client ID provided by Bungie. This returns a code inside the url that is your authorization code with the user's account. I have a kind of janky way of pulling it from the url, so any ideas of how I can improve it would be most appreciated.
document.getElementById("authButton").addEventListener("click", function(event) {
location.href = "https://www.bungie.net/en/OAuth/Authorize?client_id={my-client-id}&response_type=code&state=" + makeState(32);
});
var authCode = undefined;
if (window.location.href.includes("code=")) {
removeAuthButton();
authCode = window.location.href;
console.log(authCode);
var codeLoc = authCode.indexOf("code=");
var codeEndLoc = authCode.indexOf("&", 15);
authCode = authCode.substring(codeLoc + 5, codeEndLoc);
console.log(authCode);
}
This code is just executed after pressing a simple authorization button in the webpage, and bungie handles the redirect back to my page for me when I register my app.
Now after this, the documentation shows a POST request I need to make with the following:
POST https://www.bungie.net/platform/app/oauth/token/ HTTP/1.1
Authorization: Basic czZCaGRSa3F0MzpnWDFmQmF0M2JW
Content-Type: application/x-www-form-urlencoded
grant_type=authorization_code&code=SplxlOBeZQQYbYS6WxSbIA
To stay with the urlencoded format, I have tried this code using an answer I found:
https://stackoverflow.com/a/53189376/16910197
document.getElementById("linkButton").addEventListener("click", function(event) {
fetch('https://www.bungie.net/Platform/App/OAuth/token/', {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
body: new URLSearchParams({
'client_id': "{my-client-id}",
'grant_type': "authorization_code",
'code': authCode
})
}).then(function(response) {
console.log(response);
return response.json();
});
});
This isn't working and I have modified it every way possible to try and get it to work to no avail. What am I missing?
Here is what I am getting back if needed:
Response { type: "cors", url: "https://www.bungie.net/Platform/App/OAuth/token/", redirected: false, status: 400, ok: false, statusText: "Bad Request", headers: Headers, body: ReadableStream, bodyUsed: false }
I'm a little new to stackoverflow and this is my first question, so let me know if I can format it any better.
You need to call toString on URLSearchParams and send the Authorization header. If you haven't already, you should switch your API key to use the "Confidential" OAuth Client Type
document.getElementById("linkButton").addEventListener("click", function(event) {
fetch('https://www.bungie.net/Platform/App/OAuth/token/', {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': `Basic ${window.btoa(`${bungie_client_id}:${bungie_client_secret}`)}`
},
body: new URLSearchParams({
'client_id': "{my-client-id}",
'grant_type': "authorization_code",
'code': authCode
}).toString()
}).then(function(response) {
console.log(response);
return response.json();
});
});
In case you didn't, check the network request in browser dev tools to see what JavaScript is actually POSTing to the endpoint.
From a fellow Destiny API dev, please capitalise "token" in the endpoint path before I lose my mind!

Github Personal Authentication Token not working for Github API

I m trying to request https://api.github.com/search/issues?q=repo:react+state:open&sort=created&order=desc&per_page=100&page=1 using my personal authentication token but it always returns 422 status. The way i m using the token is on headers like this:
{
headers: {
authorization: `token ${myToken}`
}
}`
I dont know if i m doing something wrong but i supose this code should be working fine.
Just in case, after reading "How to send the authorization header using Axios", try:
axios.get('https://api.github.com/search/issues?q=react+state:open&sort=created&order=desc&per_page=100&page=1', {
headers: {
'Authorization': `token ${access_token}`
}
})
Try also to generate your token, considering its format has recently changed (March 2021)
As commented by the OP Gabriel Mazurco below, no more repo:.

Why am I receiving a 400 response of `invalid_request`:`no client authentication mechanism provided`?

I'm in the process of attempting to verify a JWT access_token against OneLogin's api as described here. My code is as follows:
const client_id = MY_CLIENT_ID
const client_secret = MY_CLIENT_SECRET
const token = MY_ONE_LOGIN_JWT_ACCESS_TOKEN
axios
.post(
"https://my-endpoint-dev.onelogin.com/oidc/2/token/introspection",
{ token, client_id, client_secret, token_type_hint: "access_token" },
{
headers: {
"Content-Type": "application/x-www-form-urlencoded",
},
}
)
.then((response) => {
console.log("response");
console.log(response);
})
.catch((err) => {
console.log("err");
console.log(err);
});
The endpoint appears to work fine, in fact when the JWT has become expired it gives me an error stating as such and I need to update the token I'm passing along. However, whenever I make a standard request as shown above with valid credentials and tokens I get the following error response:
{error: "invalid_request", error_description: "no client authentication mechanism provided"}
There's no documentation on the provided page that describes what is wrong with the request when that error is received. From the documentation, so far as I can tell, my request is formatted correctly.
I have verified that the Token Endpoint in OneLogin is set to POST, so my assumption that the client_secret should be in the body is documented as correct (though I did try it as Basic just to verify):
I've attempted searching for a solution, but the only thing close I've found advises that the Content-Type header may not be supplied. I've made sure to add that to the list of headers and have verified it shows up in the request, but still the error persists.
Any thoughts to what I may be missing here?
EDIT:
Attempted to do a cURL request and received a 200 response back with the same information. Leading me to believe it's something with the axios call that I have incorrect.
I get this message when I don't provide either the client_id or the client_secret. Hopefully you can validate that you are actually sending both in your request. Maybe you can try the request via postman to double check.
I ran into the same issue and finally figured out you have to turn the data into a query string: https://axios-http.com/docs/urlencoded
For example:
import qs from 'qs';
const data = { 'bar': 123 };
const options = {
method: 'POST',
headers: { 'content-type': 'application/x-www-form-urlencoded' },
data: qs.stringify(data),
url,
};
axios(options);

GitHub OAuth App - getting token

I have an simple web app I'm testing on localhost (using http-server) in which I'm trying to authorise it following the GitHub tutorial.
I was able to redirect to GitHub page so the user can login there and get the temporary code returned from GitHub as query parameter.
Yet I can't get auth token because every time I send a POST request with all the required data I'm getting CORB error.
The code I'm using to do that:
const getGitHubToken = async code => {
return await fetch(authData.accessTokenURL, {
method: 'POST',
body: {
client_id: authData.client_id,
client_secret: authData.client_secret,
code
},
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
}
});
};
So my questions are:
why isn't it working
is it safe to keep client_id and client_secret on client side
any suggestions if it's good idea to apply this approach when my aim is to create an app able to query GitHub API (general stats, public repos), how can I do it better?

Get Authorization from HTTP-Request header

I already searched within SO for some threads about this, but could only find some which explained what this header is for or how to get the authorization header in c# but I don't want to read it from server side but from client side.
Is there any way to get the Base64 encoded header "Authorization" from the browser?
I want to implement a tool where you can log in and if you click on a spezific button your username will be saved.
My problem is that the browser does the authorization automatically, and with jQuery and JavaScript methods you can only set the requestheaders and get the responseheaders. I couldn't find a method to get the requestheaders.
The library gethttp could get some headers, but not the authorization header.
My guess is that this header is hidden.
I'm doing a login via SVN and the browser does the authorization the moment you enter the website.
Only the username is enough.
I'm searching for solutions where the user doesn't have to input their username.
I'm assuming you're trying to use the Basic Realm authorisation mechanism
This had already been replied on Stackoverflow and involves the $.ajax() jquery object.
How to use Basic Auth with jQuery and AJAX?
So please don't upvote me on this
$.ajaxSetup({
headers: {
'Authorization': "Basic XXXXX"
},
data: '{ "comment" }',
success: function (){
alert('Thanks for your comment!');
}
});
where XXXXX is your username:password base64 encoded
You can use native fetch API:
fetch("http://localhost:8888/validate",{
method:"GET",
headers: {"Authorization": "Bearer xxxxx"}
})
.then(res => res.json())
.then(
(result) => {
// do something
},
// Note: it's important to handle errors here
// instead of a catch() block so that we don't swallow
// exceptions from actual bugs in components.
(error) => {
// handle error
}
)
It's not possible to get the headers for the request of the CURRENT page. This has been asked several times on SO.
However, you can make a new request and retrieve the headers of that request. That way you are able to get the Basic Auth headers, base64 decode that string and then you have the username (and also the password).
Decoding base64 in javascript can be done using the following function as suggested by #michael in the comments.
window.atob("base64encodedString");

Categories