我正在Visual Studio中使用Cordova开发一个跨平台的Twitter应用程序,但我被困在Twitter帐户的身份验证上。
当面向Windows/Windows Phone时,我可以使用Windows.Security.Authentication.Web.WebAuthenticationBroker.authenticateAsync
API来完成工作。但是对于Android或IOS,我无法使用API,因为它抱怨Windows未定义。
有人可以帮助我提供示例代码或关于我应该如何使用 JavaScript 进行身份验证的建议吗?
我认为你不应该依赖跨平台应用程序上的Windows API,因为它在Windows以外的任何其他平台上都不可用。相反,您可能希望使用适用于每个平台的 JavaScript 解决方案进行身份验证。
在 js 中这样做有几种可能性,具体取决于您在应用程序中使用的框架和库:如果您使用的是 jquery 或 $http 服务,如果您使用的是 angular,则可以使用 $.ajax 进行身份验证。如果你没有使用任何库,你可以使用 XMLHttpRequest。
我使用Cordova的InAppBrowser插件找到了解决方案。
将插件添加到您的项目中,然后使用以下代码来授权您的应用程序。
var self = this;
var ref = cordova.InAppBrowser.open(startURI, '_blank', 'location=yes');
ref.show();
ref.addEventListener('loadstart', function (event) {
if (event.url && event.url.match('oauth_verifier'))
{
ref.close();
self._continueAuthentication(event.url, callback);
}
});
ref.addEventListener('loadstop', function (event) {
});
ref.addEventListener('exit', function (response) {
});
_continueAuthentication: function (returnedTokens, callback) {
var self = this, oauthVerifier, oauthToken;
var responseKeyValPairs = returnedTokens.split("?")[1].split("&");
//Disect the important parts
for (i = 0; i < responseKeyValPairs.length; i++) {
splits = responseKeyValPairs[i].split("=");
switch (splits[0]) {
case "oauth_verifier":
oauthVerifier = splits[1];
break;
case "oauth_token":
oauthToken = splits[1];
break;
}
}