dsfs21312 2016-03-17 09:40
浏览 39
已采纳

CORS - API身份验证:会话(CSRF安全) - 解决方案?

I am currently using the CORS method (ReWriting my external requests from example.com/api?param=args to example.com/api/public/api.php?param=args) and sending the get Request like so:

$.get('http://www.example.com/api'), { param: "args" })
    .done(function (data) {
        alert(data);
    });

This works absolutely fine and I can now Cross-Domain reference with Requests and responses to my API software.

I am now wondering, I set up a test request to try achieve a Session.

session_start();
if(isset($_GET['store'])):
    $_SESSION['key'] = $_GET['store'];
elseif(isset($_GET['show'])):
    echo $_SESSION['key'];
endif;

When I go to the link directly in my browser, this works fine however, when I send a request from the external domain, the second request seems to "forget" the Session key I stored.

Code:

$.get('http://www.example.com/api'), { store: "test" })
    .done(function () {
        $.get('http://www.example.com/api'), { show: "args" })
            .done(function (data) {
               alert(data);
        })
    });

Data is undefined

Is there a way I can make the server that is sending the requests actually "save" or "remember" the session on the API server or is there a way I can achieve this by using a work around?

Note that the API will be used by multiple people - like a plugin - and each key will be actually added once they send a Register param as a request with the admin details of there account so I need some sort of authentication to using the API and cannot actually think of a way around not using Session's or getting it to work using session's.

Please note also, if I am using session (as you can see like that), it creates a CRSF attack. Is there a work around this also?

  • 写回答

1条回答 默认 最新

  • doulvyi2172 2016-03-17 09:44
    关注

    By default, credentials (such as cookies) are not sent on cross-origin requests because they trigger preflight requests.

    The jQuery documentation describes how to enable credentials:

    $.ajax({
       url: a_cross_domain_url,
       xhrFields: {
          withCredentials: true
       }
    });
    

    cannot actually think of a way around not using Session's

    Pass an auth token back in the body of the response. Read it with JS. Have the JS include it in each request.

    Please note also, if I am using session (as you can see like that), it creates a CRSF attack. Is there a work around this also?

    Don't use the * origin in your Access-Control-Allow-Origin header. Only allow trusted sites to use your API.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?