LoginSignup
0
1

More than 5 years have passed since last update.

mrubyでOAuth2

Last updated at Posted at 2019-01-04

IoTでOAuth2の実践編で蟹さんのmrubyからDropboxにファイルを放り込んでみます。

まず準備にmruby VMにmruby-base64とmruby-jsonをつっこみます。mruby-jsonにはfileアクセスがありリンクできなかったので、fileアクセスをとるprを出してマージしてもらいました。

次はDropboxのdeveloperのサイトでアプリを作ります。Full accessにしておきます。これでApp keyとApp secretが入手できました。

次はブラウザーで以下のURLを叩いて、アクセス許可のcodeを手に入れます。

忘れていたのですが、Dropboxの認証コードという記事を書いてました。

App keyとApp secretはmrubyのスクリプトにハードコードしますが、codeはスクリプトがリダイレクトやフォームで受け取るようにするがいいです。まだHTTPやHTTPSのLISTENの実装がないので、とりあえずハードコードします。

APPKEY = ""
APPSEC = ""
CODE = ""

yabm = YABM.new

yabm.netstartdhcp

ntpaddr = "10.0.1.18"
yabm.sntp(ntpaddr)

header = Hash.new
header.store('User-Agent', "test-agent")
header.store('Authorization', "Basic " + Base64.encode(APPKEY + ":" + APPSEC))
ustr = "/1/oauth2/token?grant_type=authorization_code&code=" + CODE
res = SimpleHttp.new("https", "api.dropbox.com", 443).post(ustr, header)

これでAccess Tokenがjsonでもらえるのでjsonのパーサーに食わせます。

data = JSON::parse(res.body)
accesstoken = data["access_token"]

この操作は一回だけで、Access TokenはFlashなどに保存しておく必要があります。

Access Tokenを使ってファイルをuploadします。

path = "yabm"
name = "morimori.txt"
body = "Hello mruby on YABM !"

header = Hash.new
header.store('User-Agent', "test-agent")
header.store('Authorization', "Bearer " + accesstoken)
header.store('Content-Type', "application/octet-stream")
header.store('Dropbox-API-Arg', "{¥"path¥": ¥"/" + path + "/" + name + "¥",¥"mode¥": ¥"add¥",¥"autorename¥": true,¥"mute¥": false}")

header.store('Body', body)

res = SimpleHttp.new("https", "content.dropboxapi.com", 443).post("/2/files/upload", header)

yabmというディレクトリにmorimori.txtというファイルが出来ているはずです。

スクリーンショット(2019-01-08 18.51.36).png

OAuth2はOAuthのようにHASH関数が必要ないので良いです。

もしAccess Tokenが入ったモジュールを盗まれた場合には自分のDropboxにFull accessされる可能性があるので、「設定」の「リンク済みのアプリ」から削除するのが良いです。

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1