Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using oauth2.0 tokens with R's httr package

Problem

The package httr provides CURL wrappers in R (see package documentation).

I'm brand new to HTTP and APIs. My trouble is getting oauth2.0 authentication to work. I have tried various syntax and get either errors or status 401.

What is the correct way to use an oauth2.0 token and make a GET() request using httr?

Code Attempts

# Set UP
  
  url = "https://canvas.{institution}.edu/api/v1/courses"
  key = "{secret_key}"

# 1
  GET(url, sign_oauth2.0(key)) 
  # Error: Deprecated: supply token object to config directly

# 2
  GET(url, config(sign_oauth2.0 = key)) 
  # unknown option: sign_oauth2.0

# 3
  GET(url, config = list(sign_oauth2.0 = key)) 
  # Status 401
like image 902
Danielle Avatar asked Jul 06 '17 21:07

Danielle


People also ask

Which format does OAuth 2.0 require tokens to use?

Bearer Tokens are the predominant type of access token used with OAuth 2.0. A Bearer Token is an opaque string, not intended to have any meaning to clients using it. Some servers will issue tokens that are a short string of hexadecimal characters, while others may use structured tokens such as JSON Web Tokens.

Is OAuth2 compatible with oauth1?

OAuth 2.0 is not backwards compatible with OAuth 1.0 or 1.1, and should be thought of as a completely new protocol. OAuth 1.0 was largely based on two existing proprietary protocols: Flickr's authorization API and Google's AuthSub.


1 Answers

Solution

In this particular use case—working with the Canvas API—additional information is required in the header of the request.

Using the GET function from the httr R package, use the add_header parameter to supply the argument including your oauth2 key.

Use Option 1 if you don't want to hard code your key into the request (recommended). Or, use Option 2 and insert the key as a string. But in both cases, "Bearer " precedes the key.

# Set Up
url = "https://canvas.{institution}.edu/api/v1/courses"
key = "{secret_key}"

# OPTION 1
GET(url, add_headers(Authorization = paste("Bearer", key, sep = " ")))

# OPTION 2
courses.request = GET(url, add_headers(Authorization = "Bearer {secret_key}"))

#Further Explanations

  • Explanation of Authorization Header
  • Rationale for why "Bearer " must go before the key.
  • The OAuth Bible is useful for understanding components of a request

Can anyone else explain other reasons why the OP's examples didn't work?

like image 89
Danielle Avatar answered Sep 29 '22 12:09

Danielle