首页 文章

跨源请求被阻止的Symfony / AngularJS

提问于
浏览
0

我正在尝试使用Angular从我的Symfony API获取数据时遇到错误,并返回JSON:

“阻止跨源请求:同源策略禁止在http://localhost:8000/customers读取远程资源 . (原因:缺少CORS标头'Access-Control-Allow-Origin') . ”

这是完整结果的屏幕截图:enter image description here

我知道这个问题已被多次询问,但我找不到合适的答案 .

当我不尝试在api控制器中检索$ session时,它可以工作,我得到了我需要的所有数据,但它没有,这是我的api控制器:

/**
 * @Rest\View(statusCode=Response::HTTP_CREATED)
 * @Rest\Get("/customers")
 */

/**
 * @Rest\View(statusCode=Response::HTTP_CREATED)
 * @Rest\Get("/index")
 */
public function getIndexAction(Request $request)
{
    $loginad = $this->getUser()->getUsername();

    $nom_ad = "******";
    $port_ad = ******;
    $compte_ad = "*******";
    $password_ad = "******";
    //parcours de l'AD
    // Connexion LDAP
    $ldapconn = ldap_connect($nom_ad, $port_ad)
    or die("Impossible de se connecter au serveur LDAP $nom_ad");
    if ($ldapconn){
        $ldapbind = ldap_bind($ldapconn, $compte_ad, $password_ad)
        or die("Impossible de se binder au serveur LDAP $nom_ad");
        if($ldapbind){
            $employeeID = false;
            $dn = "OU=CER35,DC=CeRNum,DC=dom";
            $filter="(samAccountName=$loginad)";
            $justtheseattributes = array( "ou", "sn", "givenname", "mail", "employeeid", "samaccountname");
            $sr=ldap_search($ldapconn, $dn, $filter, $justtheseattributes);
            $info = ldap_get_entries($ldapconn, $sr);
            for ($i=0;$i<$info["count"];$i++) {
                $employeeID = $info[$i]["employeeid"][0];
            }
            if (!$employeeID) {
                $dn = "OU=CER56,DC=CeRNum,DC=dom";
                $filter="(samAccountName=$loginad)";
                $justtheseattributes = array( "ou", "sn", "givenname", "mail", "employeeid", "samaccountname");
                $sr=ldap_search($ldapconn, $dn, $filter, $justtheseattributes);
                $info = ldap_get_entries($ldapconn, $sr);
                for ($i=0;$i<$info["count"];$i++) {
                    $employeeID = $info[$i]["employeeid"][0];
                }
            }
        }
    }

    $agent = $this->get('doctrine')
        ->getRepository('CERAgentBundle:Agent', 'agent')
        ->findByCode($employeeID);

    $session = new Session();
    $session->set('agent', $agent);

    $formatted = [
        'civilite' => $agent[0]->getCivilite(),
        'prenom' => $agent[0]->getPrenom(),
        'nom' => $agent[0]->getNom()
        ];

    return new JsonResponse($formatted);
}

因此,当我调用“localhost:8000 / index”时,用于cas服务器身份验证的捆绑包也会调用https url,以便用户可以向Intranet的公司验证自己,完成后,他最终可以从localhost:8000 / index检索结果

这是我的Angular控制器:

angular.module('frontProfilDeveloppementApp')
.controller('ClientsCtrl', function ($scope, $http){
    $http.get('http://localhost:8000/customers')
        .then(function (data) {
            $scope.result = data;
        });
});

nelmio_cors包配置:

nelmio_cors:
    defaults:
        allow_credentials: true
        allow_origin: ['*']
        allow_headers: ['*']
        allow_methods: ['POST', 'PUT', 'GET', 'DELETE']
        max_age: 3600
        hosts: []
        origin_regex: false

CAS捆绑配置:

p_rayno_cas_auth:
server_login_url: https://extranet-authentification-******/cas-a3net/
server_validation_url: https://extranet-authentification-*****/cas-a3net/serviceValidate
server_logout_url: https://extranet-authentification-****/cas-a3net/logout

(security.yml):

security:
providers:
    cas:
      id: prayno.cas_user_provider
role_hierarchy:
      ROLE_ADMIN:       ROLE_USER
      ROLE_SUPER_ADMIN: ROLE_ADMIN

firewalls:
    dev:
        pattern: ^/(_(profiler|wdt)|css|images|js)/
        security: false
    main:
        anonymous: ~
        logout: ~
        guard:
            authenticators:
                - prayno.cas_authenticator

access_control:
    - { path: /index, roles: ROLE_USER}

我认为我的API没有设置与angular do相同的 Headers ,因此浏览器不允许提取 .

是否可以直接从Angular控制器设置头选项,因此它可以匹配api控制器?

谢谢你的帮助 .

2 回答

  • 0

    您可以禁用标头 . 解决方案是https://www.youtube.com/watch?v=uDy_cvf4nDg&feature=youtu.be

  • 0

    您应始终从Symfony返回响应的实例,而不是直接返回$ customers结果集 .

    以下是如何完成的示例:返回新的JsonResponse($ customers,200,array('Access-Control-Allow-Origin'=>'*'));

    您也可以在这里找到更多详细信息 .

    AJAX Cross-domain on symfony2

相关问题