Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 398
9gt53wS Avatar asked Nov 26 '22 23:11

9gt53wS


1 Answers

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 })
like image 150
kam Avatar answered Dec 22 '22 01:12

kam