0

I am currently facing an error while trying to fetch datas with Angular from my Symfony API which return JSON:

"Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:8000/customers. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing)."

here is a screenshot of the full result:

enter image description here

I know the question have been multiple times asked but I couldn't find a working answer.

When I don't try to retrieve the $session in the api controller it works and I get all the datas I need, however it don't, here is my api controller:

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

So when I call "localhost:8000/index", a bundle for CAS server authentication also call an https URL so the user can authenticate themselves to the intranet's company, that done, they can finally retrieve results from localhost:8000/index

Here is my Angular controller:

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

the nelmio_cors bundle config:

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

CAS bundle configuration:

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}

I think my API doesn't set the same header as angular do, so the browser don't allow the fetching.

Is it possible to set headers option directly from the Angular controller, so it could match the api ones?

2
  • You can't control the headers from angular!. You need to disable web security of google chrome for testing Commented Jul 10, 2017 at 13:16
  • It works if i disable security (my bad, edited) But anyway, i don't want to disable security, i want to add the right header (if possible)! Commented Jul 10, 2017 at 13:37

2 Answers 2

0

You should always return an instance of a Response from Symfony and not your $customers result set directly.

Here's an example of how it can be done: return new JsonResponse($customers, 200, array('Access-Control-Allow-Origin'=> '*'));

You can find additional details here as well.

AJAX Cross-domain on symfony2

Sign up to request clarification or add additional context in comments.

10 Comments

Can you paste the response headers from the Chrome Dev Tools Network Tab? (for the request that we're interested in) Is that header set from symfony?
"Connection : Keep-Alive Content-Length : 0 Content-Type : text/html;charset=UTF-8 Date : Tue, 11 Jul 2017 13:11:46 GMT Keep-Alive : timeout=15, max=100 Location : extranet-authentification-cerfrance.35-56.fr/cas-a3net/… %2Findex Server : Apache"
i think i paste the wrong one, here's the response : Access-Control-Allow-Cred... true Access-Control-Allow-Orig... localhost Cache-Control no-cache, private Connection close Content-Type text/html; charset=UTF-8 Date Tue, 11 Jul 2017 13:28:21 GMT Host localhost:8000 Location extranet-authentification-cerfrance.35-56.fr/cas-a3net/… %2Findex Set-Cookie PHPSESSID=qg5cle767utjvsdcf5nc7tsmi5; path=/; HttpOnly X-Debug-Token 0b81f4 X-Debug-Token-Link localhost:8000/_profiler/0b81f4 X-Powered-By PHP/5.5.38
You must be having some cache issue or another quirk because I just tested on my localhost and using that line the header is properly set in the response. HTTP/1.1 200 OK Date: Tue, 11 Jul 2017 13:29:15 GMT Server: Apache/2.4.7 (Ubuntu) X-Powered-By: PHP/5.5.9-1ubuntu4.21 Access-Control-Allow-Origin: * Cache-Control: no-cache Content-Length: 23 Keep-Alive: timeout=5, max=100 Connection: Keep-Alive Content-Type: application/json. I think you should remove the contents of your cache folder (for both dev & prod envs) , warm the cache and try again.
How could i know is the header is set from Symfony? it's a symfony url that call a https url for cas-auth.
|
-1

You can disable headers. Solution is in https://www.youtube.com/watch?v=uDy_cvf4nDg&feature=youtu.be

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.