javascriptでOauth認証してTwitterAPIを利用する。(署名作成編)
ハッカソンでtwitter apiを利用する機会があったのでまとめてみした。
OAuth
OAuthとは権限認証を行うための規約のようなもの。
詳しくは
https://ja.wikipedia.org/wiki/OAuth
署名の作成
署名とはurlとパラメーターを暗号化したものです。
送られてきた署名をapi側で照合することによって第三者による不正なリクエストを防いでいます。
手順としては
- キーを作成
- データの作成
- キーとデータを署名に変更
という順序で実装していきます。
1 キーの作成。
キーは単純にaccess_token_secretとconsumer_secretをurlエンコードして"&"で結合したものです。
signature.js
const access_token_secret = ""; //まだないので空でOK
const consumer_secret = "your_consumer_secret";
const signature_key = encodeURIComponent(consumer_secret) + "&" + encodeURIComponent(access_token_secret);
2 データの作成
apiに送るデータを作成していきます。
各種URLエンコードしたメソッド、パラメータ、リクエストURLを"&"で繋げたものを作成します。
signature.js
const access_token_secret = ""; //まだないので空でOK
const consumer_secret = "your_consumer_secret";
const signature_key = encodeURIComponent(consumer_secret) + "&" + encodeURIComponent(access_token_secret);
//ここまでがキーの作成
const request_method = "GET";
const request_url = "https://api.twitter.com/oauth/request_token"
const params = {
"name": "sample",
"text": "sample",
}
const params_to_query = (params) => {
return Object.keys(params).sort().map(key => {
return encodeURIComponent(key) + "=" + encodeURIComponent(params[key]);
}).join(",");
}
const signature_data = encodeURIComponent(request_method + "&" + encodeURIComponent(request_url) + "&" + params_to_query;
署名に変換
まずHMAC-SHA1方式のハッシュ値に変換し、
そのハッシュ値をbase64エンコードして署名の完成です。
crypto-jsを使って変換していきます。
signature.js
import HmacSHA1 from 'crypto-js/hmac-sha1';
import Base64 from 'crypto-js/enc-base64';
const access_token_secret = ""; //まだないので空でOK
const consumer_secret = "your_consumer_secret";
const signature_key = encodeURIComponent(consumer_secret) + "&" + encodeURIComponent(access_token_secret);
//ここまでがキーの作成
const request_method = "GET";
const request_url = "https://api.twitter.com/oauth/request_token"
const params = {
"name": "sample",
"text": "sample",
}
const params_to_query = (params) => {
return Object.keys(params).sort().map(key => {
return encodeURIComponent(key) + "=" + encodeURIComponent(params[key]);
}).join(",");
}
const signature_data = encodeURIComponent(request_method) + "&" + encodeURIComponent(request_url) + "&" + params_to_query;
//ここまでがデータの作成
const hash = HmacSHA1(signature_data, signature_key);
const signature = Base64.stringify(hash);
このsignatureという定数が署名です。
今回は一旦ここで区切ります。