When a user logs in to be authenticated by issuing a POST request from the browser using the default Authorization Service provided by ASP.NET Web API, the POST message is not in JSON format but URL encoded like so
userName=xyz%40domain.com&password=foo_Bar&grant_type=password
This necessitates that if we use the $resource RESTful service to hit the Authorization service /token endpoint, we need to convert the JSON message format that $resource spits out to match this URL encoded format.
To do this, we need to do two things
1) Specify in the POST Request Header that the Content-Type is URL encoded like so
Content-Type = application/x-www-form-urlencoded
2) Transform the JSON to URL encoded format using the transformRequest property of $resource. See code snippet
(function(){
angular.module('common.services')
.factory('userService',
['$resource', 'appConfigs', userService]);
function userService($resource, appConfigs) {
return {
register: $resource(appConfigs.serverURL + '/api/Account/Register', null,
{
'registerUser' : { method: 'POST'}
}),
login: $resource(appConfigs.serverURL + '/token', null,
{
'loginUser': {
method: 'POST',
headers:{'Content-Type':'application/x-www-form-urlencoded'},
transformRequest: function(data, headersGetter) {
var str = [];
for (var s in data)
str.push(encodeURIComponent(s) + '=' +
encodeURIComponent(data[s]));
return str.join('&');
})
};
}
})();
Once we successfully call this endpoint from the login button, we grab and store the access token returned from the Authorization Service, thereby allowing us to pass the token along for future requests.
var user = {};
....
vm.login = function() {
vm.user.grant_type = 'password';
vm.user.userName = vm.user.email;
userService.login.loginUser ( vm.user,
function(data) {
vm.isLoggedIn = true;
vm.message = '';
vm.password = '';
vm.token = data.access_token; //SAVING TOKEN HERE!!
},
//add response.data.error callback message to the vm.user.message property
....
);
};
No comments:
Post a Comment