先日書いた「Google::API::Clientを使う(perl)」の続きです。前回示したコードでは毎回認証してアクセスコードを入力しなければいけないので、それを回避するためにjsonで保存するためのコード例を示してみます。
トークンの保存
# $authには既に認証済みのGoogle::API::OAuth2::Clientであるとする
my ($file, $jsonstr);
open($file, "> token.json");
print $file, $auth->{"json_parser"}->encode($auth->token_obj);
トークンの読み込み
my $auth = Google::API::OAuth2::Client->new({
auth_uri => "https://accounts.google.com/o/oauth2/auth",
token_uri => "https://accounts.google.com/o/oauth2/token",
client_id => "your-id",
client_secret => "your-secrets",
redirect_uri => "urn:ietf:wg:oauth:2.0:oob",
auth_doc => {
oauth2 => {
scopes => {
"https://www.googleapis.com/auth/gmail.readonly"
=> "gmail read"
}
}
});
my ($file, $jsonstr);
open($file, "< token.json");
$jsonstr = "";
while (<$file>) {
$jsonstr .= $_;
}
close($f);
$auth->token_obj($auth->{"json_parser"}->decode($jsonstr));
Data::SerializerでGoogle::API::OAuth2::Clientを丸ごとシリアライズしてみる、ということもやってみたのですが、不完全のようでシリアライズ時に警告が出たり、デシリアライズしたオブジェクトを使った際、最後にsegfaultを起こしたりします。
あとは、new_from_client_secretsというメソッドでjsonファイル上に記録されたauth_uri, token_uri, client_id, client_secretを読み込んで新しいオブジェクトを作成するものも用意されていますが、token_objについては考慮されていません。ファイル外部にclient_id等を記録しておける点が良い、ぐらいのものです。
もうちょっと永続化に関する手続きも簡略化されているとうれしいところです。