1

When I place the below in a React component that queries the user model I am able to get the entire user object as queried by graphQL including the id property:

console.log(this.props.data.user)

But when I try to access the id property from code:

console.log(this.props.data.user) // undefined 
console.log(this.props.data.user.id)
 // error cannot get property of undefined 

My first guess is that this is a security feature; I am using Auth0 and Graphcool.

But I may just be going about this in a backwards way. If so, any help on accessing the user id in the correct manner would be appreciated.

Thanks

Joseph Barnes
  • 620
  • 5
  • 10

1 Answers1

3

This is covered in the FAQ article on the logged in user.

Obtaining a Signed JWT with Auth0

The user query returns the currently authenticated user. So first we have to think about how the authenticated user is determined.

The current state-of-the-art is using verified JWT and passing them as the Authorization header.

After entering valid credentials in Auth0 Lock, it returns a JWT that is signed with your secret Auth0 key. This signed JWT is sent to the GraphQL server where we'll use your Auth0 key to verify it and if it belongs to a valid user, the request is authenticated.

Setting the Authorization Header with Apollo Client

So I suspect that you're simply not passing a valid Authorization header. With Apollo, you can use this to ensure passing the token if it is present. Note that we'll use local storage for storing the token from Auth0 Lock:

const networkInterface = createNetworkInterface({ uri: 'https://api.graph.cool/simple/v1/__PROJECT_ID__' })

// use the auth0IdToken in localStorage for authorized requests
networkInterface.use([{
  applyMiddleware (req, next) {
    if (!req.options.headers) {
      req.options.headers = {}
    }

    // get the authentication token from local storage if it exists
    if (localStorage.getItem('auth0IdToken')) {
      req.options.headers.authorization = `Bearer ${localStorage.getItem('auth0IdToken')}`
    }
    next()
  },
}])

const client = new ApolloClient({ networkInterface })

Check this Auth0 example code or the live demo to see how it works.

You might also be interested in this answer on authorization (permissions).

Community
  • 1
  • 1
marktani
  • 7,578
  • 6
  • 37
  • 60