简体   繁体   中英

Token based authentication for PHP

I am trying to implement an authentication for an API with private & public key.

What I want to do is provide a private key, hash some data with it and send the hash in a header, then rehash the same data again on the server for comparison.

What I'm having trouble with it is, what kind of data should I hash, the request URI, the content type and maybe the content itself, but what when the request is GET and there is no content.

Will hashing any data with the private key will be secure enough, or do I need to do something special?

  1. As stated in the comment, you don't want public/private key pairs here. What you want is a proof of identity. The client will give you their username/id (they'll claim an identity), and you need additional proof that it's really them. For this purpose they send a secret which only they are supposed to know. That's a simple token.

  2. You want to avoid sending this token over the wire back and forth. Remember it's a secret and should stay as secret as possible. Instead what you ask the client to send is an indirect proof; you ask them to sign the request.

  3. Signing a request means they simply hash the contents of the request with a MAC algorithm , their secret token being the key to the hash.

    • What parts of the request to hash you decide; everything that's included in the hash is unspoofable by 3rd parties, but you should refrain from requiring everything to be hashed since HTTP headers may be added or removed at various stages of the request.
    • To avoid replay attacks, hash the date of the request (and require the date be sent with the request). Don't accept requests past a certain expiry date. Alternatively include an ever changing token, if that's feasible.
    • Make sure the hash is easily reproducible, eg require sorting of the data to be hashed.
    • You should include the URL in the hash; if you do, it doesn't matter whether there's body data or not. The URL + the date/token from above is perfectly sufficient already to form a MAC.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM