Search code examples
javascriptreact-nativefetchpatchauth0

Auth0 React Native patch user by Management API


I want to patch the user_metadata of a user in my Auth0 Authentication in react native but I get the following error:

{"error": "Unauthorized", "message": "Missing authentication", "statusCode": 401}

So I am importing Auth0 in my react native:

import Auth0 from "react-native-auth0";

const auth0 = new Auth0({
 domain: Config.AUTH0_DOMAIN,
 clientId: Config.AUTH0_CLIENT_ID
});

I use the constants Config.AUTH0_DOMAIN and Config.AUTH0_CLIENT_ID from my dashboard from my application.

As a next step I execute the following code:

 login = () => {
    auth0.webAuth
      .authorize({
        scope: Config.AUTHO_SCOPE,
        audience: Config.AUTH0_AUDIENCE,
        device: DeviceInfo.getUniqueID(),
        prompt: "login"
      })
      .then(res => {
        auth0.auth
            .userInfo({token: res.accessToken})
            .then(data => {
              fetch(`https://<MY_AUTH_DOMAIN>/api/v2/users/${encodeURIComponent(data.sub)}`, {
                method: "PATCH",
                headers: {
                  'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                  "metadata": {first_name: 'John', last_name: 'Doe', skillLevel: 'PRO!'}
                })
              }).then(res => res.json())
                  .then(async (data) => {
                    try {
                      console.log('user stored', data);
                    } catch (e) {
                      console.log("error while user storing", e)
                    }
                  })
            })
      })
  }

Whereby Config.AUTHO_SCOPE and Config.AUTH0_AUDIENCE is also from my auth0's app dashboard.

Am I missing some authentication in my headers or is the Management API the wrong choice? Do I need to to this query probably from my Back-End?

Resources:

Official API Doc from the Management API: https://auth0.com/docs/api/management/v2?_ga=2.147997749.368915485.1617866251-2089752765.1617460658#!/Users/patch_users_by_id

Official react-native-auth0 doc: https://auth0.github.io/react-native-auth0/src_management_users.js.html

Thanks for the help!


Solution

  • I was having this issue and I got it working after a little work.

    First, I had to configure my project to give metadata write permission in Auth0's dashboard at Applications/Apis.

    enter image description here

    The two I added were read:current_user and update:current_user_metadata. Then, in my authorize request, I modified both scope and audience.

    audience: 'https://<MY APP DOMAIN>/api/v2/'

    scope: 'read:current_user update:current_user_metadata openid profile offline_access'

    Next, I got the userId by passing my authentication token to auth.userInfo like so.

    auth0.auth.userInfo({token: authToken}).then((response)=>{
            return response.sub;
        })
    

    Finally, I used the value returned from response.sub along with the authToken that I had setup with special audience and scope to patch the user, and it worked successfully. UserId is what response.sub returned.

    auth0.users(authToken).patchUser({id: userId, metadata: newUserMetadata});
    

    EDIT:

    One other issue I see with your code snippet, if you want to use fetch, is you didn't put a bearer authorization token in the header. Your fetch response will probably return with a 401 error if that's the case. The code should look something like this:

    const serverResponse = await fetch('https://<MYAPP>.auth0.com/api/v2/users/' + user.sub,{
                        headers:{
                            Authorization: 'Bearer ' + accessToken
                        }
                    })