我对 Auth0 有疑问。登录。和注销。使用反应打字稿。
这里位于 Index.tsx 中。
root.render(
<Auth0Provider
domain="somecode.us.auth0.com"
clientId="somecode"
authorizationParams={{
redirect_uri: window.location.origin
}}
>
<React.StrictMode>
<Provider store={store}>
<CssBaseline />
<App />
</Provider>
</React.StrictMode>
</Auth0Provider>
);
身份验证配置中给出了一些代码。
现在我有一个登录或注销按钮。
const AuthButton = () => {
const { isAuthenticated, loginWithRedirect, logout } = useAuth0();
const handleLogin = () => {
loginWithRedirect();
};
const handleLogout = () => {
logout({ logoutParams: { returnTo: window.location.origin } });
};
return (
<button
style={{
color: 'white',
backgroundColor: '#142952',
marginRight: '4rem',
fontFamily: 'Consolas',
border: 'none',
borderRadius: '3px',
width: '110px',
height: '40px'
}}
onClick={isAuthenticated ? handleLogout : handleLogin}
>
{isAuthenticated ? 'Logout' : 'Login'}
</button>
);
};
export default AuthButton;
还有。我检索用户信息以显示。
const Profile = () => {
const { user, isAuthenticated, getAccessTokenSilently } = useAuth0();
const [accessToken, setAccessToken] = useState('');
useEffect(() => {
const getAccessToken = async () => {
try {
const token = await getAccessTokenSilently();
setAccessToken(token);
} catch (error) {
console.error(error);
}
};
if (isAuthenticated) {
getAccessToken();
console.log("authenticated")
}
}, [isAuthenticated, getAccessTokenSilently]);
if (!isAuthenticated) {
return <div>Please login to view your profile.</div>;
}
return (
<div>
{user?.picture && (
<img src={user.picture} alt="Profile Picture" />
)}
<h2>Hello {user?.name}</h2>
<p>Email: {user?.email}</p>
<p>Login Method: {user?.sub?.split('|')[0]}</p>
<p>Access Token: {accessToken}</p>
</div>
);
};
export default Profile;
上面已经解释了
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
我通过使用loginWithPopup而不是loginredirect解决了这个问题。我也使用了该链接。
authorizationParams={{ redirect_uri: 'mysiteadress.com/home' }}我没有使用window.location.origin。但我在这部分代码中使用了地址。