问题
When I leave my WinJS app dormant for a while and then come back to it, and i click on a button, for some reason my calls to my backend aren't working.
I get an "Unauthorized" error from the server.
How do I modify the invokeApi so that it reauthenticates the user or something?
Does anybody have any experience using mobileservices.web.js and how to keep the end user perpetually logged in without having to reauthenticate themselves?
Thankyou.
client.invokeApi("getTopForumsTotal", {
method: "post"
}).then(function (results) {
// do something
}, function (error) {
WinJS.log(error);
});
I use winjs mobileService to authenticate the user.
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);
});
and this is what I use to refresh the end users token.
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);
});
回答1:
Instead of wrapping a promise around every API call I just incorporated an idle routine on the client that refreshes the user token when they return to the app as well as refreshes the token every 59 seconds that they are idle.
So for all intense and purposes they will always have an valid token or perpetual state.
$(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
来源:https://stackoverflow.com/questions/41310757/mobileservices-web-js-unauthorized-api-call