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

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.

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

    报告相同问题?

    悬赏问题

    • ¥20 arcgis制做交通拥堵时变图
    • ¥15 AD20 PCB板步线 这个要怎么步啊
    • ¥50 关于《奇迹世界》1.5版本,数据修改
    • ¥15 请问这个问题如何解决(关键词-File)
    • ¥50 visual studio 2022和EasyX图形化界面
    • ¥15 找一下报错原因,纠正一下
    • ¥50 Cox回归模型Nomogram图制作报错
    • ¥20 SQL如何查询多级用户的数据
    • ¥15 给车牌识别代码加一个识别轮廓长宽比的代码
    • ¥30 商品价格预测的transformer模型优化