What is the best way to log in with Angularjs

Asked

Viewed 4,341 times

6

In an app using Angularjs and Ionic, what’s the best way to authenticate in an API? I log in to all screens or use some session mechanism?

I imagine that authenticating all controllers may consume too much data... Which is the best way?

2 answers

5

Ideally using Apis that support Oauth 2, you then perform the initial procedures to get the bearer token and stores it in a cookie to be used in any request to the API (or at least to endpoints that require this authentication). I’ll give you an example of a service I am using in an application to perform all authentication procedures with an API that makes use of Oauth 2.

Here is the code of service:

(function () {
    'use strict';

    angular
        .module('zigforumApp')
        .service('users', users);

    users.$inject = ['$http', '$cookies', 'TOKEN_URL'];

    function users($http, $cookies, TOKEN_URL) {
        var sv = this;

        function NoAuthenticationException(message) {
            this.name = 'AuthenticationRequired';
            this.message = message;
        }

        function AuthenticationExpiredException(message) {
            this.name = 'AuthenticationExpired';
            this.message = message;
        }

        function AuthenticationRetrievalException(message) {
            this.name = 'AuthenticationRetrieval';
            this.message = message;
        }

        sv.userData = {
            isAuthenticated: false,
            username: '',
            bearerToken: '',
            expirationDate: null
        };

        function isAuthenticationExpired(expirationDate) {
            var now = new Date();
            expirationDate = new Date(expirationDate);

            if (expirationDate - now > 0) {
                return false;
            } else {
                return true;
            }
        }

        function saveData() {
            removeData();
            $cookies.putObject('auth_data', sv.userData);
        }

        function removeData() {
            $cookies.remove('auth_data');
        }

        function retrieveSavedData() {
            var savedData = $cookies.getObject('auth_data');

            if (typeof savedData === 'undefined') {
                throw new AuthenticationRetrievalException('No authentication data exists');
            } else if (isAuthenticationExpired(savedData.expirationDate)) {
                throw new AuthenticationExpiredException('Authentication token has already expired');
            } else {
                sv.userData = savedData;
                setHttpAuthHeader();
            }
        }

        function clearUserData() {
            sv.userData.isAuthenticated = false;
            sv.userData.username = '';
            sv.userData.bearerToken = '';
            sv.userData.expirationDate = null;
        }

        function setHttpAuthHeader() {
            $http.defaults.headers.common.Authorization = 'Bearer ' + sv.userData.bearerToken;
        }

        this.isAuthenticated = function () {
            if (!(sv.userData.isAuthenticated && !isAuthenticationExpired(sv.userData.expirationDate))) {
                try {
                    retrieveSavedData();
                } catch (e) {
                    return false;
                }
            }

            return true;
        };

        this.removeAuthentication = function () {
            removeData();
            clearUserData();
            $http.defaults.headers.common.Authorization = null;
        };

        this.authenticate = function (username, password, persistData, successCallback, errorCallback) {
            this.removeAuthentication();
            var config = {
                method: 'POST',
                url: TOKEN_URL,
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded'
                },
                data: 'grant_type=password&username=' + username + '&password=' + password
            };

            $http(config)
                .success(function (data) {
                    sv.userData.isAuthenticated = true;
                    sv.userData.username = data.userName;
                    sv.userData.bearerToken = data.access_token;
                    sv.userData.expirationDate = new Date(data['.expires']);
                    setHttpAuthHeader();
                    if (persistData === true) {
                        saveData();
                    }
                    if (typeof successCallback === 'function') {
                        successCallback();
                    }
                })
                .error(function (data) {
                    if (typeof errorCallback === 'function') {
                        if (data && data.error_description) {
                            errorCallback(data.error_description);
                        } else {
                            errorCallback('Unable to contact server; please, try again later.');
                        }
                    }
                });
        };

        try {
            retrieveSavedData();
        } catch (e) { }
    }
})();

The most important function is authenticate it receives user login data, requests the API to get the token, stores the token in a cookie and to automatically authenticate all requests that will be made hereafter it adds this token as header pattern.

You can use this service as a base to build your.

  • Good @Zignd! I will make an implementation using Oauth2 and following your code example. Thank you.

3

The best way to log in with Angularjs is...

Do not log in with Angularjs.

Seriously. Being a technology that runs on the client, any and all credential validation rules (connection to a endpoint to verify user and password, for example) can be exploited by a malicious user.

The best way, in this case, would involve delegating responsibility for Sign-in and Sign-out actions to another part of the application - in the well-given example by Zignd, this technology would be Oauth.

The final result of an antentication via Oauth is a token, which can be stored in Localstorage or a cookie. Use this token for information regarding the currently logged in user.

  • Okay @Ibotinelly, I have a two-step authentication in an api... I will seek to implement the Oauth2 standard. Thank you.

  • 1

    @Maurílionovais Not so - feel free to post more questions when the questions regarding the implementation start to appear. This post (in English) provides several links that can help your initial research: http://stackoverflow.com/questions/29660828/custom-oauth-server-implementation-and-its-advantages

Browser other questions tagged

You are not signed in. Login or sign up in order to post.