Can I set authorization headers with RequireJS?

前端 未结 1 1103
灰色年华
灰色年华 2021-01-24 17:57

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

相关标签:
1条回答
  • 2021-01-24 18:24

    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.

    For example, in a 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');
    

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


    UPDATE

    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);
                }
            }
        }
    

    Refer to: custom-xhr-hooks


    Another UPDATE

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

    require.config({
        urlArgs: 'token='+token,
        ...
    )}
    
    0 讨论(0)
提交回复
热议问题