AngularJS service code with ASP .NET WEB API2

less than 1 minute read

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
'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;
});