Invalid acces token - Graph Api with R - r

Until a month ago I was using the Rfacebook library with no problems. When I load the token I had generated and I want to use some function for example
getUsers("me",fb_oauth) #fb_oauth is my token
it gives me the following error:
Error in callAPI(url = url, token = token) :
Error validating access token: Session has expired on Tuesday, 04-Apr-17 13:24:59 PDT. The current time is Tuesday, 02-May-17 06:33:21 PDT.
To try to solve it I generate a new password in the app and generate a new token and I get the new token correctly:
fb_oauth <- fbOAuth(app_id="12345678", app_secret="xxxx")
Copy and paste into Site URL on Facebook App Settings: http://localhost:1410/
When done, press any key to continue...
Waiting for authentication in browser...
Press Esc/Ctrl + C to abort
Authentication complete.
But when I want to use the same function it gives me error
Error in callAPI(url = url, token = token) :
An access token is required to request this resource.
Also configure the login in the app but it does not work either
Anyone know how to generate the new token with the new 2.9 update?
Regards

As CBroe mentioned, the access token return format has changed and therefore the problem seems to be, that the credentials (including the access token) returned when authorizing with facebook is saved as the field name/key instead of the field value.
So a fix to this would be the following:
fb_oauth <- fbOAuth(app_id, app_secret, extended_permissions = FALSE,legacy_permissions = FALSE)
fb_oauth_credentials <- fromJSON(names(fb_oauth$credentials))
and then to make a request, such as getting a page would be;
fb_page <- getPage(page = "FBUserNameHere",
token = fb_oauth_credentials$access_token)

Related

Log in a webpage which uses github OAuth

I want to log in https://adventofcode.com/2021 programatically using httr.
I have only a very superficial understanding of the OAuth "dance", so to understand the principles I did the following:
Create an OAuth App on GitHub
Used the following code to authenticate (N.B. I know I could simply use oauth2.0_token but I felt that this workflow helped me to better understand the different messages, which are exchanged).
library(httr)
client_id <- "<my client id>"
base_url <- "https://github.com"
path <- "login/oauth/authorize"
client_secret <- "<my secret>"
url <- modify_url(base_url, path = path,
query = list(client_id = client_id,
redirect_uri = oauth_callback()))
code <- oauth_listener(url) ## needed to provide credentials in the web browser
access_token <- POST(modify_url(base_url, path = "login/oauth/access_token"),
add_headers(Accept = "application/json"),
body = list(client_id = client_id,
client_secret = client_secret,
code = code$code))
## successfully returns the values
GET("https://api.github.com/rate_limit",
add_headers(Authorization = paste(content(access_token)$access_token,
"OAUTH-TOKEN")))
From this example I think I understand the steps as highlighted in the documentation.
However, I fail to see how I could use this to login to https://adventofcode.com/2021. I have, of course, not the client_secret nor can I redirect the response to my localhost (as GitHub requires that the stored callback matches the redirect URI).
Thus, I was wondering how I could programatically login to https://adventofcode.com/2021 to fetch my task data, say?
I think you are mismatching OAuth2 roles. If you want to use adventofcode.com, you are a resource owner, adventofcode.com is a client and github is an authorization server. So you authenticate, adventofcode.com gets an auth code and then tokens. They can use the tokens to get information about your github account.
The example code you posted is different - your application is a client that gets a code and tokens from the authorization server (github) after a user was authenticated and gave a consent to passing the tokens to your app (permission delegation). So you probably cannot include adventofcode.com into this scenario.
The only way is if adventofcode.com takes a role of a resource server and their API accepts github tokens from different clients. But I know nothing about their API.

How to do YouTube OAuth Authentication/Reauthentication in R Automatically Using HTTR

