2

I have an angularJS web application which uses the web api and jwt. I followed tutorial on the internet here > angularjs-jwt-auth everything is working fine when I login using credentials from my own api,returns token on console as it should.

But the issue comes when I try to register a new user, nothing happens and console is throwing me an error Failed to load resource: the server responded with a status of 401 (Unauthorized). When I use api from tutorial is working fine so am little bit lost, please help!!

My code

(function () {

function authInterceptor(API, auth) {
    return {
        // automatically attach Authorization header
        request: function (config) {
            config.headers = config.headers || {};
            var token = auth.getToken();
            if (config.url.indexOf(API) === 0 && token) {
                config.headers.Authorization = 'Bearer ' + token;
            }
            return config;
        },

        response: function (res) {
            if (res.config.url.indexOf(API) === 0 && res.data.token) {
                auth.saveToken(res.data.token);
            }

            return res;
        },
    }
}

// Services

function authService($window) {
    var srvc = this;

    srvc.parseJwt = function (token) {
        var base64Url = token.split('.')[1];
        var base64 = base64Url.replace('-', '+').replace('_', '/');
        return JSON.parse($window.atob(base64));
    };

    srvc.saveToken = function (token) {
        $window.localStorage['jwtToken'] = token
    };

    srvc.logout = function (token) {
        $window.localStorage.removeItem('jwtToken');
    };

    srvc.getToken = function () {
        return $window.localStorage['jwtToken'];
    };

    srvc.saveUsername = function (username) {
        $window.localStorage['username'] = username;
    }

    srvc.getUsername = function () {
        return $window.localStorage['username'];
    }

    srvc.isAuthed = function () {
        var token = srvc.getToken();
        if (token) {
            var params = srvc.parseJwt(token);
            return Math.round(new Date().getTime() / 1000) <= params.exp;

        } else {
            return false;
        }
    }

}



function userService($http, API, auth) {
    var srvc = this;

    srvc.register = function (first_name, last_name, email, password, role, gender, phone_number) {
        return $http.post(API + '/api/v1/users/', { // <-- Registration link here
            first_name: first_name,
            last_name: last_name,
            email: email,
            password: password,
            role: role,
            gender: gender,
            phone_number: phone_number
        });
    }

    srvc.login = function (username, password) {
        return $http.post(API + '/api/v1/token/auth/', { // <-- Login link here
            username: username,
            password: password
        });

    };




    return srvc;


}




// We won't touch anything in here
function MainCtrl(user, auth, $location, $state, $rootScope) {
    var self = this;

    function handleRequest(res) {
        var token = res.data ? res.data.token : null;
        if (token) {
            $location.path('/portfolio');
            console.log('Bearer:', token);


            auth.saveUsername($scope.username);
            $rootScope.username = auth.getUsername();
        }
        // self.message = res.data.message;
    }



    self.login = function () {
        user.login(self.username, self.password)
            .then(handleRequest, handleRequest)
    }


    self.register = function () {
        user.register(self.first_name, self.last_name, self.username, self.email, self.password, self.role, self.gender, self.phone_number)
            .then(handleRequest, handleRequest)
    }

    self.logout = function () {
        auth.logout && auth.logout();
        $location.path('/login');
    }
    self.isAuthed = function () {
        return auth.isAuthed ? auth.isAuthed() : false
    }
}




angular
    .module('App', ['ui.router'])
    .factory('authInterceptor', authInterceptor)
    .service('user', userService)
    .service('auth', authService)
    .constant('API', 'link-to-my-api') // <-- API Link here
    .config(function ($stateProvider, $urlRouterProvider, $httpProvider) {
1
  • Hey @Geofrey. Unfortunately, the code snippet in the question does not tell how or who created a new JWT token for the new user. Could you pls add that code as well? Commented Jan 15, 2019 at 1:44

1 Answer 1

2

Since JWT verification is working for the tutorial's API, the fault lies in your authentication server i.e. creation/verification of JWT token) and not in the snippet above (the client handling)

You are getting 401 due to an incorrect JWT token created or incorrect validation of the JWT token


A brief explaination of how JWT authenticates.

How JWT authenticates

  • In the example, the user first signs into the authentication server using the authentication server’s login system.
  • The authentication server then creates the JWT and sends it to the user.
  • When the user makes API calls to the application, the user passes the JWT along with the API call.
  • In this setup, the application server would be configured to verify that the incoming JWT are created by the authentication server
Sign up to request clarification or add additional context in comments.

1 Comment

Hello there, thank you so much for your answer. The authentication server API was built using python django by one of my team member. He doesn't code using angularjs. When I try to call the API using postman it works fine, but when I try to implement it on my app on client side I get 401..but only on registration. I wonder maybe I have to pass along API token on client side so that I can be registered but I don't have a clue to do that.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.