Mendeley で自分のライブラリの操作を行う
前回(RでMendeleyのAPIを叩いてみる)はアノニマスな認証でMendeleyのAPIを触ってみました。
今回はOAuth認証で自分のライブラリにアクセス権限を持つトークンを作成後APIを叩いてみたいと思います。
Authorization code flow
コード
各種情報の入力
username <- "MendeleyのID(E-mail addres)"
password <- "Mendeleyのパスワード"
client_id <- "アプリケーションID"
client_secret <- "アプリケーションSecret"
redirect_uri <- "アプリケーションに登録したURL"
state <- "213653957730.97845" #CSRF対策用のコード、何でもよい
利用するAPIの設定
利用するMendeley APIを適宜設定してください。
http://dev.mendeley.com/ から選べます。
api <- "https://api.mendeley.com/documents?limit=100"
ライブラリと文字列操作用の二項演算子の設定
require(httr)
require(rjson)
require(RCurl)
require(dplyr)
'%+%' <- paste0
Mendeleyのユーザー認証URLにユーザー情報入力をしてアプリケーション側で利用するコードを得る
basic_auth_credentials <- RCurl::base64(paste(client_id, client_secret, sep = ":"))
auth <-
POST(
"https://api.mendeley.com/oauth/authorize?client_id=" %+%
client_id %+%
"&redirect_uri=" %+%
redirect_uri %+%
"&response_type=code&scope=all&state=" %+%
state
,
add_headers(
'Content-Type' = 'application/x-www-form-urlencoded'
),
body = "&username=" %+% username %+% "&password=" %+% password
)
code <- auth$url %>%
{function(x) strsplit(x, split="\\?")[[1]][2]}() %>%
{function(x) strsplit(x, split="\\&")[[1]][1]}() %>%
{function(x) strsplit(x, split="\\=")[[1]][2]}()
得られたコードからアクセストークンを得る
access_token_rsp <-
POST(
'https://api.mendeley.com/oauth/token',
add_headers(
'Authorization' = paste("Basic", basic_auth_credentials),
'Content-Type' = 'application/x-www-form-urlencoded'
),
body = "grant_type=authorization_code&code=" %+%
code %+% "&redirect_uri=" %+% redirect_uri
)
access_token <- content(access_token_rsp)$access_token
APIを叩いて、欲しい情報を得たり、やりたい操作を行う
doc_rsp <- GET(api,
add_headers(
'Authorization' = paste("Bearer", access_token),
'Content-Type' = 'application/vnd.mendeley-document.1+json' #APIを変える場合、ここも適宜変える必要あり
)
)
docs <- doc_rsp %>% content %>% rawToChar %>% fromJSON
docs %>% lapply(function(x) x$title)