cognitoでクエリパラメータ引継ぎ - kocya-dev/note GitHub Wiki
仕組み
- 認証開始時に/oauth2/authorizeエンドポイントにstateパラメータとして、元のクエリパラメータ(redirect_page=test_viewなど)を含めて送信
- Cognitoのhosted UIでの認証フロー全体を通して、このstateパラメータが保持される
- 認証完了後のコールバック時に、同じstateパラメータが返される
実装例
// 1. 元のクエリパラメータを取得
const urlParams = new URLSearchParams(window.location.search);
const redirectPage = urlParams.get('redirect_page');
// 2. stateパラメータとしてエンコード(JSON形式の場合はbase64エンコードが推奨)
const state = redirectPage ? btoa(JSON.stringify({redirect_page: redirectPage})) : 'default_state';
// 3. Cognitoのauthorizeエンドポイントに送信
const cognitoUrl = `https://your-domain.auth.region.amazoncognito.com/oauth2/authorize?` +
`response_type=code&` +
`client_id=your_client_id&` +
`redirect_uri=https://your-app.com/callback&` +
`state=${encodeURIComponent(state)}&` +
`scope=openid`;
window.location.href = cognitoUrl;
// 4. コールバック処理で state を復元
const urlParams = new URLSearchParams(window.location.search);
const returnedState = urlParams.get('state');
if (returnedState) {
try {
const decodedState = JSON.parse(atob(returnedState));
const redirectPage = decodedState.redirect_page;
// 5. 元のクエリパラメータに基づいて適切な画面に遷移
if (redirectPage === 'test_view') {
window.location.href = '/test_view';
}
} catch (error) {
console.error('State parameter parsing failed:', error);
}
}
重要な注意点
- URL-encoded JSON形式の制限: AWS Cognitoのドキュメントによると、stateパラメータにURL-encoded JSON文字列は直接設定できません。JSON形式のデータを渡す場合は、base64エンコードしてから設定し、アプリケーション側でデコードする必要があります。
- CSRF対策: stateパラメータは本来CSRF攻撃を防ぐためのものでもあるため、セキュリティを考慮して適切なランダム値も含めることを推奨します。
- ログアウト時も同様: /logoutエンドポイントでも同様にstateパラメータを使用可能です。
この方法により、Cognitoのhosted UIを経由しても、元のクエリパラメータ情報を保持して適切な画面に遷移させることができます。
本来の使い方
The state query parameter in Amazon Cognito Hosted UI is an optional but highly recommended parameter used in OAuth 2.0 authorization flows, particularly for preventing Cross-Site Request Forgery (CSRF) attacks. Purpose of the state parameter:
CSRF Protection:
When your application initiates an authentication request to the Cognito Hosted UI, you can include a randomly generated state value. After successful authentication, Cognito redirects the user back to your redirect_uri and includes the same state value in the query parameters. Your application should then verify that the state value returned by Cognito matches the one it originally sent. This ensures that the authentication response truly belongs to a request initiated by your application and not a malicious third party.
Maintaining Application State:
The state parameter can also be used to carry information about the user's original request or the application's state before the authentication flow began. For example, you could encode the intended destination URL or other relevant data within the state parameter, allowing your application to redirect the user to the correct page after authentication.
How to use the state parameter:
Generate a random state value: Before redirecting the user to the Cognito Hosted UI login page, generate a unique, unguessable random string.
Include in the authorization request:
Append the state parameter to the URL for the Cognito Hosted UI's /oauth2/authorize endpoint. For example:
https://your-user-pool-domain.auth.region.amazoncognito.com/oauth2/authorize?response_type=code&client_id=YOUR_CLIENT_ID&redirect_uri=YOUR_REDIRECT_URI&state=YOUR_RANDOM_STATE_VALUE
Store the state value:
Securely store the generated state value in your application's session or a temporary location, associated with the user's current session. Verify the returned state: When Cognito redirects the user back to your redirect_uri, retrieve the state parameter from the incoming request. Compare this value with the stored state value. If they do not match, reject the authentication response as it may be a CSRF attack.