如何通过Amazon Cognito托管Web UI获取用户参数
Hey there, let's work through why you're stuck getting user info after switching to Cognito's hosted UI!
问题分析
The template you used before relied on the Cognito JS SDK's standard auth flow, where the SDK automatically manages user sessions in local storage—this is why userPool.getCurrentUser() worked smoothly. But when you switch to the hosted UI, you're using the OAuth implicit grant flow (since you set response_type=token), which returns tokens in the URL hash. The SDK doesn't automatically pick up these tokens as a valid user session, so getCurrentUser() can't find the user data you need.
解决方法
1. 直接解码id_token获取基础用户信息
Your id_token is a JWT that already contains core user attributes (like user ID sub, email, username, etc.). You can decode it easily with the jwt-decode library:
First install the dependency:
npm install jwt-decode
Then decode the token from the URL hash:
import jwtDecode from 'jwt-decode'; // Extract parameters from the URL hash const hashParams = new URLSearchParams(window.location.hash.slice(1)); const idToken = hashParams.get('id_token'); if (idToken) { // Decode the id_token to get user data const decodedUser = jwtDecode(idToken); console.log('Basic user info:', decodedUser); // You'll find fields like sub, email, name here (depending on your user pool settings) }
2. 手动初始化CognitoUser对象适配SDK流程
If you need to keep using Cognito SDK methods (like fetching full user attributes or refreshing sessions), you'll need to manually create a CognitoUser and session using the returned tokens:
import jwtDecode from 'jwt-decode'; import { CognitoUserPool, CognitoUser, CognitoUserSession, CognitoIdToken } from 'amazon-cognito-identity-js'; // Initialize your user pool const userPool = new CognitoUserPool({ UserPoolId: 'your-user-pool-id', ClientId: 'your-client-id' }); // Extract and decode the id_token from URL hash const hashParams = new URLSearchParams(window.location.hash.slice(1)); const idToken = hashParams.get('id_token'); if (idToken) { const decodedToken = jwtDecode(idToken); // Create a CognitoUser object const cognitoUser = new CognitoUser({ Username: decodedToken.sub, // Use sub as username, or decodedToken.username if that's your pool's setting Pool: userPool }); // Create a session object with the id_token const userSession = new CognitoUserSession({ IdToken: new CognitoIdToken({ IdToken: idToken }), // Add access_token and refresh_token here if your hosted UI returns them // AccessToken: new CognitoAccessToken({ AccessToken: hashParams.get('access_token') }), // RefreshToken: new CognitoRefreshToken({ RefreshToken: hashParams.get('refresh_token') }) }); // Attach the session to the CognitoUser cognitoUser.setSignInUserSession(userSession); // Now you can use SDK methods to fetch full user attributes cognitoUser.getUserAttributes((err, attributes) => { if (err) { console.error('Failed to get user attributes:', err); return; } console.log('Full user attributes:', attributes); // Iterate through attributes: attributes.forEach(attr => console.log(`${attr.Name}: ${attr.Value}`)) }); // Configure AWS credentials like you did before AWS.config.credentials = new AWS.CognitoIdentityCredentials({ IdentityPoolId: 'your-identity-pool-id', Logins: { `cognito-idp.your-region.amazonaws.com/your-user-pool-id`: idToken } }); }
3. 额外注意事项
- Make sure your hosted UI redirect URL is listed in your Cognito user pool client's "Allowed Callback URLs"—otherwise the auth flow will fail.
- Store the decoded token or session in
localStorage/sessionStorageso you can restore the user session after page refreshes, avoiding repeated trips to the hosted UI. - If you're using Angular, wrap this logic in an Auth service to keep it organized and accessible across components.
内容的提问来源于stack exchange,提问作者Vítor Resende

