Getting 401 error from Post request in R with Bearer token - r

Im trying to update a body on a postman POST which ask for Bearer Token (that I have) but still getting 401 error..
I first request the Token
login <- list(
"corporateEmail" = " xxx#xxx.com",
"password" = "xxx"
)
test <- httr::POST("https://xxxx", body = login, encode = "json")
and succesfully the the access token in the response.
then trying to do the post to change the body
test2 <- httr::POST(url = urls,
add_headers(Authorization = token),
body = bodys,
encode = "json",
verbose())
and i get 401...
the body is correct and I have tryed with Authorization = paste("Bearer",token)... the Postman configuration of the request is that Bearer is add in Auth tab and not directly in the Header tab.
Post request, expecting 200 answer

Related

How to send basic authorization header with Python3.6.9 urllib3

I am trying to send an API call to get the time from the Questrade platform. Here is the sample request from their guide
GET /v1/time HTTP/1.1
Host: https://api01.iq.questrade.com
Authorization: Bearer C3lTUKuNQrAAmSD/TPjuV/HI7aNrAwDp
I am able to get it working with the request module
headers = {'Authorization': f'{token_type} {access_token}'}
print(headers) -> {'Authorization': 'Bearer -xSoUNCLYCrFjxxxxx_wAQVpi4olWrQs0'}
qt_time_obj = requests.get(api_server + 'v1/time', headers=headers)
qt_time = qt_time_obj.json()['time']
print(qt_time) -> 2020-10-13T17:06:32.388000-04:00
Now I am trying to get urllib3 to work but without luck
headers = {'Authorization': f'{token_type} {access_token}'}
url = api_server + 'v1/time'
http = urllib3.PoolManager()
qt_time_obj = http.urlopen('GET', url, headers)
print(qt_time_obj.status) -> 401
print(qt_time_obj.data) -> b'{"code":1014,"message":"Missing authorization header"}'
I also tried with the make_headers method but it gives me the same error.
headers = urllib3.make_headers(basic_auth="Authorization: Bearer AdKt3YUl46_tGnZp7cRgTu4W2vtfBME50")
Could you point where I did wrong? Thank you!
So after some trying, I found that I need to use http.request instead of the http.open. I also need to do "headers=headers" instead of just the "headers" in the method.
qt_time_obj = http.request('GET', url, headers=headers)

Posting a file to an outside API with a JSON web token

