java - 带有授权 header 的 AngularJS CORS

标签 java angularjs jax-rs cors web.xml

很抱歉又问了一个关于 Angular 和 CORS 的问题,但我无法确定问题出在哪里。我的基本设置是一个纯 Angular 的独立网站,因此没有 Express 或任何服务器端组件,它与另一台服务器上基于 Java 的 API 通信。 API 是使用 JAX-RS 构建的,位于 JBoss 7.1.3 应用程序服务器中。我可以访问 angular 和 java 的代码。

在 API 端,使用如下所示的流行 thetransactioncompany CORS 过滤器启用 CORS。

<filter>
    <filter-name>CORS</filter-name>
    <filter-class>com.thetransactioncompany.cors.CORSFilter</filter-class>
    <init-param>
        <param-name>cors.supportedMethods</param-name>
        <param-value>GET, POST, HEAD, PUT, DELETE, OPTIONS</param-value>
    </init-param>
    <init-param>
        <param-name>cors.supportedHeaders</param-name>
        <param-value>Origin, Accept, Content-Type, X-Requested-With, Cookie,content-type</param-value>
    </init-param>
</filter>
<filter-mapping>
    <filter-name>CORS</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

API 的工作方式是通过向返回 token 的端点提供用户名和密码,然后将此 token 包含在每个后续请求的授权 header 中。该过程的第一部分工作正常,我可以提供有效的凭证并接收 token ,但随后的任何后续请求都无法正常工作。所以在我的 Angular 服务中,我有以下登录方法,它获取一个 token ,然后尝试获取当前登录的用户。

login: function(username, password){

        var deferred = $q.defer();

        $http({
            method: 'POST',
            url: 'http://localhost:8080/website-api/rest/account/token',
            headers: {'Content-Type': 'application/x-www-form-urlencoded', 'Accept': 'application/json'},
            transformRequest: function(obj) {
                var str = [];
                for(var p in obj){
                    str.push(encodeURIComponent(p) + '=' + encodeURIComponent(obj[p])); 
                }
                return str.join('&');
            },
            data: {username: username, password: password }
        })
        .success(function(token) {

            $log.info(token.jwt);

            var requestConfig = {
                headers: {
                    'Authorization': token.jwt,
                    'Accept': 'application/json',
                    'X-Testing': 'Testing'
                }
            };

            $http.get('http://localhost:8080/website-api/rest/users/current', requestConfig)
                .success(function(user) {

                    $log.info('Retrieved User');
                    user.sessionToken = token.jwt;
                    deferred.resolve(user);

                })
                .error(function(data, status, headers, config) {

                    $log.info(data);
                    $log.info(status);
                    $log.info(headers);
                    $log.info(config);
                });

        })
        .error(function(data, status, headers, config) {

            $log.info(data);
            $log.info(status);
            $log.info(headers);
            $log.info(config);
        });

        return deferred.promise;
    }

第一个请求完美运行,第二个请求失败并出现错误:

XMLHttpRequest cannot load http://localhost:8080/website-api/rest/users/current. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:9000' is therefore not allowed access.

我无法确定是 API 上的 CORS 过滤器设置是我的问题的原因,还是我在从 Angular 发送请求时没有正确执行某些操作。我怀疑它是 Angular,因为我可以使用第三方服务 Postman 和 Hurl.it 来测试我的 API 端点,它们会按预期返回用户对象。

任何帮助将不胜感激!

最佳答案

基于阅读这篇 post 的直觉,我注意到我不仅在接受的 header 列表中定义了两次 Content-Type,而且我没有将 Authorization 设置为允许的 header 。 CORS 过滤器拒绝任何包含不允许的 header 的传入请求,导致我的 403 错误。

关于java - 带有授权 header 的 AngularJS CORS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26634771/

相关文章:

java - 无法访问类的内部接口(interface)

java - 如何使用 Apache Olingo 发出 PUT 请求?

java - 如何在选择模式下使用多个ID "Property"

javascript - 将用户选择的多个单选按钮选项存储在使用 ng-repeat 构建的 Angular js 中

angularjs - 如何在angular js的选择框中加载先前的值?

java - 构建在 Spring 3 (m3) 上的 REST-fully 注释服务的最小配置是什么?

java - 如何从大量的URL中提取数据?

javascript - AngularJS:避免使用 $timeout 等待图像加载完成

java - Restful 网络服务 - NoClassDefFoundError : org/glassfish/jersey/ExtendedConfig

java - Jersey : Detect when Controller Class is Created