• 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
ci3 cors doesn't works

#1
Question 
Hallo i have a tasks from college to create elearning (me as backend) but i have problem when i deploy it to vps it's always getting error that said 'CORS NOT ALLOWED'.

Im using:
  • Codeigniter3
  • Library ci rest server (criskagruice)
  • JWT
  • NGINX
  • simple login xhr with github.io
My structure of code is ALL ENDPOINT/Class (.php) extends to Token.php extends to REST_Controller.php (library).

Here are ma code:

Login page (github.io)

Code:
  let xhr = new XMLHttpRequest();
  xhr.open('POST', 'https://IP_VPS/elearning/auth/login');
  xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
  xhr.onreadystatechange = function() {
    if(this.readyState == 4 && this.status == 200) {
      console.log(this.response);
    }
  }
  xhr.send('email='+email.value+'&password='+password.value);


Token.php (child of REST_Controller)

Code:
<?php
// load library rest server
use Restserver\Libraries\REST_Controller;
require APPPATH . 'libraries/REST_Controller.php';
require APPPATH . 'libraries/Format.php';

// load library rest server
use \Firebase\JWT\JWT;
require APPPATH . 'libraries/JWT.php';
require APPPATH . 'libraries/BeforeValidException.php';
require APPPATH . 'libraries/ExpiredException.php';
require APPPATH . 'libraries/SignatureInvalidException.php';

defined('BASEPATH') OR exit('No direct script access allowed');

class Token extends REST_Controller {

  private $_secretkey = 'elearning';
  private $_token;

  public function __construct(){
    header("Access-Control-Allow-Origin: *");
    header('Access-Control-Allow-Credentials: true');
    header('Access-Control-Max-Age: 86400');
    parent::__construct();
    $this->load->model('m_users', 'user');
  }
......................................................

} ?>


Auth.php (child of Token.php)

Code:
<?php
require APPPATH . 'controllers/api/Token.php';

defined('BASEPATH') OR exit('No direct script access allowed');

class Auth extends Token {

  public function __construct() {
    parent::__construct();
    $this->load->library('form_validation');
  }

  public function login_post() {
    // terima data dari form
    $email    = $this->post('email');
    $password = $this->post('password');

    $this->form_validation->set_rules('email', 'Email', 'required|valid_email');
    $this->form_validation->set_rules('password', 'Password', 'required');

    // form validation false akan merespon input form yang false
    if (!$this->form_validation->run()) {
      $form_error = $this->form_validation->error_array();
      $this->response([
        'status'  => FALSE,
        'message' => 'form tidak lengkap',
        'error'   => ['form_error' => $form_error]
      ], 404);
    }



    //  -------- AKAN DIEKSEKUSI JIKA FORM INPUT LENGKAP ------

    // cek apakah user ada pada database
    $user_detail = $this->user->getUser($email);

    if (!$user_detail) {
      $this->response([
        'status' => FALSE,
        'message' => 'Email/Password Salah'
      ], 404);
    }

    // response 404 jika user tidak ada
    $hash_password = $user_detail['password'];

    if ( !password_verify($password, $hash_password) ) {
      $this->response([
          'status' => FALSE,
          'message' => 'Email/Password Salah',
      ], 404);
    }

    // menyiapkan token
    $token = parent::generateToken($user_detail);

    // menyapkan response json
    $response = [
      'status'  => TRUE,
      'message' => 'berhasil login',
      'data'    => [
                    'name' => $user_detail['name'],
                    'email' => $user_detail['email'],
                    'user_role' => $user_detail['type'],
                    'token' => $token
                  ]
    ];

    // response 200 user berhasil masuk
    $this->response($response, 200);
  }

}
?>


/etc/nginx/sites-available/default



