最新消息: 电脑我帮您提供丰富的电脑知识,编程学习,软件下载,win7系统下载。

在IoT

IT培训 admin 10浏览 0评论

在IoT

我正在尝试使用后端nodeJS服务器来访问(和编辑)IoT-Core上的设备配置,参考API文档:.locations.registries.devices/get。

但是,我不断收到错误代码401并显示错误消息“message”:“请求具有无效的身份验证凭据。预期的OAuth 2访问令牌,登录cookie或其他有效的身份验证凭据。请参阅。”,“status”:“UNAUTHENTICATED”。

我从Google IAM创建了一个服务帐户和一个密钥,并为其提供了Cloud IoT Device Controller权限,该权限可以更新设备配置但不能创建或删除。随后,我将其更改为Cloud IoT Admin甚至是Project Editor权限,但仍然看到了相同的错误消息。我得到的钥匙都错了,还是没做其他我应该做的事情?

下面的代码是我如何调用请求

function createJwt (projectId, privateKeyFile, algorithm) {
    // Create a JWT to authenticate this device. The device will be disconnected
    // after the token expires, and will have to reconnect with a new token. The
    // audience field should always be set to the GCP project ID.
    const token = {
      'iat': parseInt(Date.now() / 1000),
      'exp': parseInt(Date.now() / 1000) + 20 * 60,  // 20 minutes
      'aud': projectId
    };
    const privateKey = fs.readFileSync(privateKeyFile);
    return jwt.sign(token, privateKey, { algorithm: algorithm });
}

app.get('/', function(req, res){

    let authToken = createJwt('test-project', './keys/device-config.pem', 'RS256');

    const options = {
        url: '',
        headers: {
            'authorization': 'Bearer ' + authToken,
            'content-type': 'application/json',
            'cache-control': 'no-cache'
        },
        json: true
    }

    request.get(options, function(error, response){
        if(error) res.json(error);
        else res.json(response);
    })

});
回答如下:

对于与IoT-Core交互的后端服务器,身份验证方法与设备MQTT或HTTP连接不同。参考:https://cloud.google/iot/docs/samples/device-manager-samples#get_a_device

我能够使用下面的代码检索和更新设备配置

function getClient (serviceAccountJson, cb) {
    const serviceAccount = JSON.parse(fs.readFileSync(serviceAccountJson));
    const jwtAccess = new google.auth.JWT();
    jwtAccess.fromJSON(serviceAccount);
    // Note that if you require additional scopes, they should be specified as a
    // string, separated by spaces.
    jwtAccess.scopes = 'https://www.googleapis/auth/cloud-platform';
    // Set the default authentication to the above JWT access.
    google.options({ auth: jwtAccess });

    const DISCOVERY_API = 'https://cloudiot.googleapis/$discovery/rest';
    const API_VERSION = 'v1';
    const discoveryUrl = `${DISCOVERY_API}?version=${API_VERSION}`;

    google.discoverAPI(discoveryUrl, {}, (err, client) => {
        if (err) {
        console.log('Error during API discovery', err);
        return undefined;
        }
        cb(client);
    });
}

function getDevice (client, deviceId, registryId, projectId, cloudRegion) {
    const parentName = `projects/${process.env.GCP_PROJECT_ID}/locations/${cloudRegion}`;
    const registryName = `${parentName}/registries/${registryId}`;
    const request = {
      name: `${registryName}/devices/${deviceId}`
    };

    const promise = new Promise(function(resolve, reject){
        client.projects.locations.registries.devices.get(request, (err, data) => {
            if (err) {
                console.log('Could not find device:', deviceId);
                console.log(err);
                reject(err);
            } else {
                console.log(data.config.binaryData);
                resolve(data);
            }
        });

    });
    return promise;
}

app.get('/', function(req, res){
    const cb = function(client){
        getDevice(client, 'test-device', 'dev-registry', process.env.GCP_PROJECT_ID, 'us-central1')
            .then(function(response){
                let decoded = new Buffer(response.config.binaryData, 'base64').toString();
                res.json(decoded);
            })
            .catch(function(error){
                res.json(error);
            })
    }
    getClient(serviceAccountJson, cb);

});

在IoT

我正在尝试使用后端nodeJS服务器来访问(和编辑)IoT-Core上的设备配置,参考API文档:.locations.registries.devices/get。

但是,我不断收到错误代码401并显示错误消息“message”:“请求具有无效的身份验证凭据。预期的OAuth 2访问令牌,登录cookie或其他有效的身份验证凭据。请参阅。”,“status”:“UNAUTHENTICATED”。

我从Google IAM创建了一个服务帐户和一个密钥,并为其提供了Cloud IoT Device Controller权限,该权限可以更新设备配置但不能创建或删除。随后,我将其更改为Cloud IoT Admin甚至是Project Editor权限,但仍然看到了相同的错误消息。我得到的钥匙都错了,还是没做其他我应该做的事情?

下面的代码是我如何调用请求

function createJwt (projectId, privateKeyFile, algorithm) {
    // Create a JWT to authenticate this device. The device will be disconnected
    // after the token expires, and will have to reconnect with a new token. The
    // audience field should always be set to the GCP project ID.
    const token = {
      'iat': parseInt(Date.now() / 1000),
      'exp': parseInt(Date.now() / 1000) + 20 * 60,  // 20 minutes
      'aud': projectId
    };
    const privateKey = fs.readFileSync(privateKeyFile);
    return jwt.sign(token, privateKey, { algorithm: algorithm });
}

app.get('/', function(req, res){

    let authToken = createJwt('test-project', './keys/device-config.pem', 'RS256');

    const options = {
        url: '',
        headers: {
            'authorization': 'Bearer ' + authToken,
            'content-type': 'application/json',
            'cache-control': 'no-cache'
        },
        json: true
    }

    request.get(options, function(error, response){
        if(error) res.json(error);
        else res.json(response);
    })

});
回答如下:

对于与IoT-Core交互的后端服务器,身份验证方法与设备MQTT或HTTP连接不同。参考:https://cloud.google/iot/docs/samples/device-manager-samples#get_a_device

我能够使用下面的代码检索和更新设备配置

function getClient (serviceAccountJson, cb) {
    const serviceAccount = JSON.parse(fs.readFileSync(serviceAccountJson));
    const jwtAccess = new google.auth.JWT();
    jwtAccess.fromJSON(serviceAccount);
    // Note that if you require additional scopes, they should be specified as a
    // string, separated by spaces.
    jwtAccess.scopes = 'https://www.googleapis/auth/cloud-platform';
    // Set the default authentication to the above JWT access.
    google.options({ auth: jwtAccess });

    const DISCOVERY_API = 'https://cloudiot.googleapis/$discovery/rest';
    const API_VERSION = 'v1';
    const discoveryUrl = `${DISCOVERY_API}?version=${API_VERSION}`;

    google.discoverAPI(discoveryUrl, {}, (err, client) => {
        if (err) {
        console.log('Error during API discovery', err);
        return undefined;
        }
        cb(client);
    });
}

function getDevice (client, deviceId, registryId, projectId, cloudRegion) {
    const parentName = `projects/${process.env.GCP_PROJECT_ID}/locations/${cloudRegion}`;
    const registryName = `${parentName}/registries/${registryId}`;
    const request = {
      name: `${registryName}/devices/${deviceId}`
    };

    const promise = new Promise(function(resolve, reject){
        client.projects.locations.registries.devices.get(request, (err, data) => {
            if (err) {
                console.log('Could not find device:', deviceId);
                console.log(err);
                reject(err);
            } else {
                console.log(data.config.binaryData);
                resolve(data);
            }
        });

    });
    return promise;
}

app.get('/', function(req, res){
    const cb = function(client){
        getDevice(client, 'test-device', 'dev-registry', process.env.GCP_PROJECT_ID, 'us-central1')
            .then(function(response){
                let decoded = new Buffer(response.config.binaryData, 'base64').toString();
                res.json(decoded);
            })
            .catch(function(error){
                res.json(error);
            })
    }
    getClient(serviceAccountJson, cb);

});

与本文相关的文章

发布评论

评论列表 (0)

  1. 暂无评论