Skip to content

Instantly share code, notes, and snippets.

@MattWohler
Last active January 31, 2016 22:53
Show Gist options
  • Save MattWohler/bee385cf202c773a02bc to your computer and use it in GitHub Desktop.
Save MattWohler/bee385cf202c773a02bc to your computer and use it in GitHub Desktop.
Laravel 5.2: Authentication Guard API Token

Laravel 5.2: Authentication Guard API Token

Recently, Jacob Bennett beat me to the punch when after much digging, came to the realization that I needed to utilize Laravel's Token Guard, yet there were no resources to be found on implementing such feature as the Laravel Documentation leaves much to be desired.

I highly recommend you take a look at Jacob's API Token Authentication in Laravel 5.2 article, as it provides great insight onto the subject, as well as an active discussion in the comment section.

However, there is a variation on the popular suggestion, as in the case of my implementation.

For the setup, I wanted a custom HTTP Header with key to be sent on every request for authentication.

Is the key a match? Set the Auth user to said User entity with matching key.

The Implementation

Creating a new Middleware

Create a new middleware for the purpose of authenticating the User by Token.

Inject the AuthManager into Constructor

I'm not the biggest fan of using Facades, so I wanted to use the AuthManager directly.

use Illuminate\Auth\AuthManager;
public function __construct(AuthManager $auth) {
    $this->auth = $auth;
}

Pass the AuthManager the request and call upon the user

public function handle($request, Closure $next) {
    $user = $this->auth->setRequest($request)->user();

    if ($user) return $next($request);
    
    return response('Unauthorized.', 401);
}

This really IS where the magic happens. I suppose it's poorly built and will be improved upon further releases, however it gets the job done. Laravel does make you conform to their standards if you'd like to utilize the Token Guard.

In order for this to work, several things must be present in your Request & Application.

  • First, your Guard model must have a field named api_token.
  • Second, the Authentication header must conform to the Bearer Token implementation:

Authorization: Bearer w3XqyCNmbgU4F3PBCPglRd1qj7bS8tsY

That's it. When the user function is invoked, the Token Guard takes the header passed in from the request object, parses it for the key, and then checks the users.api_token table for a match, if found, it Auth's the user.

If anyone has any better architected strategies to implement this, please let me know in the comments below!

ps. After thinking about it, I assume you could create your own Token Guard implementation as long as it implements the Illuminate\Contracts\Auth\Guard contract :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment