質問

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?

役に立ちましたか?

解決

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

他のヒント

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!

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 = '';
        }
    }
})();
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top