token based authentication in php

前端 未结 3 963
误落风尘
误落风尘 2021-02-14 06:17

I have an REST service on my webserver, written in php. I was wondering, what would be the best authentication (besides basic http access authentication). I\'ve heared of token-

3条回答
  •  滥情空心
    2021-02-14 06:25

    It can be done either way, and values in a GET request aren't really any more visible than values in a POST request. If anybody can "see" (i.e. intercept) the request, he can see everything you're sending. In the end an HTTP request is just a bunch of HTTP headers possibly followed by a body. The URL is send in the first GET /foo/bar HTTP/1.1 line, other values are just send in different, following lines.

    So it's up to you where you expect your authentication token to be send. You can require it to be a query parameter that is appended to every request:

    GET /foo/bar?user=123456&token=abcde...
    

    To really use the HTTP protocol as intended though, you should use the Authorization HTTP header:

    Authorization: MyScheme 123456:abcde...
    

    The content of this header is entirely up to you. It usually specifies an authorization method like Basic, followed by whatever you want to require for authentication. This can simply be the username and password, a hash of them, an opaque token the client has obtained at some point or anything else really.

    I'd recommend a token system or a request signing system, with the latter being very much preferred. In a request signing system, the client has to obtain a token from you. It then sends a hash of this token and certain characteristics of the request to authenticate the request, e.g. sha1(Token + Timestamp + Request URL + Request Body). Your server can validate this without the client having to send the token in plain text on each request.

    How do I make the token only valid for a specific time?

    You save the token server-side with an expiration timestamp and check against it.

提交回复
热议问题