我可以使用RequireJS设置授权标头吗? [英] Can I set authorization headers with RequireJS?

查看:103
本文介绍了我可以使用RequireJS设置授权标头吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们想为使用RequireJS进行依赖项管理的AngularJS应用程序(公共/私有)拥有2组资源.基本上,登录页面上的所有内容都是公开的,一旦登录,就会加载另一个angularjs应用程序(新的requirejs配置),该应用程序将加载需要身份验证才能访问的资源.

We want to have 2 sets of resources for our AngularJS app (public/private) which uses RequireJS for dependency management. Basically everything on the login page would be public and once logged in, another angularjs app would be loaded (new requirejs config) that would load resources that require authentication to access.

是否有一种方法可以配置requirejs以在加载资源时设置授权标头?

Is there a way to configure requirejs to set an authorization header when loading resources?

推荐答案

这取决于资源"的含义以及服务器的配置方式.但是总的来说-是的,因为您使用的是AngularJS,所以可以使用$ httpProvider注入拦截器服务.

It depends on what you mean by "resources" and how your server is configured. But in general - yes, since you are using AngularJS you can use the $httpProvider to inject an interceptor service.

例如,在服务中:

        var dependencies = ['$rootScope', 'userService'];

        var service = function ($rootScope, userService) {
            return {
                request: function(config) {
                    var currentUser = userService.getCurrentUser();
                    var access_token = currentUser ? currentUser.access_token : null;

                    if(access_token) {
                        config.headers.authorization = access_token;
                    }
                    return config;
                },
                responseError: function (response) {
                    if(response.status === 401) {
                        $rootScope.$broadcast('unauthorized');
                    }
                    return response;
                }
            };
        };

        module.factory(name, dependencies.concat(service));

然后,在配置路由后,您可以使用:

Then, after you configure your routes, you can use:

$httpProvider.interceptors.push( 'someService');

您可以在此处找到有关拦截器的更多信息: https://docs .angularjs.org/api/ng/service/$ http#interceptors

You can find some more information on interceptors here: https://docs.angularjs.org/api/ng/service/$http#interceptors

更新

您也许可以使用文本插件来尝试接收它,但是我认为保护客户端代码没有意义.另外,如果您想使用优化,无论如何资源都只会放在一个文件中...

You might be able to use the text plugin to try and receive it, but I don't see the point in protecting client side code. Plus, if you want to use optimization the resources will just come in one file anyway...

 config: {
        text: {
            onXhr: function (xhr, url) {
               xhr.setRequestHeader('Authorization','Basic ' + token);
            }
        }
    }

参考: custom-xhr-hooks

另一个更新

您也可以使用urlArgs(主要用于缓存失效),而无需使用文本插件:

You could also use urlArgs (mainly used for cache invalidation) without using the text plugin:

require.config({
    urlArgs: 'token='+token,
    ...
)}

这篇关于我可以使用RequireJS设置授权标头吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