Skip to content
Advertisement

how does this protect against csrf attacks?

I’m working on making my opencart project and used This Article to write custom apis.

It uses this block of code to do a security check against csrf attacks:

    if (isset($this->request->server['HTTP_ORIGIN'])) {
      $this->response->addHeader('Access-Control-Allow-Origin: ' . $this->request->server['HTTP_ORIGIN']);
      $this->response->addHeader('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS');
      $this->response->addHeader('Access-Control-Max-Age: 1000');
      $this->response->addHeader('Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With');
    }

My question is how is that going to protect against csrf attacks according to the article? It seems it just sets Access-Control-Allow-Origin header to whatever domain the request is coming from

Advertisement

Answer

This does not protect against CSRF attacks at all, because you are allowing all origins! It is the same writing as

Access-Control-Allow-Origin: *

You should create a list of acceptations like below, which ensures only those in the list are granted for CORS.

Scheme, Domain and Port are the important information to compare against. Port can be omitted, when defaults are to be used like http=80 and https=443.

if(in_array($this->request->server['HTTP_ORIGIN'], [
    'http://xxx-domain.org',
    'https://example.org',
    'http://localhost:8888',
])) {
    $this->response->addHeader("Access-Control-Allow-Origin: {$this->request->server['HTTP_ORIGIN']}");
    $this->response->addHeader('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS');
    $this->response->addHeader('Access-Control-Max-Age: 1000');
    $this->response->addHeader('Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With');
}
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement