【问题标题】:AngularJS $http, CORS and http authenticationAngularJS $http、CORS 和 http 身份验证
【发布时间】:2014-02-22 16:05:37
【问题描述】:

因为在 AngularJS 中使用 CORS 和 http 身份验证可能会很棘手,所以我编辑了这个问题以分享一个经验教训。首先我要感谢igorzg。他的回答对我帮助很大。场景如下:您想使用 AngularJS $http 服务将 POST 请求发送到不同的域。在获取 AngularJS 和服务器设置时,需要注意几件棘手的事情。

首先: 在您的应用程序配置中,您必须允许跨域调用

/**
 *  Cors usage example. 
 *  @author Georgi Naumov
 *  gonaumov@gmail.com for contacts and 
 *  suggestions. 
 **/ 
app.config(function($httpProvider) {
    //Enable cross domain calls
    $httpProvider.defaults.useXDomain = true;
});

第二: 您必须将 withCredentials: true 和用户名和密码指定为 要求。

 /**
  *  Cors usage example. 
  *  @author Georgi Naumov
  *  gonaumov@gmail.com for contacts and 
  *  suggestions. 
  **/ 
   $http({
        url: 'url of remote service',
        method: "POST",
        data: JSON.stringify(requestData),
        withCredentials: true,
        headers: {
            'Authorization': 'Basic bashe64usename:password'
        }
    });

第三: 服务器设置。您必须提供:

/**
 *  Cors usage example. 
 *  @author Georgi Naumov
 *  gonaumov@gmail.com for contacts and 
 *  suggestions. 
 **/ 
header("Access-Control-Allow-Credentials: true");
header("Access-Control-Allow-Origin: http://url.com:8080");
header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS");
header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept, Authorization");

对于每个请求。当您收到 OPTION 时,您必须通过:

/**
 *  Cors usage example. 
 *  @author Georgi Naumov
 *  gonaumov@gmail.com for contacts and 
 *  suggestions. 
 **/ 
if($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
   header( "HTTP/1.1 200 OK" );
   exit();
}

HTTP 身份验证和其他一切都在此之后。

这里是使用 php 的服务器端的完整示例。

<?php
/**
 *  Cors usage example. 
 *  @author Georgi Naumov
 *  gonaumov@gmail.com for contacts and 
 *  suggestions. 
 **/ 
header("Access-Control-Allow-Credentials: true");
header("Access-Control-Allow-Origin: http://url:8080");
header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS");
header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept, Authorization");

if($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
   header( "HTTP/1.1 200 OK" );
   exit();
}


$realm = 'Restricted area';

$password = 'somepassword';

$users = array('someusername' => $password);


if (isset($_SERVER['PHP_AUTH_USER']) == false ||  isset($_SERVER['PHP_AUTH_PW']) == false) {
    header('WWW-Authenticate: Basic realm="My Realm"');

    die('Not authorised');
}

if (isset($users[$_SERVER['PHP_AUTH_USER']]) && $users[$_SERVER['PHP_AUTH_USER']] == $password) 
{
    header( "HTTP/1.1 200 OK" );
    echo 'You are logged in!' ;
    exit();
}
?>

我的博客上有一篇关于这个问题的文章,可以看到here

【问题讨论】:

  • 问题已编辑。
  • 我有点困惑,它是 angularjs,但你把它包裹在 PHP 标签中......我错过了什么吗?
  • 这只是服务器端逻辑的一个例子。 “Тhird:服务器设置”下面的文本是服务器端逻辑。
  • @onaclov2000 AngularJS 用于客户端。这可以与任何服务器端对话,PHP、Ruby、Perl、Python、Java、JavaScript……我可以继续……
  • 这是一个问题吗?这更像是一个很好的答案:)

标签: angularjs cors


【解决方案1】:

不,您不必输入凭据,您必须将标头放在客户端,例如:

 $http({
        url: 'url of service',
        method: "POST",
        data: {test :  name },
        withCredentials: true,
        headers: {
                    'Content-Type': 'application/json; charset=utf-8'
        }
    });

并且在服务器端,您必须将标头放入此为 nodejs 的示例:

/**
 * On all requests add headers
 */
app.all('*', function(req, res,next) {


    /**
     * Response settings
     * @type {Object}
     */
    var responseSettings = {
        "AccessControlAllowOrigin": req.headers.origin,
        "AccessControlAllowHeaders": "Content-Type,X-CSRF-Token, X-Requested-With, Accept, Accept-Version, Content-Length, Content-MD5,  Date, X-Api-Version, X-File-Name",
        "AccessControlAllowMethods": "POST, GET, PUT, DELETE, OPTIONS",
        "AccessControlAllowCredentials": true
    };

    /**
     * Headers
     */
    res.header("Access-Control-Allow-Credentials", responseSettings.AccessControlAllowCredentials);
    res.header("Access-Control-Allow-Origin",  responseSettings.AccessControlAllowOrigin);
    res.header("Access-Control-Allow-Headers", (req.headers['access-control-request-headers']) ? req.headers['access-control-request-headers'] : "x-requested-with");
    res.header("Access-Control-Allow-Methods", (req.headers['access-control-request-method']) ? req.headers['access-control-request-method'] : responseSettings.AccessControlAllowMethods);

    if ('OPTIONS' == req.method) {
        res.send(200);
    }
    else {
        next();
    }


});

【讨论】:

  • 一般来说,对于 CORS,服务器是否必须允许 所有 标头(内容、内容长度、引用者等)存在于现实中,即非选项,请求?
  • @KevinMeredith 不,您不必允许所有标头,您可以只允许您需要的内容,甚至可以限制为一个域。
  • 我怎么知道我需要什么?
  • 感谢您的好回答 :)
  • 我很困惑,如果端点是通过http基本身份验证保护的,为什么我不需要对端点进行身份验证?
【解决方案2】:

为了发出 CORS 请求,必须在请求中添加标头以及他需要检查在 Apache 中启用了 mode_header 的标头。

在 Ubuntu 中启用标头:

sudo a2enmod headers

让 php 服务器接受来自不同来源的请求:

Header set Access-Control-Allow-Origin *
Header set Access-Control-Allow-Methods "GET, POST, PUT, DELETE"
Header always set Access-Control-Allow-Headers "x-requested-with, Content-Type, origin, authorization, accept, client-security-token"

【讨论】:

    猜你喜欢
    • 2019-01-07
    • 2013-09-01
    • 2015-09-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-24
    • 1970-01-01
    相关资源
    最近更新 更多