In this article, we will be looking into how to login and logout a user who is using token authentication to access your REST APIs. This is the second part of a series, you can read the first one here.

What are we trying to achieve?

Laravel generally expects an “api_token” in the “users” table, against which it compares the token sent by the user with each request (it can be in the header or in the url). And that is the extent till which the framework supports you in this case. How the api token gets to the user, is for the developer to the decide.

While integrating a back-end application with front-end frameworks like Angular or Backbone, I expect the following behavior –

  • The front-end sends a login request with the username (or email) and password.
  • The server authenticates the user and sends back a token if authentication succeeds.
  • The front-end uses the token for the subsequent requests to access the REST APIs.
  • The front-end sends a logout request.
  • The server invalidates the token.

Login: The Implementation

I have tried to use the AuthenticatesUsers trait and override the web login functionalities, but it is just too much work. So I prefer to just go ahead and create my own controller – Api\LoginController.php.

The “login” method will be quite simple. It will authenticate the user by the credential sent, create a fresh api token, save it in the database and send back the details in the response.

The corresponding route in routes/api.php.

Now the login can be tested by sending a POST request with credentials in json format in the request body, like :

Note: Chrome extension Postman is a wonderful tool for testing REST APIs.

Exception Handling:

Let us now handle the usecases where the user sends wrong email/password. The client of course will be expecting the response in json format. To handle all the response I generally add a simple utility method in the base class (Controller.php) –

And change the login method to handle the exception paths

Logout

Logging out will of course do just the opposite and set null to the api_token of the authenticated user.

Add route

And we are done.

Nandini is a Web Developer and a blogger who loves tinkering with new technologies, frameworks and devices. When not in front of her computer she likes to travel, read and spend time gardening.

REST with Laravel 5.4 – Part 2: Login & Logout
Tagged on:     

Leave a Reply

Your email address will not be published. Required fields are marked *