OllamaのAPIに認証をつけよう【Ollama】【Express】
Ollama のAPIには認証機能がなく、実装の予定もありません。これは、Ollama はモデルの提供に集中するべきという設計思想から来ており、認証 (認可) はスコープ外となっているからです。OllamaのAPIを安全に公開するには、サービスプロバイダーが適切な認証 (認可) システムを使用する必要があります。本記事では Express を使用した簡単な認証 (認可) システムを実装します。
対象の読者
- Ollama API を安全に公開したい人
- TypeScript/JavaScriptによるプログラミングの経験がある人
前提条件
- Ollama (LLMランタイム)
- Deno (JavaScriptランタイム)
- おそらくNode.jsでも動作しますが、ライブラリのimportを変える必要があると思います。
- Express 5 (JavaScript ウェブフレームワーク)
APIゲートウェイ
実装する (TypeScript+Express)
Ollamaの代わりに外部からのリクエストを受け付け、APIキーの利用可否を判定した後にOllamaにリクエストを行うAPIゲートウェイを実装します。
api-gateway.ts:
import express from 'npm:express';
import axios from 'npm:axios';
import cors from 'npm:cors';
const app = express();
const PORT = 3000; // APIゲートウェイが外部からの接続を待ち受けるポート (本番では環境変数などに保存)
const UPSTREAM = 'http://localhost:11434' // Ollama APIをホストしているURL (本番では環境変数などに保存)
// API キーの例 (本番では環境変数などに保存)
const API_KEYS = {
'your-secret-key': true,
};
app.use(express.json());
// ミドルウェアで API キーを検証
app.use((req, res, next) => {
const apiKey = req.headers['x-api-key'];
if (!apiKey || !API_KEYS[apiKey]) {
return res.status(401).json({ error: 'Invalid API key' });
}
next();
});
// Ollama API にリクエストを転送
app.use('/api', async (req, res) => {
const endpoint = `${UPSTREAM}${req.originalUrl}`;
const options = {
method: req.method,
url: endpoint,
data: req.body,
responseType: 'stream',
timeout: 30000,
};
try {
console.log('REQUESTING:', options);
const response = await axios(options);
console.log('RESPONSE');
response.data.pipe(res);
} catch (error) {
console.error('ERROR: ', error);
res.status(error.response?.status || 500).json({
error: error.message,
details: error.response?.data,
});
}
});
// CORS 設定
app.use(cors());
app.listen(PORT, () => {
console.log(`API Gateway is running on http://localhost:${PORT}`);
});
- PORT: APIゲートウェイが外部からの接続を待ち受けるポートを設定します。
- UPSTREAM: Ollama APIをホストしているURLを設定します。
- API_KEY: 有効なAPIキーの値を
trueにします。
起動する
deno run --allow-env --allow-net api-gateway.ts # API Gateway is running on port 3000
Ollamaを起動する
ollama serve コマンドでOllamaを起動することができます:
ollama serve # 127.0.0.1:11434 でリクエストを待ち受ける
API呼び出しをテストする
curlコマンドでAPI呼び出しをテストできます:
curl -XPOST localhost:3000/api/chat \
-H 'x-api-key: your-secret-key' \
--json '{
"model": "qwen3:30b",
"messages": [
{
"role": "user",
"content": "なぜ空は青いのですか?"
}
],
"stream": false
}'
# {"model":"qwen3:30b","created_at":"2025-12-02T03:28:01.993953105Z","message":{"role":"assistant","content":"\u003cthink\u003e\nOkay, the user is asking why the sky is blue. I need to explain this in a clear and simple way. Let me start by recalling what I know about light and the atmosphere.\n\nFirst, sunlight is white, but it's made up of different colors. Each color has a different wavelength. Blue light has a shorter wavelength compared to red or yellow. When sunlight enters the Earth's atmosphere, it collides with molecules and tiny particles in the air. This is called Rayleigh scattering. \n\nShorter wavelengths (blue and violet) scatter more than longer ones (red, orange). But wait, why isn't the sky violet then? Maybe because our eyes are more sensitive to blue, and the sun emits more blue light than violet. Also, the atmosphere scatters the blue light in all directions, so when we look up, we see that scattered blue light coming from all around. \n\nI should also mention that during sunrise or sunset, the sky turns red or orange because the light has to pass through more atmosphere, scattering the blue light away and leaving the longer wavelengths. \n\nWait, I need to make sure I'm not mixing up any details. Let me check: Rayleigh scattering is the main reason, and it's more effective for shorter wavelengths. So blue is scattered more, but our eyes perceive it as blue. Also, the sun's spectrum has more blue than violet. \n\nI should structure the answer step by step: start with sunlight composition, then explain scattering, mention the wavelength difference, why blue is dominant, and maybe the sunset effect as a bonus. Keep it conversational and avoid jargon. Let me put that together.\n\u003c/think\u003e\n\n空が青く見える理由は、**光の散乱**(レイリー散乱)と**人間の目への反応**によって説明されます。以下に段階的に解説します。\n\n---\n\n### 1. **太陽光の性質**\n太陽から出る光(可視光線
は、**白い光**に見えますが、実は**さまざまな波長の光の混合**です。この中には、**青(短波長)**、**緑**、**黄**、**赤(長波長)**などがあります。\n\n---\n\n### 2. **大気中の分子との衝突**\n太陽光が地球の大気に入る
、**空気中の分子(主に窒素や酸素)や微細な粒子**と衝突します。この衝突によって光が**散乱**されます。\n\n- **短波長の光(青・紫)**は、**長波長の光(赤・オレンジ)**よりも**強く散乱**されます。 \n これは、**レイ
ー散乱**と呼ばれる現象で、波長の**4乗に反比例**して散乱の強さが増します。\n\n---\n\n### 3. **なぜ青に見えるのか?**\n- 空気中で散乱された**青い光**が、空全体に広がって目に届きます。 \n- 一方で、**紫の光**も強く
乱されるにもかかわらず、**人間の目は紫に敏感ではなく**、**青に強く反応**します。 \n また、太陽光のスペクトル(波長分布)は**青よりも赤に寄っている**ため、青がより目立ちます。\n\n---\n\n### 4. **夕方の空が赤く見
る理由**\n- 夕方や朝は、太陽が地平線近くにあるため、光が大気を**長く通過**します。 \n- このとき、**青い光**は途中で散乱され、**赤やオレンジの光**だけが残って地面に届きます。 \n これが**夕焼け**や**朝焼け**の赤
光の原因です。\n\n---\n\n### まとめ\n空が青いのは、**太陽光の中の青い光が大気中で強く散乱され、人間の目に届くため**です。この現象は、科学の「レイリー散乱」と関係しています。"},"done_reason":"stop","done":true,"total_duration":12057484602,"load_duration":28850643,"prompt_eval_count":16,"prompt_eval_duration":6419210,"eval_count":883,"eval_duration":12021444649}
本番で使用する前に
本番で使用する前に次の事項について検討してください。
- TLS (HTTPS) による暗号化を行う
- 本記事では触れませんでしたが、暗号化を行わないとAPIキーやプロンプト、推論結果を通信経路上で容易に盗み見ることができてしまいます。
- APIキーを動的に発行・無効化する
- 本記事のコードではAPIキーがハードコードされており、人の手で管理する必要があります。実際には利用者がウェブで申請を行なった時に自動でAPIキーを発行したり、過剰に推論を行うユーザーのAPIキーを無効化するなどの実装が必要でしょう。
終わりに
本記事ではExpressでAPIゲートウェイを実装し、Ollamaを公開する例を示しました。実際の環境でOllamaを公開するにあたっては、前セクションで述べた事項について検討してください。また、本記事の内容はOllama以外のサービスを安全に公開する際にも応用できますので、ぜひお試しください。
