【问题标题】:Send request with auth token in header in angularjs在angularjs的标头中发送带有身份验证令牌的请求
【发布时间】:2016-07-05 00:55:09
【问题描述】:

我在后端实现了 jwt 无状态,所以除了登录和注册之外,所有其他方法都必须在 angularjs 中拦截并在请求标头中向服务器发送身份验证令牌。但是令牌没有发送意味着在控制台的请求标头中看不到(开发人员工具) .

这是我的interceptor.js:

/**
 * 
 */
/* Interceptor declaration */
rootApp.factory('authInterceptor', function ($rootScope, $q, $sessionStorage, $location,$window) {
    return {
        request: function (config) {
            //config.headers['Content-Type'] = 'application/json';
            config.headers = config.headers || {};
            if ($window.sessionStorage.token) {
                config.headers.Authorization =  'Bearer '  + $window.sessionStorage.token;
                //config.headers['x-auth-token'] ='Bearer '  + $window.sessionStorage.token;
            }
            return config;
        },
        response: function (response) {

            if(response.status === 200){                
                if(response.data && response.data.success === false){
                    if($rootScope.authFailureReasons.indexOf(response.data.reason) !== -1){
                        $location.path('/login');
                    }
                }
            }

            if (response.status === 401) {
                $location.path('/');
            }

            return response || $q.when(response);
        },
        'responseError': function (rejection) {
            return $q.reject(rejection);
        }
    };
});

rootApp.config(['$httpProvider', function ($httpProvider) {
      // $httpProvider.interceptors.push('headerInterceptor');
        $httpProvider.interceptors.push('authInterceptor');
    }]);

而service.js文件是:

rootApp.service('adminService', function ($rootScope, $http, $q,$window) {

    return {
        inviteUser: function (user) {

            var deferred = $q.defer();

            $http({
                method: 'POST',
                url:$rootScope.baseUrl+'api/v1/admin/user/add',
                data:user


            }).success(function (response, status, headers, config) {



                deferred.resolve(response);
            }).error(function () {
                // Something went wrong.
                deferred.reject({'success': false, 'msg': 'Oops! Something went wrong. Please try again later.'});
            });

            return deferred.promise;

        }
    };
});

在服务器端 X-AUTH-TOKEN 也允许在标头中。我哪里出错了 请帮忙。

【问题讨论】:

  • 您确定 if ($window.sessionStorage.token) 正在评估为 true

标签: angularjs spring jwt


【解决方案1】:

嘿,我最近在我的 Ionic 应用程序中进行了我的第一个令牌身份验证.. 是的,这是一个简单的步骤,但如果您不是语言专业人士,实施可能需要一些时间.. 你可以试试这个。 https://devdactic.com/user-auth-angularjs-ionic/ 这是网络上最好的和经过测试的基于令牌的 AUTH 教程之一。 也许这可以帮助您找到错误!

【讨论】:

    猜你喜欢
    • 2019-12-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-15
    • 2012-12-12
    相关资源
    最近更新 更多