Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implement token for Laravel 4 RESTful API authentication

I'm a beginner to Laravel 4 framework and PHP.

Currently, I'm trying to do a simple authentication process between client application and server.

Below is my planned approach:

  1. Client logs in to server via GET request with username and password.

  2. Server validates and returns a token string if successful. The token string will be encoded (hashed?) with the username, password and expiration time.

  3. Client submits a request, including the given token. Server will validate token (decode it -> check username/password and expired time). If successful, it will process the client's request.

What is the best way to generate the token with the above parameters given, and decode it at the server side?

Thank you, and I appreciate your time and help.

like image 472
davidcoder Avatar asked Sep 18 '13 03:09

davidcoder


2 Answers

I don't think it is good idea to store user name and password encoded in some kind of token. Instead generate random token after successful login and store data related to the token on server side.

You may store record about each login into some table with columns token, user_id, valid_until. After each request, look for token in the database, check if it is still valid and use user_id for authentication.

You may think of token as one-time user and password, e.g. consider first 8 characters of token as temporary user name and the rest as password, if you feel uneasy about allowing access without password :)

Also you may want to run some cron job to remove expired records from database every day or so.

like image 134
Martin Komara Avatar answered Oct 05 '22 03:10

Martin Komara


You can use JWT JSON web Tokens for authentication to eliminate sessions and cookies completely. Similar approach is used by Facebook. Once you login with email and pwd you get a Web Token so even if its hacked you can't get the pwd from it. You can set a time limit to expire the token.

like image 42
rohitnaidu19 Avatar answered Oct 05 '22 03:10

rohitnaidu19