この用語をシェア
OAuthとは
OAuth(Open Authorization)は、第三者アプリケーションが安全にユーザーデータにアクセスできるよう設計された認証・認可のためのオープンスタンダードです。パスワードを直接共有することなく、限定的なアクセス権限を付与することで、セキュアなAPIアクセスを実現します。
OAuthの主要な特徴
- 認可フレームワーク:認証ではなく認可に焦点を当てた設計
- パスワードレス:パスワードを第三者に提供する必要がない
- 限定的なアクセス:必要最小限の権限のみを付与
- 一時的なアクセス:トークンの有効期限による時間制限
- 取り消し可能:いつでもアクセス権限を取り消し可能
OAuthの基本概念
登場人物(Role)
Role | 役割 | 例 |
---|---|---|
Resource Owner | リソースの所有者 | ユーザー |
Resource Server | 保護されたリソースを提供するサーバー | Google Drive API |
Client | リソースにアクセスしたいアプリケーション | 写真管理アプリ |
Authorization Server | 認可を行うサーバー | Google OAuth Server |
トークンの種類
- Authorization Code:認可コード(一時的)
- Access Token:アクセストークン(リソースアクセス用)
- Refresh Token:リフレッシュトークン(Access Token更新用)
OAuthの認可フロー
Authorization Code Flow(推奨)
- 認可リクエスト:Client が User を Authorization Server にリダイレクト
- ユーザー認証:User が Authorization Server でログイン
- 認可コード発行:User が許可すると Authorization Code を発行
- 認可コード受け取り:Client が Authorization Code を受け取る
- アクセストークン要求:Client が Authorization Code と Client Secret を使ってアクセストークンを要求
- アクセストークン発行:Authorization Server がアクセストークンを発行
- リソースアクセス:Client がアクセストークンを使ってリソースにアクセス
認可リクエストの例
https://accounts.google.com/oauth/authorize?
response_type=code&
client_id=YOUR_CLIENT_ID&
redirect_uri=https://yourapp.com/callback&
scope=https://www.googleapis.com/auth/drive.readonly&
state=random_state_string
アクセストークン要求の例
POST /oauth/token HTTP/1.1
Host: accounts.google.com
Content-Type: application/x-www-form-urlencoded
grant_type=authorization_code&
code=AUTHORIZATION_CODE&
redirect_uri=https://yourapp.com/callback&
client_id=YOUR_CLIENT_ID&
client_secret=YOUR_CLIENT_SECRET
OAuthの Grant Types
Authorization Code Grant
- 用途:Webアプリケーション
- 特徴:最も安全、Client Secret を使用
- フロー:ブラウザ経由で認可コードを取得
Implicit Grant
- 用途:シングルページアプリケーション(非推奨)
- 特徴:Client Secret なし、直接 Access Token を発行
- セキュリティ:現在は PKCE を使用した Authorization Code Grant が推奨
Resource Owner Password Credentials Grant
- 用途:信頼できるアプリケーション
- 特徴:ユーザー名とパスワードを直接使用
- 注意:パスワードがアプリケーションに露出
Client Credentials Grant
- 用途:サーバー間通信
- 特徴:ユーザー認証なし、アプリケーション認証のみ
- 適用:バックエンドサービス間のAPI通信
PKCE(Proof Key for Code Exchange)
PKCEは、公開クライアント(モバイルアプリやSPA)でのセキュリティを強化するためのOAuth拡張です。
PKCEの流れ
- Code Verifier生成:ランダムな文字列を生成
- Code Challenge生成:Code Verifierのハッシュ値を生成
- 認可リクエスト:Code Challengeを含める
- トークン要求:Code Verifierを含める
- 検証:Authorization Serverが検証
PKCEの実装例
// Code Verifier 生成
const codeVerifier = generateRandomString(128);
// Code Challenge 生成
const codeChallenge = base64URLEncode(sha256(codeVerifier));
// 認可リクエスト
const authUrl = `https://accounts.google.com/oauth/authorize?
response_type=code&
client_id=${CLIENT_ID}&
redirect_uri=${REDIRECT_URI}&
scope=${SCOPE}&
state=${STATE}&
code_challenge=${codeChallenge}&
code_challenge_method=S256`;
// トークン要求
const tokenRequest = {
grant_type: 'authorization_code',
code: authorizationCode,
redirect_uri: REDIRECT_URI,
client_id: CLIENT_ID,
code_verifier: codeVerifier
};
OAuth 2.0の実装例
Node.js(Express)
const express = require('express');
const axios = require('axios');
const app = express();
// 認可URL生成
app.get('/auth', (req, res) => {
const authUrl = `https://accounts.google.com/oauth/authorize?` +
`response_type=code&` +
`client_id=${process.env.GOOGLE_CLIENT_ID}&` +
`redirect_uri=${process.env.REDIRECT_URI}&` +
`scope=https://www.googleapis.com/auth/userinfo.profile&` +
`state=${generateState()}`;
res.redirect(authUrl);
});
// コールバック処理
app.get('/callback', async (req, res) => {
const { code, state } = req.query;
try {
// アクセストークン取得
const tokenResponse = await axios.post('https://oauth2.googleapis.com/token', {
grant_type: 'authorization_code',
code: code,
redirect_uri: process.env.REDIRECT_URI,
client_id: process.env.GOOGLE_CLIENT_ID,
client_secret: process.env.GOOGLE_CLIENT_SECRET
});
const accessToken = tokenResponse.data.access_token;
// ユーザー情報取得
const userResponse = await axios.get('https://www.googleapis.com/oauth2/v2/userinfo', {
headers: {
Authorization: `Bearer ${accessToken}`
}
});
res.json(userResponse.data);
} catch (error) {
res.status(500).json({ error: 'Authentication failed' });
}
});
JavaScript(Frontend)
// OAuth認証開始
function startOAuth() {
const clientId = 'YOUR_CLIENT_ID';
const redirectUri = 'https://yourapp.com/callback';
const scope = 'https://www.googleapis.com/auth/userinfo.profile';
const state = generateRandomString();
const authUrl = `https://accounts.google.com/oauth/authorize?` +
`response_type=code&` +
`client_id=${clientId}&` +
`redirect_uri=${encodeURIComponent(redirectUri)}&` +
`scope=${encodeURIComponent(scope)}&` +
`state=${state}`;
// 状態をセッションストレージに保存
sessionStorage.setItem('oauth_state', state);
// 認可サーバーにリダイレクト
window.location.href = authUrl;
}
// コールバック処理
function handleCallback() {
const urlParams = new URLSearchParams(window.location.search);
const code = urlParams.get('code');
const state = urlParams.get('state');
const storedState = sessionStorage.getItem('oauth_state');
if (state !== storedState) {
console.error('State mismatch');
return;
}
// バックエンドにコードを送信してトークンを取得
fetch('/api/oauth/token', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ code: code })
})
.then(response => response.json())
.then(data => {
console.log('Access token:', data.access_token);
// アクセストークンを使ってAPIにアクセス
});
}
OAuth 2.0のセキュリティ
ベストプラクティス
- HTTPS必須:すべての通信でHTTPSを使用
- State パラメータ:CSRF攻撃を防ぐためのランダムな値
- 短期間のトークン:アクセストークンの有効期限を短く設定
- スコープ制限:必要最小限の権限のみを要求
- リダイレクトURI検証:事前に登録されたURIのみを許可
セキュリティ脅威と対策
脅威 | 対策 |
---|---|
CSRF攻撃 | Stateパラメータの使用 |
認可コード傍受 | PKCEの使用 |
リプレイ攻撃 | 認可コードの一回限りの使用 |
トークンリーク | 短期間の有効期限とHTTPS |
OAuth 2.0 vs OAuth 1.0
特徴 | OAuth 1.0 | OAuth 2.0 |
---|---|---|
複雑さ | 高い | 低い |
署名 | 必須 | 不要(HTTPS前提) |
暗号化 | アプリケーション層 | トランスポート層(HTTPS) |
柔軟性 | 低い | 高い |
モバイル対応 | 困難 | 容易 |
OpenID Connect
OpenID Connect(OIDC)は、OAuth 2.0の上に構築された認証層です。OAuth 2.0が認可に焦点を当てているのに対し、OIDCは認証情報も提供します。
OpenID Connectの追加要素
- ID Token:JWT形式のユーザー情報
- UserInfo Endpoint:ユーザー情報取得用エンドポイント
- 標準化されたスコープ:openid, profile, email等
OAuth 2.0の活用例
- SNSログイン:Google、Facebook、Twitter等でのログイン
- API連携:第三者アプリケーションからのAPI利用
- シングルサインオン:複数アプリケーション間でのSSO
- マイクロサービス:サービス間でのアクセス制御
OAuth 2.0プロバイダー
- Google:Google OAuth 2.0
- Microsoft:Microsoft Identity Platform
- Amazon:Amazon Cognito
- Facebook:Facebook Login
- GitHub:GitHub OAuth
関連技術
- JWT:JSON Web Token
- OpenID Connect:OAuth 2.0ベースの認証
- SAML:Security Assertion Markup Language
- WebAuthn:Web Authentication API