2016-12-24 98 views
0

当我离开我的WinJS应用程序休眠一段时间然后再回到它,并且我点击一个按钮,出于某种原因,我对后端的调用不起作用。MobileServices.web.js未授权的API调用

我从服务器收到“未经授权”错误。

如何修改invokeApi以便重新验证用户或其他东西?

有没有人有使用mobileservices.web.js的经验,以及如何让最终用户永久登录而不必重新进行身份验证?

谢谢。

client.invokeApi("getTopForumsTotal", { 
    method: "post" 
}).then(function (results) { 
    // do something 
}, function (error) { 
    WinJS.log(error); 
}); 

我使用winjs mobileService来认证用户。

client.login("microsoftaccount").done(function (results) { 
    // Create a credential for the returned user. 
    credential = new Windows.Security.Credentials.PasswordCredential("myapp", results.userId, results.mobileServiceAuthenticationToken); 
    vault.add(credential); 

    completeDispatcher(); 
}, function (error) { 
    WinJS.log(JSON.stringify(error)); 
    errorDispatcher(error); 
}); 

这就是我用来刷新最终用户的令牌。

client._request("GET", "/.auth/refresh", null, null, { 
    accept: "application/json", 
    "ZUMO-API-VERSION": "2.0.0" 
}, [], (error, response) => { 
    if (!error) { 
     var userObject = JSON.parse(response.responseText) 

     if (userObject.authenticationToken) { 
      client.currentUser.mobileServiceAuthenticationToken = userObject.authenticationToken; 

      testCall().done(function (success) { 
       if (success) { 
        credential = new Windows.Security.Credentials.PasswordCredential("myapp", userObject.user.userId, userObject.authenticationToken); 
        vault.add(credential); 
        authenticated = true; 
        completeDispatcher(); 
       } 
       else errorDispatcher('testCall API does not exist'); 
      }); 
     } 
     else errorDispatcher('no authentication token returned'); 
    } 
    else errorDispatcher(error); 
}); 
+0

你使用WinJS创建Windows/Windows Phone应用程序?你如何验证你的手机应用程序?请提供更多信息以帮助我们更好地理解您的问题。 –

+0

我已经更新了我的答案。我遇到的问题是何时调用刷新令牌例程。失败的要点是使用客户端对象对服务器进行api调用时。例如client.invokeApi,表格调用或client._request调用。如果身份验证令牌过期,则这些调用将失败,因此必须在此之前调用刷新。如何设置它以便在用户机器闲置并返回时可以刷新令牌? –

+0

关于如何使用刷新标记我建议您参考[本博文](https://shellmonger.com/2016/04/13/30-days-of-zumo-v2-azure-mobile-apps-day -7-刷新的令牌/)。 –

回答

1

而不是周围包裹每个API调用一个承诺我刚注册成立,当他们返回到应用程序,以及刷新令牌要59秒他们空闲时刷新用户令牌客户端上的空闲程序。

因此,对于所有激烈和目的,他们将始终有一个有效的令牌或永久状态。

$(document).idle({ 
    onIdle: function() { 
     // refresh user token 
     if (User.Person !== null) 
      User.Person.reauthenticate().done(); 
    }, 
    onActive: function() { 
     // when the user returns refresh their token 1 more time 
     if (User.Person !== null) 
      User.Person.reauthenticate().done(); 
    }, 
    idle: 59000, // 59 seconds 
    recurIdleCall: true // will keep refreshing every 59 seconds 
}); 

https://github.com/kidh0/jquery.idle