0

I am new to php.I want to build a token based authentication in php without using any external library which generates a token and make it valid for 10 days so that I can pass that token to anybody and they can access certain api by passing token in url parameter.

I am able to generate a token but don't know how to make it valid for 10 days after that it will expire. And user will not be able to access it further. This is how I am generating token.

$token = bin2hex(random_bytes(16));

Any help would be appreciated.

Asdee gen
  • 33
  • 8
  • 1
    you need to maintain a "state" for the token. For example put it in persistent storage (e.g. a redis cache with persistence enabled) and check if it's still valid when used. – apokryfos May 09 '19 at 08:09
  • Can't I do the same only using php. I don;t want to use any other tool. I am learning php. – Asdee gen May 09 '19 at 08:11
  • [The web is stateless](https://stackoverflow.com/questions/13200152/why-is-it-said-that-http-is-a-stateless-protocol) so you need *some* way to persistently maintain information; the closest you'll get *just* using PHP would be to set a cookie. – CD001 May 09 '19 at 08:17
  • Your persistent storage can be a file, it doesn't have to be redis, I mention redis because it supports expiring entries after a set amount of time so you don't have to do the checks manually – apokryfos May 09 '19 at 08:38
  • _“This is how I am generating token”_ - that so far is basically just an arbitrary random value, that alone and in itself is not really a token yet … If you do not want to store these tokens anywhere - then you need to include the info until when they are valid in the token value itself. To prevent users from manipulating it, you will either have to en- and decrypt this info - or you pass that part as plain text, and combine it with a hash of the value combined with a secret. – 04FS May 09 '19 at 08:53

0 Answers0