AngularJS CORS请求自定义头

AngularJS CORS request custom header

本文关键字:自定义 请求 CORS AngularJS      更新时间:2023-09-26

我在与AngularJS结合的服务器上启用CORS时遇到了麻烦。我使用的是Angular 1.2.16,这是我的服务器配置:

Header set Access-Control-Allow-Origin "*"
Header set Access-Control-Allow-Headers "Content-Type, X-CSRF-Token, X-Requested-With, Accept, Accept-Version, Content-Length, Content-MD5, Date, X-Api-Version, X-File-Name, Authorization"
Header set Access-Control-Allow-Methods "POST, GET, PUT, DELETE, OPTIONS"
Header set Access-Control-Allow-Credentials "true"

我可以使用下面的请求:

$http.post(configuration.authUrl, {username: 'username', password: 'password'})
    .success(function (data) {
         $cookieStore.put(configuration.sessionName, {
             token: data.authenticationToken,
              user: data.user
         });
    })
    .error(function () {}));

因为这个请求没有使用自定义头。

当我之后尝试请求以下内容时:Balance.get(), Balance为:

angular.module('portalApp')
    .factory('Balance', ['$resource', 'Auth', 'configuration', function ($resource, Auth, configuration) {
        return $resource(configuration.balanceUrl, {}, {
            get: {
                method: 'GET',
                isArray: false,
                headers: {
                    Authorization: Auth.getAuthToken()
                }
            }
        });
    }]);

我在balanceUrl上得到一个401 Unauthorized

在配置中我添加了:

$httpProvider.defaults.useXDomain = true;
delete $httpProvider.defaults.headers.common['X-Requested-With'];

我甚至试着把$http.defaults.headers.common.Authorization = Auth.getAuthToken();放在Balance资源工厂的$resource之前,但这没有帮助。

发送到飞行前OPTIONS请求的头没有Authorization头,无论我使用什么方法。这些是飞行前OPTIONS请求的请求头。

OPTIONS /api/v1.0/user/orders HTTP/1.1
Host: host
Connection: keep-alive
Cache-Control: no-cache
Access-Control-Request-Method: GET
Pragma: no-cache
Origin: origin
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.153 Safari/537.36
Access-Control-Request-Headers: accept, authorization
Accept: */*
Referer: referer
Accept-Encoding: gzip,deflate,sdch
Accept-Language: en-US,en;q=0.8

有什么建议吗?

我知道你不能用Access-Control-Allow-Origin "*"Access-Control-Allow-Credentials "true"

经过大量研究,我发现问题不是因为AngularJS或Apache的配置而发生的。这是后端服务器应用程序(Java)中的问题。url对所有HTTP方法都有限制,所以当AngularJS想要执行preflight OPTIONS请求时,访问被拒绝,并返回401

if(!authenticationService.isTokenValid(glueToken) && !((HttpServletRequest)servletRequest).getMethod().equals(HttpMethod.OPTIONS.toString()) ){
  response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
} else {
  filterChain.doFilter(servletRequest, servletResponse);
}

代替:

if(!authenticationService.isTokenValid(glueToken)){
  response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
} else {
  filterChain.doFilter(servletRequest, servletResponse);
}

为什么不匿名(不执行身份验证或授权)允许飞行前请求的选项。https://stackoverflow.com/a/21458845/101662

我使用了一种完全不同的方法,但前提仍然是相同的。

首先尝试将Bearer放在您的访问令牌前面:

headers: {
    Authorization: 'Bearer ' + Auth.getAuthToken()
}

如果没有,试试这个:如果你没有将app设置为变量,app.config可能无法工作,所以你可能需要调整。

app.config(
    function($httpProvider) {
        $httpProvider.defaults.headers.common = {};
        $httpProvider.defaults.headers.post = {};
        $httpProvider.defaults.headers.put = {};
        $httpProvider.defaults.headers.patch = {};
        $httpProvider.defaults.headers.common.Authorization = 'Bearer ' + Auth.getAuthToken();
    }
);