AngularJS service code with ASP .NET WEB API2

The following AngularJS service code shows how to login with bearer token authentication of ASP.NET WEB API2 to access exported restful APIs.

'use strict';
app.factory('authService', function ($http, $q) {

    var service = {};

    service.loginToken = {};

    service.getAccessToken = function () {
        return loginToken.access_token;
    };

    service.login = function (userName, password) {
        var deferred = $q.defer();

        var loginData = {
            grant_type: "password",
            username: userName,
            password: password
        };

        $http({
                method: 'POST',
                url: '/Token',
                headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                data: $.param(loginData)
            })
            .success(function (response) {
                service.loginToken = response;
                deferred.resolve(response);
            })
            .error(function (response) {
                deferred.reject(response);
            });

        return deferred.promise;
    };

    service.logout = function () {
        var deferred = $q.defer();

        $http({
            method: 'POST',
            url: '/api/Account/Logout',
            headers: { 'Authorization': 'Bearer ' + this.loginToken.access_token },
        })
            .success(function (response) {
                service.loginToken = [];
                deferred.resolve(response);
            })
            .error(function (response) {
                deferred.reject(response);
            });

        return deferred.promise;
    };

    return service;
});
Advertisements
This entry was posted in ASP.NET, Programming. Bookmark the permalink.

2 Responses to AngularJS service code with ASP .NET WEB API2

  1. osmancelik says:

    locationChangeStart or routeChangeStart, which is the best way to redirect user to login page if not logged in? any working example?

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s