Handling JWT in angularjs Authentication

2020-07-30 03:59发布

问题:

We got an Angular application and we got another .Net application. The login is managed by .Net application and when the user is logged, it redirects to the Angular app.with authentication token (JWT) to the header. lets say to url example.com/

I need to capture the JWT from the Header and pass it on to a API to validate the JWT and authenticate the user if JWT is valid.

How do I capture the JWT token from the header when the page is hit?

回答1:

Please go to :

https://auth0.com/blog/2014/01/07/angularjs-authentication-with-cookies-vs-token/

On this blog Alberto described how to manage JWT tokens in Angular using $httpProvider.interceptors



回答2:

Another thing you should try is the new angular-jwt project. Let me know if this helps!

Disclamer: I built angular-jwt project based on the blog post above.

Thanks!



回答3:

I had to setup JWT auth in angular recently as well, here's my authentication service that posts to the server side api and uses local storage to hold on to the token.

For more info I wrote this post that includes a working demo with a fake backend.

(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 = '';
        }
    }
})();


标签: angularjs jwt