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.

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

报告相同问题?

悬赏问题

  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥15 stable diffusion
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