在 aws-amplify v6 之前,我使用 federatedSignIn 让用户使用 google 登录网站。单击
sign in with google
按钮会调用 federatedSignIn 方法,该方法会将用户重定向到一个页面,用户可以在其中选择要使用哪个 Google 帐户登录。
迁移后,这种情况就不会发生。显示用户可以登录的所有帐户列表的谷歌页面没有出现。 (重定向到 account.google.com/o/oauth=?etc..etc.. 没有发生)按照官方 doc 的建议使用
await signInWithRedirect({ provider: 'Google' });
Amplify.configure({
Auth: {
Cognito: {
userPoolId: 'us-west-xxxxx',
userPoolClientId: 'xxxxxxx',
loginWith: {
oauth: {
domain: 'auth.abcdefgh.com',
redirectSignIn: ["http://localhost:3000/"],
redirectSignOut: ["http://localhost:3000/"],
responseType: 'code',
scope: ['email', 'openid']
}
}
}
}
});
const handleSocialSignIn = async () => {
await signInWithRedirect({
provider: 'Google'
});
}
我试过这个。但不起作用。 https://docs.amplify.aws/react/build-a-backend/auth/advanced-workflows/#identity-pool-federation
你需要像这样使用 hub.listen
import React, { useEffect, useState } from "react";
import { Hub } from "aws-amplify/utils";
import { signInWithRedirect, signOut, getCurrentUser } from "aws-amplify/auth";
function App() {
const [user, setUser] = useState(null);
const [error, setError] = useState(null);
const [customState, setCustomState] = useState(null);
useEffect(() => {
const unsubscribe = Hub.listen("auth", ({ payload }) => {
switch (payload.event) {
case "signInWithRedirect":
getUser();
break;
case "signInWithRedirect_failure":
setError("An error has ocurred during the OAuth flow.");
break;
case "customOAuthState":
setCustomState(payload.data); // this is the customState provided on signInWithRedirect function
break;
}
});
getUser();
return unsubscribe;
}, []);
const getUser = async () => {
try {
const currentUser = await getCurrentUser();
setUser(currentUser);
} catch (error) {
console.error(error);
console.log("Not signed in");
}
};
return (
<div className="App">
<button onClick={() => signInWithRedirect({ customState: "shopping-cart"})}>Open Hosted UI</button>
<button onClick={() => signInWithRedirect({ provider: "Facebook", customState: "shopping-cart" })}>
Open Facebook
</button>
<button onClick={() => signInWithRedirect({ provider: "Google", customState: "shopping-cart" })}>
Open Google
</button>
<button onClick={() => signInWithRedirect({ provider: "Amazon", customState: "shopping-cart" })}>
Open Amazon
</button>
<button onClick={() => signInWithRedirect({ provider: "Apple", customState: "shopping-cart" })}>
Open Apple
</button>
<button onClick={() => signOut()}>Sign Out</button>
<div>{user?.username}</div>
<div>{customState}</div>
</div>
);
}