I've been using the HTTR package to make requests to the YouTube Data API. I have two channels that I am getting stats for. Upon the first use, when requesting an access token I did the whole OAuth dance where I was redirected to Google as expected. However, I saved the tokens in .httr-oauth files. I developed a for loop similar to the following for me to get my statistics:
channelOneFile <- ".httr-oauth-channel1"
channelTwoFile <- ".httr-oauth-channel2"
myData <- list()
for(i in 1:2){
token <- try(suppressWarnings(readRDS(tokenFile)), silent = TRUE)[[1]]
# And Then I get stats with a GET Request
url <- paste0("https://youtube.googleapis.com/youtube/v3/videospart=contentDetails%2Csnippet",
"&id=",videoId)
request <- GET(url, token)
myData[[i]] <- request
}
which worked well for a while. However, after running this code roughly 20x or so (due to some testing and tweaking parameters, ONE of the get requests came back with
Auto-refreshing stale OAuth token.
Warning: Unable to refresh token: invalid_grant
Token has been expired or revoked.
At this point I'd just delete the ".httr-oauth" file, reauthenticate, save the new file, and then my code works again. However, I'm hoping to have this code automated on a local server, where the server (I think) can't do the OAuth dance if the token doesn't work.
When I make a request, I know HTTR automatically uses the refresh token to get a new access token, and I know that Google APIs has a limit of how many times a refresh token can be used. I think that perhaps when it gets the new token it doesn't update the ".httr-oauth" file? How can I get it to do that? If that's not an option, what can I do to do the authentication ONCE, save the credentials and access token and such in a file, and then refer to that file when making server requests?
UPDATE: Here is my OAuth flow:
if (file.exists(tokenFile)) {
token <- try(suppressWarnings(readRDS(tokenFile)), silent = TRUE)[[1]]
} else if (is.null(appId) | is.null(appSecret)) {
stop("Missing App Credentials")
} else {
token <- httr::oauth2.0_token(httr::oauth_endpoints("google"),
httr::oauth_app("google", appId, appSecret),
scope = c("https://www.googleapis.com/auth/youtube.readonly",
"https://www.googleapis.com/auth/yt-analytics.readonly"))
}
You need to refresh your access token, since this kind of OAuth tokens are short lived (usually are valid one hour). Use httrs function refresh_oauth2.0.
See this answer of mine for the procedure of handling refresh tokens offline: How to get my own Google API access token without using "Log in with Google"?
Note that a refresh token can be used as many times as needed for to renew an expiring access token. The refresh tokens usually do not expire (they do when one's app is in testing stage), but can be revoked.

R httr Linkedin API: Bad Request (HTTP 400)

My question is closely related to this one: LinkedIn API error of redirect uri from httr
Here is my code:
library(httr)
clientid <- "MY-ID"
secret <- "MY-SECRET"
app <- oauth_app(appname = "app name", key = clientid, secret = secret)
endpoint <- oauth_endpoint(base_url = "https://www.linkedin.com/uas/oauth2",
authorize = "authorization", access = "accessToken")
token <- oauth2.0_token(endpoint = endpoint, app = app)
As I do this, the browser opens with the message Authentication complete. Please close this page and return to R.
In R I get this:
Waiting for authentication in browser...
Press Esc/Ctrl + C to abort
Authentication complete.
Error in oauth2.0_access_token(endpoint, app, code = code, user_params = user_params, :
Bad Request (HTTP 400). Failed to get an access token.
I use the client id and secret given to my app on https://www.linkedin.com/developers/ and I did set the redirect URL there to http://localhost:1410/.
I'm on Ubuntu 18.04, R version 3.6.3, httr version ‘1.4.2’.
I think you might be missing the scope argument in oauth2.0_token().
Examples of LinkedIn scopes you could use would be: scope = "r_organization_social" or scope = "rw_organization_admin".
So it could look like:
token <- oauth2.0_token(endpoint = endpoint, app = app, scope = "rw_organization_admin")
It depends on how much access you've got and what data you'd like to request through the API
I solved the problem changing :token <- oauth2.0_token(endpoint = endpoint, app = app, scope = "w_member_social")

OAuth2 authentication with R using httr

I am trying to read some data from the Polar Accesslink API. I have read the documentation and examples (I'm not that familiar with Python) as well as httr examples/demos of Oauth2.0:
https://www.polar.com/accesslink-api/#polar-accesslink-api
https://github.com/polarofficial/accesslink-example-python
Here is my code:
library(httr)
client_id <- rstudioapi::askForPassword()
client_secret <- rstudioapi::askForPassword()
# redirect_uri determined in registration to http://localhost:1410/
app <- oauth_app(appname = "polar_app",
key = client_id,
secret = client_secret)
endpoint <- oauth_endpoint(
request = NULL,
authorize = "https://flow.polar.com/oauth2/authorization",
access = "https://polarremote.com/v2/oauth2/token")
token <- oauth2.0_token(endpoint = endpoint,
app = app,
scope = "accesslink.read_all", # tested also without scope
use_basic_auth = T # tested both T and F
)
Last part of the code (token) produces the following error:
Waiting for authentication in browser...
Press Esc/Ctrl + C to abort
Authentication complete.
Error in oauth2.0_access_token(endpoint, app, code = code, user_params = user_params, :
Bad Request (HTTP 400). Failed to get an access token.
It opens browser with url localhost:1410/?state={STATE}&code={CODE} and says:
"Authentication complete. Please close this page and return to R."
Based on the API documentation and github Python examples, I can't figure out if I need to set some values for user_params or query_authorize_extra in oauth2.0_token.
Having the same issue. Sent a message off to support and they came back with making sure that you include header "Content-Type: application/x-www-form-urlencoded" and that the body gets sent as plain/raw text and contains "grant_type=authorization_code&code=<AUTHORIZATION_CODE>".
I have not tested this out but hoping it helps you out if you have not already found a solution

Invalid Session ID found in SessionHeader - Salesforce

I am using OAuth2 for connecting my app with user's salesforce account. I am making authorization request with success and getting following things in response
access_token
instance_url
id
issued_at
signature
scope
token_type: Bearer
When I am trying to fetch salesforce data with following code
Dim binding As sforce.SforceService
binding = New sforce.SforceService()
binding.SessionHeaderValue = New sforce.SessionHeader()
binding.SessionHeaderValue.sessionId = <<access_token>> ' This is obtained by above step
binding.Url = <<id>> ' This is obtained by above step
dgr = binding.describeSObject("case")
I am getting exception
INVALID_SESSION_ID: Invalid Session ID found in SessionHeader: Illegal
Session. Session not found, missing session hash:
dGNP7MWaYz4kTAATqdvCAQk8H5NxD/xw/L+PpuPMpFA= This error usually occurs
after a session expires or a user logs out.
How can I fix it? I am sure I am passing something wrong but can't figure out what.

Resources