I am trying to upload a database file to an outside organization's API using R. I have a username and password, as well as an separate address to get the token from, and then to upload the file.
usr<-"username"
pw<-"passwood"
url <- "https:/routurl/api/"
Token='Token'
UploadFile='UploadFile'
#Get Token
r <- httr::POST(url = paste0(url,Token),
body = list(
UserName = usr,
Password = pw,
grant_type = "password"
), verbose())
tkn=jsonlite::prettify(httr::content(r, "text"))
This seems to work, as I can extract a token from the content.
> tkn
{
"result": {
"token": "eyJhbGciOiJIUzFAKEIsInR5cCI6IkpCJ9.eyJodHRwOi8vc2NoZW1hcy54bWxzb2FwLm9yZy93cy8yMDA1LzA1L2lkZW50aXR5L2NsYWltcy9uYW1lIjoiZ3JphzZSIsImp0aSI6IjUwNmIwN2MyLTTHISISFAKEIwMDUvMDUvaWRlbnRpdHkvY2xhaW1zL2VIVECHANGEDTHINGScyI6ImVtaWx5dGdyaWZmaXRoc0BiaW9zLmF1LmRrIiwiZXhwIjoxNTk4NzEwMTU3LCJpc3MiOiJ2bXNhcHAiLCJhdWQiOiJ2bXN1c2VycyJ9.z8sr-HT21u1bN7qCEXAMPLEONLY-TKAluO3k",
"expiration": "29 August 2020 16:09:17"
},
"id": 2,
"exception": null,
"status": 5,
"isCanceled": false,
"isCompleted": true,
"isCompletedSuccessfully": true,
"creationOptions": 0,
"asyncState": null,
"isFaulted": false
}
#re-formatting
tkn=jsonlite::fromJSON(content(r, "text"), simplifyVector = FALSE)
So, this all seems ok, however, if I try to double check this on the JSON DeCoder, my correct web information comes up in the payload, but at the bottom it claims it is an invalid signature.
Also, the auth_token variable is NULL in the request, and that doesn't seem right.
> r$request$auth_token
NULL
However, I can't test this because I cannot, for the life of me, figure out how to use this JWT to POST a file to the rooturl/UploadFile. Every document I look at that goes over how to POST to an API does not include how to include your JWT in the POST, or at least it isn't very clear. Is it in the header? Is it like this?
r2=POST(url=paste0(url,UploadFile), body = list(y = upload_file('O:/Igoturfilerighthere.h5')),
add_headers('Authorization' = paste("Bearer", tkn$result$token, sep = " ")), encode = "json", verbose())
Am I setting the headers incorrectly?
r3=POST(url=paste0(url,UploadFile), body = list(y = upload_file('O:/Igoturfilerighthere.h5')),
httr::add_headers("x-auth-token"=tkn$result$token), verbose())
For the r3 request I get a 401 error, which makes me think that I am on the correct path and that I am entering my token information incorrectly. If anyone could help guide me on the next step, I'd appreciate it. I just don't know where else to place that information.
Cheers,
etg
UPDATE:
If, in the initial request, I add 'encode = "json"', it throws a 400 Bad Request Error. This is how the website I am trying to upload to writes its own code. I've double checked my username and password, and they are correct.
r <- httr::POST(url = paste0(url,Token),
body = list(
UserName = usr,
Password = pw,
grant_type = "password"
),encode = "json", verbose())
HTTP/1.1 400 Bad Request
Transfer-Encoding: chunked
Content-Type: application/problem+json; charset=utf-8
Server: Microsoft-IIS/10.0
Strict-Transport-Security: max-age=2592000
X-Powered-By: ASP.NET
So, I reached out to the org behind the API I was trying to access, and there few a few problems with my JWT request. This is the correct code:
r <- httr::POST(paste0(url,Token),
body = list(UserName = usr, password = pw),
encode = "form", verbose())
The big difference is 'grant_type' is removed and 'encode="form"', as I was trying to log in via a form on their site. With that difference, I was able to upload a file using the following:
r2=POST(url=paste0(url,UploadFile), body = list(fileToUpload = httr::upload_file('O:/IGotUrFileHere.h5')),
httr::add_headers('Authorization' = paste("Bearer", tkn$result$token, sep = " ")), verbose())
Again, the verbose() function isn't necessary. It just helps you troubleshoot. Good luck!

API authentication in R - unable to pass auth token as header

I am looking to do a simple GET request (from the Aplos API) in R using the httr package. I'm able to obtain a temporary token by authenticating with an API key, but then I get a 401 "Token could not be located" once trying to use the token to make an actual GET request. Would appreciate any help! Thank you in advance.
AplosURL <- "https://www.aplos.com/hermes/api/v1/auth/"
AplosAPIkey <- "XYZ"
AplosAuth <- GET(paste0(AplosURL,AplosAPIkey))
AplosAuthContent <- content(AplosAuth, "parsed")
AplosAuthToken <- AplosAuthContent$data$token
#This is where the error occurs
GET("https://www.aplos.com/hermes/api/v1/accounts",
add_headers(Authorization = paste("Bearer:", AplosAuthToken)))
This is a Python snippet provided by the API documentation:
def api_accounts_get(api_base_url, api_id, api_access_token):
# This should print a contact from Aplos.
# Lets show what we're doing.
headers = {'Authorization': 'Bearer: {}'.format(api_access_token)}
print 'geting URL: {}accounts'.format(api_base_url)
print 'With headers: {}'.format(headers)
# Actual request goes here.
r = requests.get('{}accounts'.format(api_base_url), headers=headers)
api_error_handling(r.status_code)
response = r.json()
print 'JSON response: {}'.format(response)
return (response)
In the python example, the return of the auth code block is the api_bearer_token which is base64 decoded and rsa decrypted (using your key) before it can be used.
...
api_token_encrypted = data['data']['token']
api_bearer_token = rsa.decrypt(base64.decodestring(api_token_encrypted), api_user_key)
return(api_bearer_token)
That decoded token is then used in the api call to get the accounts.
The second issue I see is that your Authorization header does not match the example's header. Specifically, you are missing the space after "Bearer:"
headers = {'Authorization': 'Bearer: {}'.format(api_access_token)}
vs
add_headers(Authorization = paste("Bearer:", AplosAuthToken)))
Likely after addressing both of these you should be able to proceed.

QuickBooks OAuth API (401) Unauthorized

