How much state can I save in session variables for

2019-07-17 20:47发布

I'm coding up a REST/RPC API for a web app that I'm creating. From what I've learned it seems like one of the core ideas behind REST is to not maintain any state. That said I find myself doing things like marking a session as authenticated on the server side of things and this feels like saving state. How far should I take this practice? Where should I draw the line? There are other things that would be really convenient to save as part of the session's variables but I'm wondering how do I know when I shouldn't or shouldn't do this.

I hope this is the right venue to ask this question. I debated on whether or not to post it in programmers but this just felt more appropriate.

UPDATE:

I'm told that using a ticketing system is better than using session variables to maintain things like auth information. Could someone include and answer that has a very highly description of how such a ticketing system would work?

1条回答
smile是对你的礼貌
2楼-- · 2019-07-17 21:35

You are correct - REST calls are ideally stateless, and storing something in a session variable, and using that for the REST call, is anathema. You can't, for instance, guarantee that a RESTful client can even send the cookie information necessary for the session variables.

If you need authentication, then you should have REST calls that return something like a ticket, then the REST caller would send that ticket as part of another call.

UPDATE For a ticketing system, you generally want to use the same auth or similar auth system. For instance, if you require a user name and password, you might want the ticket request to POST that. A ticket is a GUID that is passed on subsequent calls. The ticket on the server can be stored in session, or in a DB (I typically have a TICKETS table, with things like expiration dates).

$result = file_get_contents('http://site.com?action=auth&user=matt&password=pass');
// parse $result XML for ticket or auth error
// subsequent calls...
$result = file_get_contents('http://site.com?action=getSomething&ticket=" . $ticket);

QuickBase works this way - you send an API_Auth action with a username, password and api app token, and get a ticket in return. Then you pass your api app token and the ticket on subsequent calls - both GET requests and POST sends.

查看更多
登录 后发表回答