【问题标题】:Angular js get user after initial middleware authenticationAngular js在初始中间件身份验证后获取用户
【发布时间】:2017-02-11 12:10:23
【问题描述】:

我正在使用 Autho JWT 为前端 Angular 应用程序验证用户。身份验证成功后,它会返回一个令牌。返回的令牌包含有效负载数据,其中包含用户名、用户 ID 和电子邮件。令牌的一个例子是:

eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VybmFtZSI6Im11dGhpb3JhIiwidXNlcl9pZCI6MiwiZXhwIjoxNDc1NTAxNDIxLCJlbWFpbCI6Im11dGhpb3JhQGdtYWlsLmNvbSJ9._jtLZ6FTlKZ_uDzqDgedIJ_4LC2LpiaVqgqfjT_4k_A

由于令牌是 base64 编码的,我很想知道如何从令牌中获取用户名。

【问题讨论】:

    标签: javascript angularjs jwt access-token


    【解决方案1】:

    如果令牌被验证,这是获取用户的解决方案

    /*global angular*/
    angular.module('authService', [])
    
    // ===================================================
    // auth factory to login and get information
    // inject $http for communicating with the API
    // inject $q to return promise objects
    // inject AuthToken to manage tokens
    // ===================================================
    .factory('Auth', function($http, $q, AuthToken) {
    
        // create auth factory object
        var authFactory = {};
    
        // log a user in
        authFactory.login = function(username, password) {
    
            // return the promise object and its data
            return $http.post('/api/authenticate', {
                username: username,
                password: password
            })
                .success(function(data) {
                    AuthToken.setToken(data.token);
                    return data;
                });
        };
    
        // log a user out by clearing the token
        authFactory.logout = function() {
            // clear the token
            AuthToken.setToken();
        };
    
        // check if a user is logged in
        // checks if there is a local token
        authFactory.isLoggedIn = function() {
            if (AuthToken.getToken()) 
                return true;
            else
                return false;   
        };
    
        // get the logged in user
        authFactory.getUser = function() {
            if (AuthToken.getToken())
                return $http.get('/api/me', { cache: true });
            else
                return $q.reject({ message: 'User has no token.' });        
        };
    
        // return auth factory object
        return authFactory;
    
    })
    
    // ===================================================
    // factory for handling tokens
    // inject $window to store token client-side
    // ===================================================
    .factory('AuthToken', function($window) {
    
        var authTokenFactory = {};
    
        // get the token out of local storage
        authTokenFactory.getToken = function() {
            return $window.localStorage.getItem('token');
        };
    
        // function to set token or clear token
        // if a token is passed, set the token
        // if there is no token, clear it from local storage
        authTokenFactory.setToken = function(token) {
            if (token)
                $window.localStorage.setItem('token', token);
            else
                $window.localStorage.removeItem('token');
        };
    
        return authTokenFactory;
    
    })
    
    // ===================================================
    // application configuration to integrate token into requests
    // ===================================================
    .factory('AuthInterceptor', function($q, $location, AuthToken) {
    
        var interceptorFactory = {};
    
        // this will happen on all HTTP requests
        interceptorFactory.request = function(config) {
    
            // grab the token
            var token = AuthToken.getToken();
    
            // if the token exists, add it to the header as x-access-token
            if (token) 
                config.headers['x-access-token'] = token;
    
            return config;
        };
    
        // happens on response errors
        interceptorFactory.responseError = function(response) {
    
            // if our server returns a 403 forbidden response
            if (response.status == 403) {
                AuthToken.setToken();
                $location.path('/login');
            }
    
            // return the errors from the server as a promise
            return $q.reject(response);
        };
    
        return interceptorFactory;
    
    });
    

    【讨论】:

      猜你喜欢
      • 2017-09-07
      • 2020-11-04
      • 2014-09-15
      • 2013-08-02
      • 2023-03-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-02
      相关资源
      最近更新 更多