I am trying to accomplish two things here:
1) pass in a username and password from a login screen to getToken.getToken() which in turn calls getTokenFromServer.getToken which sets token to the returned token value.
2) call getToken.getToken each subsequent time from Angular controllers, but this time just returning the already retrieved token that I'm assuming is stored in the getToken factory since it's a singleton?
Am I on the right track here with AngularJS / Web API 2 authentication?
I know getTokenFromServer.getToken works if given a username and password it will return a valid token. But I am not sure what exactly to do from there in terms of saving a token for subsequent calls to controllers that need a token. Thank you for your help.
securityApp.factory("getToken", function (getTokenFromServer) {
function getToken(userName, password) {
var token;
if (!!token) {
getTokenFromServer.getToken(username, password).then(function (data) {
token = data;
});
};
return token;
}
});
securityApp.factory("getTokenFromServer", function ($http, $q) {
function getToken(userName, password) {
return $http({
method: 'POST', url: '/token', data: { username: userName, password: password, grant_type: 'password' }, transformRequest: function (obj) {
var str = [];
for (var p in obj)
str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
return str.join("&");
}
})
.then(function (result) {
return result.data.access_token;
}, function (errorResponse) {
return $q.reject(errorResponse.data);
});
}
return {
getToken: getToken
};
});