Code:
location / {
        # First attempt to serve request as file, then
        # as directory, then fall back to displaying a 404.
        #try_files $uri $uri/ =404;

        if ($request_method = 'OPTIONS') {
    add_header 'Access-Control-Allow-Origin' '*';
        add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
        #
        # Custom headers and headers various browsers *should* be OK with but aren't
        #
        add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range';
        #
        # Tell client that this pre-flight info is valid for 20 days
        #
        add_header 'Access-Control-Max-Age' 1728000;
        add_header 'Content-Type' 'text/plain; charset=utf-8';
        add_header 'Content-Length' 0;
        return 204;
     }
     if ($request_method = 'POST') {
        add_header 'Access-Control-Allow-Origin' '*';
        add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
        add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range';
        add_header 'Access-Control-Expose-Headers' 'Content-Length,Content-Range';
     }
     if ($request_method = 'GET') {
        add_header 'Access-Control-Allow-Origin' '*';
        add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
        add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range';
        add_header 'Access-Control-Expose-Headers' 'Content-Length,Content-Range';
     }
    }

    # pass PHP scripts to FastCGI server
    #
    location ~ \.php$ {
        include snippets/fastcgi-php.conf;
    #
    #    # With php-fpm (or other unix sockets):
        fastcgi_pass unix:/var/run/php/php7.2-fpm.sock;
    #    # With php-cgi (or other tcp sockets):
    #    fastcgi_pass 127.0.0.1:9000;
    }

    # codeigniter elearning
    location /elearning {
        try_files $uri $uri/ /elearning/index.php;
    }

    # deny access to .htaccess files, if Apache's document root
    # concurs with nginx's one
    #
    location ~ /\.ht {
        deny all;
    }

Im actually super new at creating API & deploying and don't know what should i do now. In these code above which is wrong ? Thanks Anyway Smile Smile
Reply

#2
I believe your problem is in the:

PHP Code:
// change thjis
header("Access-Control-Allow-Origin: *");

// should be your web site url
header("Access-Control-Allow-Origin: https://www.your-web-site.com"); 

READ:

Cross-Origin Resource Sharing (CORS)
What did you Try? What did you Get? What did you Expect?

Joined CodeIgniter Community 2009.  ( Skype: insitfx )
Reply

#3
(11-30-2020, 12:16 PM)InsiteFX Wrote: I believe your problem is in the:

PHP Code:
// change thjis
header("Access-Control-Allow-Origin: *");

// should be your web site url
header("Access-Control-Allow-Origin: https://www.your-web-site.com"); 

READ:

Cross-Origin Resource Sharing (CORS)

i had tried this and still doesn't works ?. Im so confused what should i do now
Reply

#4
Not sure why your still getting an error maybe something with the server configuration.

I run all my cors stuff in my .htaccess file.


.htaccess:

Code:
    # Add Font Types
       AddType application/vnd.ms-fontobject .eot
       AddType application/x-font-ttf        .ttf
       AddType application/x-font-opentype   .otf
       AddType application/font-woff         .woff
       AddType application/font-woff2        .woff2

       # Add Image Types
       AddType image/svg+xml .svg .svgz .jpg .png .ico

       <IfModule mod_headers.c>
           <FilesMatch "\.(ttf|ttc|otf|eot|woff|woff2|svg|svgz|jpg|png|ico|font.css|css|js)$">
               #Header set Access-Control-Allow-Origin "*"
               Header add Access-Control-Allow-Origin: "https://admin.local/"
            Header add Access-Control-Allow-Methods: "GET,POST,OPTIONS,DELETE,PUT"
            Header add Access-Control-Allow-Headers: "Upgrade-Insecure-Requests"
           </FilesMatch>
       </IfModule>

That's how I do mine but I'm running apache sever.
What did you Try? What did you Get? What did you Expect?

Joined CodeIgniter Community 2009.  ( Skype: insitfx )
Reply

#5
CORS is ... fun ... In my current project I have a Sencha Ext JS front-end and a CI 4.0.4 back-end and it's working fine.

Have you checked the debugger in the browser for any messages? 
In Chrome you have to select "All" under Network tab to see the OPTIONS requests (they don't show up under XHR for some reason). 
I also use Charles proxy to really see what's going on.

I route all my OPTIONS request to a single function that returns this:
PHP Code:
        return $this->response->setHeader('Access-Control-Allow-Methods''DELETE, POST, GET, PUT, OPTIONS')
            ->setHeader('Access-Control-Allow-Headers',
                'Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With')
            ->setHeader('Access-Control-Max-Age''3600')
            ->setHeader('Access-Control-Allow-Origin''https://my.frontend.url/')
            ->setHeader('Access-Control-Allow-Credentials''true')
            ->setStatusCode(204); 

If the browser is happy with that it will send the actual request.


For my front-end the withCredentials needs to be set on the XHR request (https://developer.mozilla.org/en-US/docs...redentials) and also cors to generate XDomainRequests (https://docs.sencha.com/extjs/7.2.0/mode....Ajax.html)

Remember that cookies could also be hard to get working cross-domain. I'm using Bearer Authorization instead.

Good luck! /Mattias
Reply


Digg   Delicious   Reddit   Facebook   Twitter   StumbleUpon  


  Theme © 2014 iAndrew  
Powered By MyBB, © 2002-2021 MyBB Group.