"This endpoint requires a Bearer token" response when trying to update user roles

Netlify site: chromictm.netlify.app
Tested locally using Netlify CLI

Hi!
So I’m trying to update Netlify Identity roles for a user on login using a netlify function:

exports.handler = async function (event, context) {
    const { identity, user } = context.clientContext;

    return fetch(`${identity.url}/admin/users/${user.sub}`, {
        method: 'put',
        body: JSON.stringify({
            app_metadata: {
                roles: ["user"]
            }
        }),
        headers: {
            Authorization: `Bearer ${identity.token}`
        }
    }).then(response => {
        return response.json()
    }).then(updatedUser => {
        return {
            statusCode: 200,
            body: JSON.stringify(updatedUser)
        }
    })
};

Running the function:

netlifyIdentity.on('login', user => {
    fetch("/.netlify/functions/test-identity", {
        headers: {
            'content-type': 'application/json',
            Authorization: `Bearer ${user.token.access_token}`
        }
    }).then(response => {
        if (response.ok) {
            return response.json()
        } else {
            throw response.statusText
        }
    }).then(data => {
        console.log(data)
    }).catch(error => {
        console.log(error)
    })
});

When I try to run the program, I get a 401 response, saying: "This endpoint requires a Bearer token"

I know that the function is being run, and that a bearer token is sent in the header.

Any idea what i could have done wrong?

Thanks!

Hi @Chromic,

Thanks for reaching out and welcome to Netlify’s Support Forums!

You may want to check that user.token.access_token is valid access token. You can do that by using console.log to confirm the presence of the token.

Hi.

I have console logged both the user.token.access_token and the identity.token:

The first one contains the information that you get in the user variable in the serverless function:

{
  "exp": <exp>,
  "sub": <id>,
  "email": <email>,
  "app_metadata": {
    "provider": "email"
  },
  "user_metadata": {
    "full_name": <username>
  }
}

The second contains this JSON-data:

{
  "source": "netlify dev",
  "testData": "NETLIFY_DEV_LOCALLY_EMULATED_IDENTITY"
}

The first one seems to be correct at least.
I’m kinda new to Netlify, so I don’t know if the second one is correct or not.

Please let me know if something here seems wrong!

Ok, so after deploying the site it seems to work properly…

I also get a completely different identity.token:

{
  "exp": <exp>,
  "sub": "0"
}

Is there a way to make this work locally as well, or do I have to deploy the site every time I want to test it?

Identity doesn’t work in CLI: [feature] local emulation of Netlify Identity · Issue #440 · netlify/cli (github.com)

Oh, ok. I guess I’ll just deploy the site whenever I need to test this then.

Thanks for your time!