NodeJS 如何修复在React Native应用中使用M2M连接到Auth0 Management API v2时的'access_denied'错误?

xwmevbvl  于 2023-05-28  发布在  Node.js
关注(0)|答案(1)|浏览(130)

我是auth 0的新手,也是为手机构建应用程序的新手。
我已经将auth 0集成到我的项目中,这是一个react本地应用程序。
因此,我目前在这里使用一个本地项目。
我也创建了一个M2M来帮助我连接到一个API来对用户进行更改,但是我得到了一个错误
“access_denied:{“error”:“access_denied”,“error_description”:“客户端未被授权访问“https://[URL-ACCESS]/API/v2/".您需要创建一个与此API关联的“client-grant”。请参阅:Auth 0管理API v2
我不确定我是否错过了任何设置或任何其他步骤。请注意,我确实授权了M2M,并授予了它所有的范围。
这是我使用的代码,我从我的服务器Node.js发出调用,我的前端正在传递值React Native。

const express = require('express');
const { ManagementClient } = require('auth0');
const url = require('url');
const { authenticate } = require('./middlewares');
const axios = require('axios');
const auth0 = new ManagementClient({
  domain: process.env.AUTH0_DOMAIN,
  clientId: process.env.AUTH0_CLIENT_ID,
  clientSecret: process.env.AUTH0_CLIENT_SECRET,
  scope: 'read:users update:users'
});
const router = express.Router();

router.get('/authenticated', (req, res) => {
  res.send('You are authenticated!');
});

router.get('/admin', [authenticate, authenticate], (req, res) => {
  // You can add additional checks here to confirm the user has the 'admin' role.
  res.send('You are an admin!');
});

// Function to get Management API token
async function getManagementApiToken() {
  try {
    const response = await axios({
      method: 'POST',
      url: 'https://[URL-TOKEN]/oauth/token',
      headers: { 'content-type': 'application/json' },
      data: {
        client_id: process.env.M2M_CLIENT_ID,
        client_secret: process.env.M2M_CLIENT_SECRET,
        audience: '[AUDIENCE]/api/v2/',
        grant_type: 'client_credentials',
      },
    });

    return response.data.access_token;
  } catch (error) {
    console.error('Failed to get Management API token:', error);
    throw error;
  }
}

router.put('/update-profile', [authenticate], async (req, res) => {
  const { name, email, password, picture } = req.body;

  let managementApiToken;
  try {
    console.log('Getting Management API token...');
    managementApiToken = await getManagementApiToken();
    console.log('Got Management API token:', managementApiToken);

  } catch (error) {
    console.error('Failed to get Management API token:', error);
    return res.status(500).json({ error: 'Failed to update profile. Please try again.' });
  }

  // Validate name
  if (name && name.trim() === '') {
    return res.status(400).json({ error: 'Name cannot be empty.' });
  }

  // Validate email
  const emailRegex = /\S+@\S+\.\S+/;
  if (email && (!emailRegex.test(email))) {
    return res.status(400).json({ error: 'Invalid email.' });
  }

  // Validate password
  const passwordRegex = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,}$/;
  if (password && !passwordRegex.test(password)) {
    return res.status(400).json({ error: 'Password must be at least 8 characters long and contain at least one uppercase letter, one lowercase letter, one number, and one special character.' });
  }

  // Validate profile picture
  // If picture is provided, validate it (e.g., check it is a well-formed URL, and optionally that it points to a known good domain).
  if (picture && !url.parse(picture).hostname) {
    return res.status(400).json({ error: 'Invalid picture URL.' });
  }

  try {
    const userId = req.user.sub;
    const data = {};
    if (name) data.name = name;
    if (email) data.email = email;
    if (picture) data.picture = picture;
    if (password) data.password = password;

    // Update the user profile in Auth0
    await auth0.updateUser({ id: userId }, data, {
      headers: {
        'Content-Type': 'application/json',
        Authorization: `Bearer ${managementApiToken}`,
      },
    });

    res.status(200).json({ message: 'Profile updated successfully!' });
  } catch (error) {
    console.error('Failed to update profile:', error);
    console.error(error);
    res.status(500).json({ error: 'Failed to update profile. Please try again.' });
  }
});

module.exports = router;

我需要能够更新正在从我的前端React Native发送的用户信息

ijxebb2r

ijxebb2r1#

已解决问题。
解决方案:在调用中使用我的本地项目clientId和secret而不是M2M。因此得到一个错误

相关问题