How to use Swagger API with Bearer Auth in R - r

What is the syntax to use the Swagger API in R with the Bearer Auth?
(this is a question relating to the Cherwell API)

Prep: you will need a user id, password for the swagger server...
Then you'll need your public token
Then you'll need to generate the Bearer token...
I used swagger to do this via the browser tool.
Then this should set you right once you've replaced the 'xxx's with your prementioned creds.
library(httr)
library(jsonlite)
usr = 'xxx'
pwd = 'xxx'
tkn = 'xxxx'
qry <- paste0("https://xxx/xxx/api/V1/getteams?api_key=",tkn)
bearer <- "Bearer xxx"
res <- GET(qry,
authenticate(usr,pwd),
add_headers(Authorization = bearer)
)
content(res)

Related

Authenticating OAuth2.0 with R using httr

I'm trying to create authenticate into the Letterboxd API using R and the httr package. The Letterboxd docs give instructions, but I am not sure how to put everything together into a URL.
I know the url is:
url <- "https://api.letterboxd.com/api/v0/auth/token"
And then they want my username and password, presumably as JSON, but what I'll write as a named list since I'm doing this in R:
login_info <- list(
grant_type = "password",
username = "myemail#gmail.com",
password = "extremelysecurepassword"
)
I've tried various calls, using GET(), oauth2.0_token(), oauth_endpoint() functions from the httr package.
I feel like I have all the necessary information and am circling around a solution, but I can't quite nail it.
The docs contain this information:
When generating or refreshing an access token, make a form request to the /auth/token endpoint with Content-Type: application/x-www-form-urlencoded and Accept: application/json headers
(Full text is linked to above)
And I'm not sure how to add that information; in working with APIs through R, I'm used to just sending URLs with UTM parameters, but the inputs they want don't work here using ? and &.
I'm aware of this related post, but it looks like it relies on having a secret token already. And I don't seem to be able to generate a secret token inside of the GUI of Letterboxd.com, which is again what I'm used to doing with authentication. I think I need to feed it those sources of information above in login_info to the url, but I don't quite know how to connect the dots.
How do I authenticate to the Letterboxd API using R?
This runs for me but I get a 401 Unauthorized since you correctly did not supply valid credentials. It looks like there is a python library for this API https://github.com/swizzlevixen/letterboxd if you need hints how to make subsequent requests.
sign_request() is mimicking python library's api.py#L295-L304
sign_request <- function(apisecret, url, method, body = "") {
signing_bytes <- as.raw(c(charToRaw(method), 0, charToRaw(url), 0, charToRaw(body)))
# https://stackoverflow.com/a/31209556/8996878
# https://stackoverflow.com/q/54606193/8996878
digest::hmac(key = apisecret, object = signing_bytes, algo = "sha256", serialize = FALSE)
}
url <- "https://api.letterboxd.com/api/v0/auth/token"
login_info <- list(
grant_type = "password",
username = "myemail#gmail.com",
password = "extremelysecurepassword"
)
apikey <- "mytopsecretapikey"
apisecret <- "YOUR_API_SECRET"
method <- "POST"
params <- list(
apikey = apikey,
nonce = uuid::UUIDgenerate(),
timestamp = round(as.numeric(Sys.time()))
)
# now we need to sign the request
body <- paste(names(login_info), login_info, sep = "=", collapse = "&")
body <- URLencode(body)
body <- gsub("#","%40", body) # something URLencode doesn't do but post does
destination <- httr::parse_url(url)
destination$query <- params
post_url_with_params <- httr::build_url(destination)
signature <- sign_request(apikey, post_url_with_params, method, body)
token_request <- httr::POST(url, httr::add_headers(
"Accept" = "application/json",
"Authorization" = paste0("Signature ", signature)
),
query = params,
body = login_info, encode = "form", httr::verbose()
)
token_body <- httr::content(token_request, type = "application/json")
# look for the value of"access_token"

Access Reddit API using OAuth2 in R: how to request and update token

