基于AWS Gateway和Lambda的Web应用,如何无跳转获取FB Access Token实现Cognito脸书登录?
Great news for your serverless setup—you absolutely can retrieve a Facebook Access Token directly in your JavaScript code (no redirects or page reloads required) using the Facebook JavaScript SDK. This fits perfectly with your AWS API Gateway/Lambda/Cognito stack, since you don’t need a traditional backend to handle the OAuth flow.
Here’s a step-by-step breakdown to implement this:
1. Load the Facebook JavaScript SDK Asynchronously
First, add the SDK loader to your frontend code. Load it asynchronously so it doesn’t block your page from rendering:
window.fbAsyncInit = function() { FB.init({ appId : 'YOUR_FACEBOOK_APP_ID', // Replace with your actual Facebook app ID cookie : true, // Enable cookies to let Cognito access the session if needed xfbml : true, // Parse any Facebook social plugins on your page version : 'v18.0' // Use the latest stable SDK version (check Facebook docs for updates) }); }; // Async loader to avoid blocking page load (function(d, s, id){ var js, fjs = d.getElementsByTagName(s)[0]; if (d.getElementById(id)) {return;} js = d.createElement(s); js.id = id; js.src = "https://connect.facebook.net/en_US/sdk.js"; fjs.parentNode.insertBefore(js, fjs); }(document, 'script', 'facebook-jssdk'));
2. Implement a Popup-Based Login Flow
Use FB.login() to trigger a Facebook login popup (this won’t redirect or refresh your main page). When the user completes authorization, you’ll get the access token directly in the callback:
// Attach this function to your "Login with Facebook" button click event async function handleFacebookLogin() { FB.login(function(response) { if (response.authResponse) { // Success! Grab the access token here const facebookAccessToken = response.authResponse.accessToken; const tokenExpiry = response.authResponse.expiresIn; // Token lifespan in seconds // Now pass this token to AWS Cognito to authenticate the user authenticateWithCognito(facebookAccessToken); } else { console.log('User cancelled login or denied authorization.'); } }, { scope: 'public_profile,email' }); // Request only the permissions you need }
3. Integrate the Facebook Token with AWS Cognito
Once you have the Facebook Access Token, you can pass it to AWS Cognito to get Cognito’s JWT tokens (which you’ll use to call your Lambda/API Gateway endpoints):
async function authenticateWithCognito(facebookToken) { const cognitoClient = new AWS.CognitoIdentityServiceProvider(); const authParams = { AuthFlow: 'ACCESS_TOKEN_AUTH', ClientId: 'YOUR_COGNITO_APP_CLIENT_ID', // Replace with your Cognito app client ID AuthParameters: { 'FACEBOOK_ACCESS_TOKEN': facebookToken } }; try { const authResult = await cognitoClient.initiateAuth(authParams).promise(); // Extract Cognito tokens to use for your API requests const cognitoIdToken = authResult.AuthenticationResult.IdToken; const cognitoAccessToken = authResult.AuthenticationResult.AccessToken; // Store these tokens (e.g., in localStorage) for future API calls localStorage.setItem('cognitoIdToken', cognitoIdToken); } catch (error) { console.error('Cognito authentication failed:', error); } }
Key Things to Remember
- Facebook App Setup: Make sure your Facebook app’s OAuth settings include your frontend domain in the Valid OAuth Redirect URIs (even for popup flows, Facebook requires this for security).
- Permission Scopes: Only request the Facebook permissions your app actually needs (e.g.,
emailif you need the user’s email for Cognito user profiles). - Token Expiry: Facebook Access Tokens have a limited lifespan—check the
expiresInvalue in the auth response and handle token refreshes if your app needs long-lived sessions.
This approach keeps everything client-side, which aligns perfectly with your serverless architecture—no need for a backend server to handle redirects or token exchanges.
内容的提问来源于stack exchange,提问作者dmi88

