AngularJS $http,CORS 和 http 认证

因为在 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 以及 username 和 password 请求。

 /**
*  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");

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

/**
*  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();
}
?>

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

142385 次浏览

No you don't have to put credentials, You have to put headers on client side eg:

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

And and on server side you have to put headers to this is example for 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();
}




});

For making a CORS request one must add headers to the request along with the same he needs to check of mode_header is enabled in Apache.

For enabling headers in Ubuntu:

sudo a2enmod headers

For php server to accept request from different origin use:

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"