0

Hi I followed a tutorial on the web. Everything work but I would encode bas64 with a secret or jwt but I don't know how. Can you help me please ?

(function () {
    'use strict';

    angular
        .module('app')
        .factory('AuthenticationService', Service);

    function Service($http, $localStorage) {
        var service = {};

        service.Login = Login;
        service.Logout = Logout;

        return service;

        function Login(username, password, callback) {
            $http.post('/api/authenticate', { username: username, password: password })
                .success(function (response) {
                    // login successful if there's a token in the response
                    if (response.token) {
                        // store username and token in local storage to keep user logged in between page refreshes
                        $localStorage.currentUser = { username: username, token: response.token };

                        // add jwt token to auth header for all requests made by the $http service
                        $http.defaults.headers.common.Authorization = 'Bearer ' + response.token;

                        // execute callback with true to indicate successful login
                        callback(true);
                    } else {
                        // execute callback with false to indicate failed login
                        callback(false);
                    }
                });
        }

        function Logout() {
            // remove user from local storage and clear http auth header
            delete $localStorage.currentUser;
            $http.defaults.headers.common.Authorization = '';
        }
    }
})();

and my service :

function run($rootScope, $http, $location, $localStorage) {
        // keep user logged in after page refresh
        if ($localStorage.currentUser) {
            $http.defaults.headers.common.Authorization = 'Bearer ' + $localStorage.currentUser.token;
        }

        // redirect to login page if not logged in and trying to access a restricted page
        $rootScope.$on('$locationChangeStart', function (event, next, current) {
            var publicPages = ['/login'];
            var restrictedPage = publicPages.indexOf($location.path()) === -1;
            if (restrictedPage && !$localStorage.currentUser) {
                $location.path('/login');
            }
        });
    }

and the nodeJs :

function setupFakeBackend($httpBackend) {
        var testUser = { username: 'test', password: 'test', firstName: 'Test', lastName: 'User' };

        // fake authenticate api end point
        $httpBackend.whenPOST('/api/authenticate').respond(function (method, url, data) {
            // get parameters from post request
            var params = angular.fromJson(data);

            // check user credentials and return fake jwt token if valid
            if (params.username === testUser.username && params.password === testUser.password) {
                return [200, { token: 'fake-jwt-token' }, {}];
            } else {
                return [200, {}, {}];
            }
        });


        $httpBackend.whenGET(/^\w+.*/).passThrough();
    }

Thank you for your answer :)

3
  • Just a quick question, why do you want to hash the token? it should already be base64 encoded anyway. May 25, 2016 at 7:44
  • Also I would reccomended storing your JWTs in cookies rather than localstorage - ... store your JWT in cookies for web applications, because of the additional security they provide, and the simplicity of protecting against CSRF with modern web frameworks. HTML5 Web Storage is vulnerable to XSS, has a larger attack surface area, and can impact all application users on a successful attack. - stormpath.com/blog/… May 25, 2016 at 7:46
  • Thank you ! I thought it was not encoded automatically. I'm beginner, sorry. Thank you I will look your link on the cookies
    – user6285277
    May 25, 2016 at 7:50

1 Answer 1

0

JSON Web Tokens are composed of three JSON objects encoded to base 64 seperated by a . character.

header.payload.signiture

The example found at jwt.io eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9.TJVA95OrM7E2cBab30RMHrHDcEfxjoYZgeFONFh7HgQ decodes to three JSON strings separated by .

If you wish to pull out the seperate componets you must first split the String

// es6
let myJwt = getToken();
let jwtParts = myJwt.split('.').map(part => btoa(part));
console.log(`header: ${jwtParts[0]}, payload: ${jwtParts[1]}, sig: ${jwtParts[2]}`)

On the server side you should be using the signing (for login) and verifying functions (for subsequent authentication) found in your JWT library i.e https://github.com/auth0/node-jsonwebtoken

Let me know if that was not quite what you are looking for

4
  • Yes thank you with the secret because my token is 'fake-jwt-token' is not professional :) and how I can to have a storage in cookies and not local please ?
    – user6285277
    May 25, 2016 at 8:11
  • There just so happens to be an angular modules just for that purpose ngCookies the you want to be using the $cookies service - docs.angularjs.org/api/ngCookies/service/$cookies May 25, 2016 at 8:16
  • Thank you so this is correct ? $rootScope.globals = $cookieStore.get('globals') || {};
    – user6285277
    May 25, 2016 at 11:57
  • I would wrap it in your authentication service, then wrap the $cookie set and get methods as you want to make sure updates get written back May 25, 2016 at 11:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.