Amplify w/Cognito: How do I get the Current User's Email?
Asked Answered
N

6

13

I am using AWS Amplify, with Cognito for user Auth.

Users go into a user pool, and register and sign in just with email address and password.

When a user that has signed in through Cognito navigates to a certain page, I want to be retrieve their email address. How can I do this?

I am able to retrieve some user data with this code (I am using javascript/Angular):

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

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

The email does appear on the response, but I haven't yet been able to isolate the email from the returned JSON.

I've tried going through the docs, but I haven't yet found info on stuff like the attribute options I can add to currentAuthenticatedUser(), or if there is another method that is cleaner (which I assume there is).

EDIT: It looks like the following works:

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

But I am still hoping to understand the documentation better. I found this solution in a random github question, not the official docs. Where would I find this solution in the AWS Amplify / Cognito documentation?

Nectar answered 13/11, 2019 at 15:55 Comment(2)
it would help if you posted the structure of the JSON, and change any data you don't want shown to us.Eiser
I'm actually thinking that currentAuthenticatedUser is not necessarily the right way to do this--I just haven't yet found an alternative. The JSON data returned is not the clean JSON I would expect from whatever the proper method is. My hope is that this is a fairly common requirement and there is a cleaner way to do it.Nectar
C
5
    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)
            }
        })
    }, [])
Chopin answered 19/6, 2021 at 11:59 Comment(1)
For those using Amplify v6, here's an answer that explains how to fetch the email: #77718695. TLDR: use fetchUserAttributes from @aws-amplify/authAnnam
W
2

You can check this one from the official documentation

and enable read access General settings -> App clients -> Show details -> Set attribute read and write permissions link

and then to make sure you are fetching the updated attributes

Auth.currentAuthenticatedUser({ bypassCache: true })
Weinman answered 23/5, 2021 at 1:43 Comment(1)
Yep, this is what did it for me. Thanks!Shanell
F
1
Auth.currentSession()
    .then((data) => {
       // this data has user details in accessToken
    }).catch(err => console.log(err));
Floaty answered 25/11, 2020 at 15:22 Comment(0)
P
1
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));
Prehistoric answered 7/3, 2023 at 1:31 Comment(0)
B
1

Here's a hook I wrote that works well:

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


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


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

        getUserDetails();
        Hub.listen('auth', () => getUserDetails());

    }, [Auth, userDetails, setUserDetails]);

    return [userDetails, setUserDetails];
};


export default useAuth;
Banerjee answered 3/6, 2023 at 20:47 Comment(0)
P
-4

The following works for me after the user is logged in...

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

console.log(Auth.user.attributes.email)
Phratry answered 1/6, 2020 at 2:13 Comment(1)
Gnerally not advised. The user property on the Auth class is marked as a private variable, and cannot be reliably accessed directly.Seddon

© 2022 - 2024 — McMap. All rights reserved.