在angularjs身份验证中处理JWT

时间:2014-06-03 17:27:36

标签: angularjs jwt

我们有一个Angular应用程序,我们得到了另一个.Net应用程序。登录由.Net应用程序管理,当用户登录时,它会重定向到Angular app.with身份验证令牌(JWT)到标头。让我们说url example.com /

我需要从Header捕获JWT并将其传递给API以验证JWT并在JWT有效时对用户进行身份验证。

当页面被点击时,如何从标题中捕获JWT标记?

3 个答案:

答案 0 :(得分:6)

请转到:

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

在这篇博客中,Alberto描述了如何使用$ httpProvider.interceptors管理Angular中的JWT令牌

答案 1 :(得分:2)

您应该尝试的另一件事是新的angular-jwt项目。如果这有帮助,请告诉我!

Disclamer:我基于上面的博客文章构建了angular-jwt项目。

谢谢!

答案 2 :(得分:0)

我最近也必须在角度设置JWT auth,这是我的身份验证服务,它发布到服务器端api并使用本地存储来保留令牌。

有关更多信息,我写了this post,其中包含一个带有假后端的工作演示。

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