How to CURL -H basic auth in R to access API - r

I want to retrieve data from a classifier API. The documentation showed me:
curl -H "Authentication: Basic <my_secret>" "http://www.superapi.io/classifier/test
model_id=123&value=your+text"
How do I implement this in R? I tried with package RCurl:
getURL("http://www.superapi.io/classifier/test",
userpwd ="secret",
httpheader=list(model_id="123",value="your+text"))
but this was didnt work:
[1] "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 3.2 Final//EN\">\n<title>405 Method Not
Allowed</title>\n<h1>Method Not Allowed</h1>\n<p>The method is not allowed for the requested
URL </p>\n"

answer:
getURL("http://wwww.superapi.io/classifier/test?_model_id=123&value=TEST", userpwd="<secret>",
httpauth = 1L)

Related

Password Grant generate token using HTTR package in R OAuth2

Brand new to API's and in a bit over my head. Reading a bit and searching around but still confused. I was given the following code to run in curl to generate a token using oauth2 with the password grant. I want to implement this code in R and running into some issues.
curl -H "Content-type: application/x-www-form-urlencoded" -H "Authorization: Basic xxxyyy123xxx==" -d "grant_type=password&username={username}&password={password}" https://{website}.com/rest/v2/oauth/token
When I run the above command in a terminal it generates a token which I have successfully used in R using this code:
token <- {character string generated by the above curl command}
call <- "https://{website}.com/rest/v2/services/APIService/getRegistryRecordByAccessionID?id={id#}"
df <- as.data.frame(fromJSON(content(httr::GET(call, add_headers(Authorization = paste("Bearer", token))), "text"), flatten = TRUE))
All I want is to generate the token in R instead of using another program like I have been. This is where my errors come up. The basic format I believe is:
token <- oauth2.0_token(endpoint = oauth_endpoint(
authorize = NULL,
access = "https://{website}.com/rest/v2/oauth/token"),
app = oauth_app(), #not sure how to set this up
use_basic_auth = T,
add_headers(Content-type = "application/x-www-form-urlencoded",
Authorization = "Basic xxxyyy123xxx==") #not sure if i need the authorization header here, I believe I need the content-type heder
)
From MrFlick's comments above, we can integrate the curl auhtorization commands into a POST using the httr package. We then look at the content of the object this returns which will include the access token in the first item in the list.
token <- content(httr::POST("https://{website}.com/rest/v2/oauth/token", body=list(grant_type="password", "username="{username}", password="{password}"), encode="form"))[[1]]

HTTP POST using httr in R

I am trying to adapt my curl request from running it in Terminal to R. For this I am using the httr package. My request is as follows and works from Terminal
curl -u user#email.com:password -H "Content-Type:application/json" -X POST "https://catalogue.onda-dias.eu/dias-catalogue/Products(48809a01-71bc-4669-8639-f0528abcdafe)/Ens.Order"
My attempt to use httr POST function is as follows:
pars <- list(username='user#email.com', password='password')
res<-POST("https://catalogue.onda-dias.eu/dias-catalogue/Products(48809a01-71bc-4669-8639-f0528abcdafe)/Ens.Order", body = pars, add_headers('Content-Type'='application/json'))
I am getting a 401 error code. Do you know how should I properly convert my request?
Try using httr:authenticate
require(httr)
headers = c('Content-Type' = 'application/json')
r <- httr::POST( url = 'https://catalogue.onda-dias.eu/dias-catalogue/Products(48809a01-71bc-4669-8639-f0528abcdafe)/Ens.Order'
, httr::add_headers(.headers=headers)
, httr::authenticate('user#email.com', 'password'))

Artifactory access token works via Bearer, not user

Artifactory OSS
5.4.6 rev 50406900
Trying to get access token to work.
I created token...
e.g. curl -uadmin:adminpw -X POST "myserver:8081/artifactory/api/security/token" -d "username=moehoward"
Returned msg looks like success...
{
"scope" : "member-of-groups:readers api:*",
"access_token" : <very-long-string>
"expires_in" : 3600,
"token_type" : "Bearer"
}
I can see it in the gui (admin -> Security -> Access Tokens) with "Subject" = to the user ("moehoward" in the example above) and with a "Token ID" that's a lot shorter, something like...
f2eb693a-d4ff-4618-ba52-764dc975c497
To test, I tried to ping using example in the docs...
curl -umoehoward:<very-long-string> myserver:8081/artifactory/api/system/ping
Fails with a 401 (bad credentials).
I replace the token with the "token id" I see in the gui, same result.
I replace again with the hardcoded pw of the "moehoward" user and that works (responds with "OK").
I tried the "-H"Authentication: Bearer " approach using the long string and that worked. So I guess the very long string is the token and not the "Token ID" in the gui.
Q: Any idea why this works for Bearer" and not the user by name ?
So you are right that this is supposed to work for both standard authentication and the Authentication HTTP header.
I did the test on a server with the same version Artifactory OSS 5.4.6 and the following works fine here
Inject the proper variables
export SERVER=server-artifactory
export APIKEY=XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
Create and use an access token for user moehoward
curl -u "admin:$APIKEY" -X POST "http://$SERVER/artifactory/api/security/token" -d "username=moehoward" -d "scope=member-of-groups:readers" > token.log
export TOKEN=`cat token.log | jq -r '.access_token'`
curl -u "moehoward:$TOKEN" "http://$SERVER/artifactory/api/system/ping"
curl -H "Authorization: Bearer $TOKEN" "http://$SERVER/artifactory/api/system/ping"
I get "OK" from the last two commands. Can you run exactly these commands and report back?
I have personally experienced the same problem (Bearer header working, standard user credentials not working) with an old version of curl. The obvious workaround is to use Bearer, the more complex workaround is to upgrade curl (or use another tool).
What is the version of curl you use? Any curl from 2015 or more recent should work fine.

httr POST authentication error

I am trying to structure a POST json request using httr. The API documentation proposes the following the CURL request:
curl -X POST -H "Authorization:Token XXXXXXXXX" -H "Content-Type: application/json" --data "{\"texts\":[\"A simple string\"]}" https://api.uclassify.com/v1/uclassify/topics/classify
My R httr implementation is the following:
POST("https://api.uclassify.com/v1/uClassify/Topics/classify",
encode="json",
add_headers('Authorization:Token'="XXXXXXXXX"),
body=("A simple string"))
But I received a 401 error message which indicates that my authentication failed. Any suggestion on how I can implement the CURL request on httr?
Just in case it can help somebody else, the below code works for me:
POST("https://api.uclassify.com/v1/uClassify/Topics/classify",
encode="json",
add_headers(Authorization = "Token XXXXXXXXX"),
body = "{\"texts\":[\"A simple string\"]}")

How do I get an API token using R, cURL command on cygwin terminal works (windows 8)

I am able to get a API authentication token using the curl command on cygwin terminal on windows
curl -X POST -d '{"username":"usenamexxx","password":"passwordxxx"}' https://demo.website.com/api/token
output looks like
{"token":"87JrlYIOQa6g6aXciJOxNUK81","_links":{"DiscoveryPage":{"title":"Available API Resources","href":"https://demo.website.com/api"}}}
but when I try the POST command from R using the httr package I get the following error
library(httr)
tokenURL <- "https://demo.website.com/api/token"
s <- POST(tokenURL,body = list(username = "usenamexxx",password = "passwordxxx" ))
Error in function (type, msg, asError = TRUE) :
Unknown SSL protocol error in connection to demo.website.com:443
What am I doing wrong. Is there a different way to use POST?
Sorry I cannot provide a reproducible example as I cannot share my authentication details. If there is a way to provide more details please let me know.

Resources