Getting auth0 username from React auth0Client

Hello there, I’m new to all of this so please point me in the right direction if I’m lost.

I followed this tutorial for creating a react-app with Auth0, and everything seems to be running fine, but I am trying to get access to a user’s username and can’t seem to get it to work.

I created the Auth class and am using an instance of it as auth0Client as per the tutorial, and when I run auth0Client.getProfile() I can see the user’s name(email), nickname, picture, updated_at, and iss. How would I go about editing the code provided in this tutorial to also get the user’s username?

Sorry if this is vague, I’m feeling a bit lost.

Hi @CameronKnaus,

Sorry if this response is too late for you, but you may want to take a look at a new blog post that has come out since you posted - The Complete Guide to React User Authentication with Auth0
This makes use of our React SDK - Auth0 React SDK for Single Page Apps

As for getting the username, as it is not directly part of the OIDC standard claims you will need to add it to the ID token using custom namespaced claims in a rule.

For example, by adding this rule:

function (user, context, callback) {
  const namespace = 'https://myapp.example.com/';
  context.idToken[namespace + 'username'] = user.username;
  return callback(null, user, context);
}

I was able to retrieve the username from the user object by editing the react quickstart’s Profile.js:

export const ProfileComponent = () => {
  const { user } = useAuth0();

  return (
    <Container className="mb-5">
      <Row className="align-items-center profile-header mb-5 text-center text-md-left">
        <Col md={2}>
          <img
            src={user.picture}
            alt="Profile"
            className="rounded-circle img-fluid profile-picture mb-3 mb-md-0"
          />
        </Col>
        <Col md>
          <h2>{user.name}</h2>
          <p className="lead text-muted">{user.email}</p>
          <p className="lead text-muted">Username:{user['https://myapp.example.com/username']}</p>
        </Col>
      </Row>
      <Row>
        <Highlight>{JSON.stringify(user, null, 2)}</Highlight>
      </Row>
    </Container>
  );
};
1 Like

This topic was automatically closed 15 days after the last reply. New replies are no longer allowed.