Resolved
I am using the following R code to acquire a token from Reddit API on behalf of a user. However, tokens expire in an hour. To keep access with that app, I need to use a refresh_token parameter that I would receive with a first request, I understand. However, for some reason, I cannot receive a refresh_token using the following code:
#API app settings reddit:
endpoint <- oauth_endpoint(
authorize = "https://www.reddit.com/api/v1/authorize",
access = "https://www.reddit.com/api/v1/access_token"
)
appName <- "xxx"
key <- "xxx"
secret <- "xxx"
app <- oauth_app(appName, key, secret)
# authenticate using OAuth2 [an issue with token]
token <- oauth2.0_token(
endpoint = endpoint,
app=app,
scope = c("read"),
user_params = list(duration = "permanent"),
use_basic_auth = TRUE,
config_init = user_agent("Testing"),
cache = TRUE
)
That's how the resulted token looks like:
print(token$credentials)
$access_token
[1] "xxx"
$token_type
[1] "bearer"
$expires_in
[1] 3600
$scope
[1] "read"
Would anybody please suggest how to improve this request?
The request should include duration = "permanent" attribute in query_authorize_extra field
Here is a corrected request:
token <- oauth2.0_token(
endpoint = endpoint,
app=app,
scope = c("read"),
query_authorize_extra = list(duration = "permanent"),
use_basic_auth = TRUE,
config_init = user_agent("Testing"),
cache = TRUE
)
In one hour, token updates itself automatically ones a get or other type of request sent

Trying to access Indeed API using HTTR ( R Programming)

I am a API newbie trying to access a certain webpage on Indeed.Com website using it's API for my employer.I am not able to receive token once I am sending the CLIENT ID AND SECRET ID.Any help is appreciated.
The Indeed API documentation : http://opensource.indeedeng.io/api-documentation/docs/oauth/#before-you-start
Indeed Employer API : https://employers.indeed.com/api/v1
options("httr_oob_default" = T)
options("httr_oauth_cache"= T)
Sys.setenv("HTTR_SERVER_PORT" = "1410/")
library(httr)
library('httpuv')
#Token Request URL
request_url = 'https://secure.indeed.com/'
#Token Access URL
access_url = 'https://secure.indeed.com'
#Authorization URL
authorization_url = 'https://secure.indeed.com/account/oauth?client_id="Your client ID" &redirect_uri=http://localhost:1410/&response_type=code'
#Saving client ID and Secret ID
key <- 'YOUR CLIENT ID'
secret <- 'CLIENT SECRET ID'
#Sending OAUTH Request
myinapp = oauth_app(NULL, key, secret)
in_app = oauth_endpoint(request_url, authorization_url, access_url)
#Getting Token
token = oauth1.0_token(in_app, myinapp)
#Authenticating Token
mytoken = config(token = token)

HTTP API Authentification in R via 0auth

I got some problems accessing tracking API via 0auth;
I have sign key, secret and Authorization_key.
Sign key and secret should form a sig file as I understand and authorization_key that should be added as header.
The code:
auth_info <-
read.csv2('./Data/auth_info.csv',
encoding = 'UTF-8',
stringsAsFactors = F)
express <-
oauth_app("express", key = 'Ur1475', secret = auth_info$sign_key)
sig <- sign_oauth1.0(express)
order <-
GET(
"http://www.express.ru/api/v2/getOrder?orderNumber=WEBN3141018",
authenticate("Ur1475", auth_info$sign_key),
add_headers(Authorization = auth_info$auth_key),
sig
)
order_info <- content(order)
order_info
Returns me auth error;
Official api documentation tells that should be formed md5(client key . URL . GET params . POST params . sign key).
Also I've looked at 0auth function code it does not use http.
Could it cause the problem?
Could you please comment on how to get data from API via R?
API doc (in russian)): https://www.express.ru/docs/APIExpressRu.pdf
The major of API's (Google, Twitter, Facebook) need a token that you must to obtain from an oauth authentication. Depending from the API's you must to use the functions GETor POST. And you must to provide your key encoded in base64. So what I think you need is:
First: Authenticate.
if(!require("jsonlite")){library("jsonlite")}
if(!require("httr")){library("httr")}
#Create your own appication key
consumer_key <- "your consumer key" #needed
consumer_secret <- "your consumer secret" #some api's don't need.
#Use basic auth
secret <- jsonlite::base64_enc(paste(consumer_key, consumer_secret, sep = ":"))
req <- httr::POST("https://url.of.your.api/oauth/token", #"oauth" and "token" are not parameters, they are fixed.
httr::add_headers(
"Authorization" = paste("Basic", gsub("\n", "", secret)),
"Content-Type" = "application/x-www-form-urlencoded;charset=UTF-8"
),
body = "grant_type=client_credentials"
)
#Extract the access token
token <- paste("Bearer", httr::content(req)$access_token)
Next: Make a request.
url<-"http://url.of.your.api/search?parameter1=value&parameter2=value"
req <- httr::POST(url, httr::add_headers("Authorization" = token))
json <- httr::content(req)
json
As I said, some API's need GETand others POST, try both.

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.

Resources