简体   繁体   中英

Secure web API with token

I need help to understand how to secure an API.

I am working on a project based on a RESTful API with a JSON response.

I have a web application and a mobile application which send requests like this:

http://my-server.com/api/v1/products

with a protocol (GET, POST, PUT, and DELETE) and eventually parameters.

My concern is to secure these calls, from both applications. Today I am just checking if this is an Ajax call:

$method = $_SERVER['REQUEST_METHOD'];

    if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest')
    {
        if ($method == 'GET')
        {
            return $data = $this->stores_model->get_all($select);
        }
    }

But mobile does not send xmlhttprequest, right?

I think I have to check a token stored in the session or locally for the mobile. I have also seen some points about the CSRF token, regenerate each time.

This is all I know about security. How do I get to understand more regarding my architecture?

This is a very deep topic, but first of all you should have SSL installed on your server. I think this is a starting point for the security.

For your JavaScript and browser clients, you can enable cors on your API. You can get more information about cors here .

For application clients, you can consider to implement OAuth . OAuth 2 is widely used these days, easy to implement but you can also go with OAuth 1. Check their differences and see which one suits for your project. You can find a good comparison here about them. There are good implementations of them out there, so check them out. One example for the OAuth 2 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM