2017-08-09 39 views
0

我正在设置IBM Watson语音到文本。这需要一个访问令牌,documented hereIBM Watson令牌在一小时内过期。代码刷新令牌?

“令牌有一个小时的生存时间(TTL),在此之后,您不能再使用它们与服务建立连接。已经与令牌建立的连接是不受超时影响尝试传递过期或无效令牌会从DataPower中引发HTTP 401 Unauthorized状态代码,您的应用程序代码需要准备好刷新令牌以响应此返回代码。

我没有在文档页面上看到刷新令牌的应用程序代码示例。

我的代码是否应该为每个下载JavaScript应用程序的用户生成一个新的令牌?或者服务器应该每隔一小时申请一个新的令牌,并为所有用户提供一个小时的相同令牌?

shell命令获得令牌是:

卷曲-X GET --user用户名:密码\ --output令牌\ “https://stream.watsonplatform.net/authorization/api/v1/token?url=https://stream.watsonplatform.net/speech-to-text/api

这看起来像我可以发送一个HTTP来自我的JavaScript应用程序的请求并获取令牌。我是否应该将令牌作为文件请求,然后让我的应用程序从文件中获取令牌?

回答

0

enter code here工作原理是使用用于登录的用户触发的Firebase(Google Cloud Functions的一部分)Cloud Functions,运行Node发送HTTP请求以获取令牌,然后将结果写入AngularJS值服务。

这个云功能的工作原理:

// Node modules 
const functions = require('firebase-functions'); 
const admin = require('firebase-admin'); 
const request = require('request'); // node module to send HTTP requests 
const fs = require('fs'); 

admin.initializeApp(functions.config().firebase); 

exports.getWatsonToken = functions.database.ref('userLoginEvent').onUpdate(event => { // authentication trigger when user logs in 

    var username = 'groucho', 
     password = 'swordfish', 
     url = 'https://' + username + ':' + password + '@stream.watsonplatform.net/authorization/api/v1/token?url=https://stream.watsonplatform.net/speech-to-text/api'; 

    request({url: url}, function (error, response, body) { 

    var tokenService = "app.value('watsonToken','" + body + "');"; 

    fs.writeFile('../public/javascript/services/watsonTokenValue.js', tokenService, (err) => { 
     if (err) throw err; 
     console.log('The file has been saved!'); 
    }); // close fs.writeFile 

    }); // close request 

}); // close getWatsonToken 

在控制器:

firebase.auth().onAuthStateChanged(function(user) { // this runs on login 
    if (user) { // user is signed in 
     console.log("User signed in!"); 
     $scope.authData = user; 
     firebase.database().ref('userLoginEvent').update({'user': user.uid}); // update Firebase database to trigger Cloud Function to get a new IBM Watson token 
    } // end if user is signed in 
    else { // User is signed out 
     console.log("User signed out."); 
    } 
    }); // end onAuthStateChanged 

通过云功能散步,它注入四个波节模块,包括request发送HTTP请求,并fs写作结果到一个文件。然后,将触发器设置为更新Firebase数据库中的位置userLoginEvent(我通过控制台创建该位置)。接下来,HTTP请求消失。响应(令牌)被称为body。 app.value(“watsonToken”,'” +体+“');”是一个角度值的服务包裹令牌然后fs写入这一切向位置在我的项目

在AngularJS控制器,onAuthStateChanged。触发用户登录。然后user.uid更新到Firebase数据库中的位置userLoginEvent,并且Cloud Function触发器,HTTP请求熄灭,并将响应写入到角度服务。