How to get Access Token from ASP.Net Web API 2 via AngularJS $http?

Chaddeus picture Chaddeus · Dec 4, 2013 · Viewed 21.2k times · Source

I try like this:

$http({ method: 'POST', url: '/token', data: { username: $scope.username, password: $scope.password, grant_type: 'password' } }).success(function (data, status, headers, config) {
    $scope.output = data;
}).error(function (data, status, headers, config) {
    $scope.output = data;
});

then tried changing the grant_type to a param:

$http({ method: 'POST', url: '/token', data: { username: $scope.username, password: $scope.password }, params: { grant_type: 'password' } }).success(function (data, status, headers, config) {
    $scope.output = data;
}).error(function (data, status, headers, config) {
    $scope.output = data;
});

Still get the dreaded: {"error":"unsupported_grant_type"}

So I do what no AngularJS developer should ever do, resorted to jQuery:

var data = $('#regForm').serialize() + "&grant_type=password";
$.post('/token', data).always(showResponse);

function showResponse(object) {
    $scope.output = JSON.stringify(object, null, 4);
    $scope.$apply();
};

Which works like a champ... so my question is: how do we replicate the jQuery $.post() call above using AngularJS $http() so we can grab an access token from the OWIN middleware based /token endpoint in ASP.Net Web API 2?

Answer

Achinth Gurkhi picture Achinth Gurkhi · Feb 24, 2014

Do this:

$http({
        url: '/token',
        method: 'POST',
        data: "userName=" + $scope.username + "&password=" + $scope.password + 
              "&grant_type=password"
})