PHP cookies and member security

2019-05-19 07:00发布

问题:

I've created a forum which uses a PHP session when logged in to determine the user id, and cookies for log-term login.

I suppose I have two questions:

  1. Is this the best/securest method?
  2. Cookies can be added manually via the address bar with javascript, which is a huge security risk. Is there any way around this?

Thanks!

回答1:

First, make sure you are using https and not http. This will keep your traffic from getting sniffed and exploited.

Secondly, generate as random a value as possible to use as a token in the cookie. This is how many of the big sites do their user tracking. Have a map of token to user on the server side that tracks the identities. Remember: Anything that comes from the client is untrusted and could be tampered with.

Third, use an HMAC to make tampering much more difficult. You don't want users being able to brute force other tokens.

EDIT:

You may find these other SO questions/answers helpful as you build this system:

  1. Long details about creating and using tokens (doesn't necessarily have to be a REST service to be applicable): REST Web Service authentication token implementation

  2. Creating good tokens (don't use microtime): Is using microtime() to generate password-reset tokens bad practice