Files
cpp-httplib/docs-src/pages/ja/cookbook/c06-bearer-token.md
yhirose 0fa4912891 Fix broken relative links in cookbook docs (Fix #2490)
Cookbook body links referenced sibling pages with a bare slug
(e.g. `c14-keep-alive`). Under the pretty-URL layout each page lives
in its own directory, so these resolve against the page's own
directory and 404. Prefix them with `../` to match the convention
already used in the tour and llm-app sections.

Verified clean with `docs-gen check`.
2026-07-08 22:45:29 -04:00

1.9 KiB

title, order, status
title order status
C06. BearerトークンでAPIを呼ぶ 6 draft

OAuth 2.0やモダンなWeb APIでよく使われるBearerトークン認証には、set_bearer_token_auth()を使います。トークンを渡すと、cpp-httplibがAuthorization: Bearer <token>ヘッダーを自動で組み立ててくれます。

基本の使い方

httplib::Client cli("https://api.example.com");
cli.set_bearer_token_auth("eyJhbGciOiJIUzI1NiIs...");

auto res = cli.Get("/me");
if (res && res->status == 200) {
  std::cout << res->body << std::endl;
}

一度設定すれば、以降のリクエストすべてにトークンが付きます。GitHub APIやSlack API、自前のOAuthサービスなど、トークンベースのAPIを叩くときの定番です。

リクエスト単位で使う

特定のリクエストだけにトークンを付けたい、あるいはリクエストごとに違うトークンを使いたいときは、Headersで直接渡せます。

httplib::Headers headers = {
  httplib::make_bearer_token_authentication_header(token),
};
auto res = cli.Get("/me", headers);

make_bearer_token_authentication_header()Authorizationヘッダーを組み立ててくれます。

トークンをリフレッシュする

トークンの有効期限が切れたら、新しいトークンでset_bearer_token_auth()を呼び直すだけで更新できます。

if (res && res->status == 401) {
  auto new_token = refresh_token();
  cli.set_bearer_token_auth(new_token);
  res = cli.Get("/me");
}

Warning: Bearerトークンはそれ自体が認証情報です。必ずHTTPS経由で送ってください。また、ソースコードや設定ファイルにトークンをハードコードしないようにしましょう。

複数のヘッダーをまとめて設定したいときはC03. デフォルトヘッダーを設定するも便利です。