簡體   English   中英

Amplify w/Cognito:如何獲取當前用戶的 Email?

[英]Amplify w/Cognito: How do I get the Current User's Email?

我正在使用 AWS Amplify,並使用 Cognito 進行用戶身份驗證。

用戶go進入用戶池,使用email地址和密碼注冊登錄。

當通過 Cognito 登錄的用戶導航到某個頁面時,我想檢索他們的 email 地址。 我怎樣才能做到這一點?

我可以使用此代碼檢索一些用戶數據(我使用的是 javascript/Angular):

import Auth from '@aws-amplify/auth';
...

ngOnInit(){
  Auth.currentAuthenticatedUser().then((user)=>{
        console.log('user = ' + JSON.stringify(user.pool))      
 })
}

email 確實出現在響應中,但我還無法從返回的 JSON 中分離出 email。

我已經嘗試瀏覽文檔,但我還沒有找到關於我可以添加到currentAuthenticatedUser()的屬性選項之類的信息,或者是否有另一種更干凈的方法(我假設有)。

編輯:看起來像以下作品:

Auth.currentAuthenticatedUser().then((user) => {
  console.log('user email = ' + user.attributes.email);
});

但我仍然希望能更好地理解文檔。 我在一個隨機的 github 問題中找到了這個解決方案,而不是官方文檔。 我可以在 AWS Amplify / Cognito 文檔中的何處找到此解決方案?

你可以從官方文檔中查看這個

並啟用讀取訪問常規設置-> 應用程序客戶端-> 顯示詳細信息-> 設置屬性讀寫權限鏈接

然后確保您正在獲取更新的屬性

Auth.currentAuthenticatedUser({ bypassCache: true })
Auth.currentSession()
    .then((data) => {
       // this data has user details in accessToken
    }).catch(err => console.log(err));
    import cognito from "../path/to/your/config/cognito.json";
    import Amplify, { Auth, Hub } from 'aws-amplify';
    ...
    ...


    useEffect(() => {
        Amplify.configure({ Auth: cognito });
        Hub.listen('auth', ({ payload: { event, data } }) => {
            switch (event) {
                case 'signIn':
                    console.log('Event name -> ', event, data)
                    // here is your name, email e.t.c.
                    console.log(data.signInUserSession.idToken.payload);
                    break
                case 'signOut':
                    console.log('sign out')
                    // this.setState({ user: null })
                    break
                default:
                    console.log('Unhandled use case - ' + event)
            }
        })
    }, [])
import { Auth } from 'aws-amplify';

Auth.currentAuthenticatedUser({
  bypassCache: false // Optional, By default is false. If set to true, this call will send a request to Cognito to get the latest user data
})
  .then((user) => console.log(user))
  .catch((err) => console.log(err));

這是我寫的一個很好用的鈎子:

import { useEffect, useState } from "react";
import { Auth } from "aws-amplify";


export interface UserDetailsT {
    username: string,
    email: string,
    emailVerified: boolean,
};


const useAuth = () => {
    const [userDetails, setUserDetails] = useState<UserDetailsT | null>(null);
    
    useEffect(() => {
        const getUserDetails = async () => {
            try {
                const { username, attributes } = await Auth.currentAuthenticatedUser() || null;
                setUserDetails({
                    username,
                    email: attributes?.email,
                    emailVerified: attributes?.email_verified
                });
            } catch {
                setUserDetails(null);
            }
        }
        getUserDetails();
    }, [Auth, setUserDetails]);

    return userDetails;
};


export default useAuth;

用戶登錄后,以下對我有用...

import { Auth, Amplify } from 'aws-amplify'

console.log(Auth.user.attributes.email)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM