繁体   English   中英

Angularjs - Safari中未添加授权标头

[英]Angularjs - Authorization header not added in Safari

我目前正在使用后面的Django + Django Rest Framework(DRF)和Angularjs构建一个webapp来构建UI。

使用构建到DRF中的基本令牌身份验证对所有请求进行身份验证。 我在Angular中实现了一个基本拦截器,用于将登录后存储在会话存储中的令牌添加到每个请求中。 这适用于谷歌浏览器(我可以看到授权标题实际上是使用检查器添加到每个请求)和Firefox。 但是在Safari中,标题不会添加到某些请求中。

首先,这是我使用的拦截器:

app.factory('authInterceptor', ['$rootScope', '$q', '$window', function($rootScope, $q, $window){
    return {
        // This method adds the authentication token to each requests' header
        request: function(config){
            config.headers = config.headers || {};

            // add authentication token in header
            try {
                var token = $window.sessionStorage.token;
            } catch(err){
                token = undefined;
            }
            if(token !== undefined){
                config.headers.Authorization = 'Token ' + token;
            }
            return config;
        },
        response: function(response){
            if(response.status === 401){
                // user not authenticated
            }
            return response || $q.when(response);
        }
    };
}]);

让我在Safari中头疼的特定资源之一是:

app.factory('Coach', ['$resource', '$rootScope',
    function($resource, $rootScope){
        return $resource(
            $rootScope.api_url + 'api/coaches/:coachId/?format=json',
            {
                coachId: '@id'
            }
            ,
            {
                getByUserId: {method:'GET', url: $rootScope.api_url + 'api/coaches', isArray:false},
                update: {method:'PUT'}
            }
        );
}]);

如果尝试将withCredentials添加到getByUserId方法但没有运气。

我的拦截器被正确推送到$ httpService。 我已经验证了令牌在sessionStorage中的Safari中可用。 我已经从拦截器将令牌打印到控制台。 无法理解这个问题。

任何人?

最后偶然发现了解决这个烦人问题的方法。 事实证明,它实际上与Angularjs如何删除url中的尾部斜杠以及Django如何需要这些斜杠来执行其魔法有关。

由于Angular中的尾部斜杠已被删除,因此服务器响应301(永久移动)响应。 Django Rest Framework然后将请求重定向到正确的URL(包括尾随斜线)。 但是,由于某些原因,在IE和Safari中,身份验证令牌未传递到第二个请求中。 这是你的问题。

希望这有任何帮助。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM