RESTful authentication - resulting poor performance on high load?

前端 未结 3 1002
孤街浪徒
孤街浪徒 2020-12-31 06:02

For a RESTful web service we say that that the server shouldn\'t store any state. Now for every request the \'user\' must be authenticated and must have an authorization for

3条回答
  •  不知归路
    2020-12-31 06:37

    The spirit of REST is statelessness. This does not mean that client state cannot be persisted by a service, but in practice it does mean that client state held in memory by a server is generally a bad thing.

    Instead of keeping authentication data in memory, or going to the DB for verification every time, what you can do is keep a function in memory (i.e., code) that is used to crypt/decrypt user information. This is a technique that is also suggested by:

    What should I store in cookies to implement "Remember me" during user login

    So, for example, what you would do is the following:

    1. When a client first contacts the service, it has no cookie.
    2. You issue a cookie that contains user info and "sign" it using your function (which all servers, running your code, can do)
    3. When the client contacts the service again, you check if it has a cookie; if not, repeat (2).
    4. However, if it does have a cookie, you attempt to decrypt (again, using your single function which is replicated across your infrastructure) and verify that you can unwrap and digest that user ID info.
    5. This verifies the user and gives you identity info, all without going to the DB more times than is necessary. And it's RESTful.

    Keep in mind that this "function" I describe is not a novel thing - it's a standard secure hash, but one that is based off a unique private key that only your collective servers know about. And you can rotate such a key, etc. as needed.

提交回复
热议问题