Here is the OAuth library I'm using: https://github.com/danielcrenna/oauth
I'm getting the token, secret and realmId (company id) just fine and storing them, but when I go to do a simple request, I get (401) Unauthorized.
Here's the code I'm using:
var rq = new OAuthRequest
{
Method = "GET",
Type = OAuthRequestType.ProtectedResource,
SignatureMethod = OAuthSignatureMethod.HmacSha1,
ConsumerKey = ConfigurationManager.AppSettings["ConsumerKey"],
ConsumerSecret = ConfigurationManager.AppSettings["ConsumerSecret"],
Token = requestToken,
TokenSecret = requestTokenSecret,
RequestUrl = "https://quickbooks.api.intuit.com/v3/company/" + realmId + "/query?query=select%20%2A%20from%20CompanyInfo&minorversion=4",
Version = "1.0",
};
And the Auth header:
OAuth oauth_consumer_key="****",oauth_nonce="6su4ljd2is5bxns4",oauth_signature="0taFXiouzOkpK258tz%2Fc%2F2fVQ0c%3D",oauth_signature_method="HMAC-SHA1",oauth_timestamp="1461339515",oauth_token="****",oauth_version="1.0"
I can't find any other details in the error, I'm just getting "401 Unauthorized." How do I get this request to go through?
Oauth is pretty strict in how the header is written. Why not use one of the Libraries already provided by Intuit? or use the API Explorer to view the header and compare to your request header?
The order of the oauth header parameters matter, and version is not the last one. See this guide.
https://developer.intuit.com/docs/0050_quickbooks_api/0010_your_first_request/rest_essentials_for_the_quickbooks_api

API 1.1 requesting twitter bearer token using r

I have searched this forum and tried several things that seemed relevant, but with no success. If anyone can spot what I'm missing I would be very grateful.
I am trying to get a bearer token using application only authorization as explained at https://dev.twitter.com/docs/auth/application-only-auth so that I can GET follower s/ids.
I have constructed a request in r using rstudio with my consumer key & secret in Base64 encoded form.
library(httr)
POST(url="https://api.twitter.com/oauth2/token", config=add_headers(
c('Host="api.twitter.com"',
'User-Agent="NameOfMyApp"',
'Authorization="Basic MyKeyandSecretBase64Encoded"',
'Content-Type="application/x-www-form-urlencoded;charset=UTF-8"',
'Content-Length="29"',
'Accept-Encoding="gzip"')), body="grant_type=client_credentials")
In response I receive:
Response [https://api.twitter.com/oauth2/token]
Status: 403
Content-type: application/json; charset=utf-8
{"errors":[{"label":"authenticity_token_error","code":99,"message":"Unable to verify your credentials"}]}
I tried resetting my credentials but it made no difference.
I'm a few weeks late, but for anyone like me who stumbles across this page, here is some code that works for me, returning a bearer token:
POST(url="https://api.twitter.com/oauth2/token",
config=add_headers(c("Host: api.twitter.com",
"User-Agent: [app name]",
"Authorization: Basic [base64encoded]",
"Content-Type: application/x-www-form-urlencoded;charset=UTF-8",
"Content-Length: 29",
"Accept-Encoding: gzip")),
body="grant_type=client_credentials")
Once you have a bearer token, you put it in the header of a GET like so:
GET("https://api.twitter.com/1.1/followers/ids.json?cursor=-1&screen_name=justinbieber&count=5000",
config=add_headers(c("Host: api.twitter.com",
"User-Agent: [app name]",
"Authorization: Bearer [bearer token]",
"Accept-Encoding: gzip")))
A late response, but the existing answer wasn't working for me. So here's a solution with a modification of the GET request.
add_headers() uses a named vector. This requires the hyphenated header names to be bracketed with backticks (``). So your POST() call should be:
response <- POST(url = "https://api.twitter.com/oauth2/token",
config = add_headers(.headers = c(Host = "api.twitter.com",
`User-Agent` = "NameOfMyApp",
Authorization = "Basic [base64encoded]",
`Content-Type` = "application/x-www-form-urlencoded;charset=UTF-8",
`Content-Length` = "29",
`Accept-Encoding` = "gzip")),
body = "grant_type=client_credentials")
Within a successful response the application access token can be accessed with:
bearer_token <- jsonlite::fromJSON(rawToChar(response$content))$access_token
You can then verify this with a GET request, such as:
GET("https://api.twitter.com/1.1/followers/ids.json?cursor=-1&screen_name=justinbieber&count=100",
config = add_headers(.headers = c(Host = "api.twitter.com",
`User-Agent` = "NameOfMyApp",
Authorization = paste("Bearer", bearer_token),
`Accept-Encoding` = "gzip")))

Resources