C 言語にて libcurl と libmicrohttpd を使って Gmail + OAuth で メールを送信する

C 言語にて libcurl を使って Gmail + OAuth で メールを送信する の続きです。

libcurl

libcurl は様々な通信プロトコルに対応している C ライブラリです。
メール関連では、smtp, pop3, imap に対応している。

libcurl

Mac の場合は、brewコマンドでインストールできる。

homebrew curl

libmicrohttpd

ibmicrohttpd は HTTP/1.1 サーバ の C ライブラリです。

gnu libmicrohttpd

Mac の場合は、brewコマンドでインストールできる。

homebrew libmicrohttpd

OAuth 認証

Google: OAuth 2.0 を使用した Google API へのアクセス

[POP・IMAPはもう使えない!法人向けメールシステムのOAuth対応について](https://togeonet.co.jp/post-26528

OAUTH 認証の仕様変更

2022年 10月 より
Gmail および Google のサービスにおいて OAUTH 認証にて WEBブラウザをリダイレクト先とする帯域外(OOB)フローが廃止になった。

google: (OOB) フロー移行ガイド (https://developers.google.com/identity/protocols/oauth2/resources/oob-migration)

Google: モバイル &デスクトップ アプリ向け OAuth 2.0

この記事では、これに対応する。

デスクトップアプリでは、リダイレクト先に、 localhost サーバー (ループバック IP アドレス(127.0.0.1)を指定できる。

この実装では、認証コードを受信するために、
ローカルのウェブサーバーを建ててポートリッスンする必要がある。

この記事では、C 言語で構築できるウェブサーバーとしてlibmicrohttpd を採用した。

libmicrohttpdのチュートリアルとサンプルコードを下記に示す。

A tutorial for GNU libmicrohttpd

github: libmicrohttpd examples

最初に ウェブブラウザで認証コードを要求する。 下記のようなURLにアクセする。

https://accounts.google.com/o/oauth2/v2/auth?
 scope=&
 response_type=code&
 state=security_token%3D138r5719ru3e1%26url%3Dhttps%3A%2F%2Foauth2.example.com%2Ftoken&
 redirect_uri=127.0.0.1:3000&
 client_id=client_id

ユーザが承認すると、ウェブサーバーに認証コードが送信される。

ウェブサーバーが受信する認証コードは下記のような形式です。 GET リクエスト行に、クエリストリングとして記述される。

GET /?code=4/xxxxx&scope=xxxxx HTTP/1.1
Host: 127.0.0.1:3000
Connection: keep-alive

認証コードを受信するソースコードは下記のようになる。

int ahc_echo (
struct MHD_Connection *connection, ..... )
{
    char *code;
    code = MHD_lookup_connection_value(connection, MHD_GET_ARGUMENT_KIND,  "code");
}

gnu: libmicrohttpd Handling requests

受信した認証コードを更新トークン (refresh token) と交換する。

この処理 (プログラム) は従来と同じです。

Google サーバーに対して、下記のようなリクエストを送信する。 従来と同じように、libcurl を使って実装する。

POST /token HTTP/1.1
Host: oauth2.googleapis.com
Content-Type: application/x-www-form-urlencoded

code=4/P7q7W91a-oMsCeLvIaQm6bTrgtp7&
client_id=your_client_id&
client_secret=your_client_secret&
redirect_uri=http://127.0.0.1:9004&
grant_type=authorization_code

Github にサンプルコードを公開した。 https://github.com/ohwada/MAC_cpp_Samples/tree/master/libcurl/mail/xoauth2

Gmail API の仕様変更

2021年7月より
Gmail APIGoogle Enterprise API編入された。

codezine: Google、厳格な原則のもとで提供される「Google Enterprise API」を導入

.infoq: GoogleがEnterprise APIを発表