Skip to content

Instantly share code, notes, and snippets.

@JacobBennett
Last active March 15, 2025 10:04

Revisions

  1. JacobBennett revised this gist Oct 6, 2016. 1 changed file with 1 addition and 1 deletion.
    2 changes: 1 addition & 1 deletion gistlog.yml
    Original file line number Diff line number Diff line change
    @@ -1,2 +1,2 @@
    published: true
    preview: I was happy to find that Laravel 5.2 ships with a TokenGuard class that allows users to authenticate by sending an api_token along with their request, but the documentation on getting it to work is a bit thin, so here you go.
    preview: I was happy to find that Laravel 5.2 & 5.3 ships with a TokenGuard class that allows users to authenticate by sending an api_token along with their request, but the documentation on getting it to work is a bit thin, so here you go.
  2. JacobBennett revised this gist Jan 23, 2016. 1 changed file with 1 addition and 1 deletion.
    2 changes: 1 addition & 1 deletion blog.md
    Original file line number Diff line number Diff line change
    @@ -50,7 +50,7 @@ Just like when we called the middleware, we have to let Laravel know that we wan

    In the `App\Http\Middleware\Authenticate` middleware, you might want to change the following lines:

    > **Update**: Taylor merged my PR for this so any 5.2 installations should come with this by default now. Check out the current `Authenticate` Middleware [here](https://github.com/laravel/laravel/blob/master/app/Http/Middleware/Authenticate.php)
    > **Update**: This has been merged into 5.2. Check out the current `Authenticate` Middleware [here](https://github.com/laravel/laravel/blob/master/app/Http/Middleware/Authenticate.php)
    ```php
    // Original
  3. JacobBennett revised this gist Jan 23, 2016. 1 changed file with 3 additions and 3 deletions.
    6 changes: 3 additions & 3 deletions blog.md
    Original file line number Diff line number Diff line change
    @@ -48,10 +48,10 @@ Just like when we called the middleware, we have to let Laravel know that we wan

    ## Extras

    > **Update**: Taylor merged my PR for this so any 5.2 installations should come with this by default now. Check out the current `Authenticate` Middleware [here](https://github.com/laravel/laravel/blob/master/app/Http/Middleware/Authenticate.php)
    In the `App\Http\Middleware\Authenticate` middleware, you might want to change the following lines:

    > **Update**: Taylor merged my PR for this so any 5.2 installations should come with this by default now. Check out the current `Authenticate` Middleware [here](https://github.com/laravel/laravel/blob/master/app/Http/Middleware/Authenticate.php)
    ```php
    // Original
    if ($request->ajax()) {
    @@ -68,7 +68,7 @@ In the `App\Http\Middleware\Authenticate` middleware, you might want to change t
    }
    ```

    This will hopefully return a 401 status code to unauthorized API requests instead of redirect it to a login page.
    This will return a 401 status code to unauthorized API requests instead of redirect it to a login page.

    Lastly, if you are planning on primarily using the `TokenGuard` to authenticate requests, change the default guard in `config/auth.php` to be `api` instead of `web`. That should prevent you from having to tell Laravel to use the `api` version of the middleware or guard since Laravel will use by default what you have set in `config/auth.php`.

  4. JacobBennett revised this gist Jan 23, 2016. 1 changed file with 3 additions and 1 deletion.
    4 changes: 3 additions & 1 deletion blog.md
    Original file line number Diff line number Diff line change
    @@ -5,7 +5,7 @@ Knowing that this was going to be a tiny RESTful API and also knowing that Larav
    The problem for me came when I wanted to start associating those short urls with a user.

    Typically my applications have a UI and authentication is done through a simple login page. Obviously for a RESTful API, having a login page isn't ideal. Instead, my hope was to have users append an `api_token` to the end of their query string and use that to authenticate their request.
    I was happy to find that 5.2 also ships with a `TokenGuard`[link](https://github.com/laravel/framework/blob/master/src/Illuminate/Auth/TokenGuard.php) class that allows you to do exactly that, but the documentation on getting it to work was a bit thin, so here you go.
    I was happy to find that 5.2 also ships with a `TokenGuard`([link](https://github.com/laravel/framework/blob/master/src/Illuminate/Auth/TokenGuard.php)) class that allows you to do exactly that, but the documentation on getting it to work was a bit thin, so here you go.

    ## Set up Token based Authenticaton

    @@ -48,6 +48,8 @@ Just like when we called the middleware, we have to let Laravel know that we wan

    ## Extras

    > **Update**: Taylor merged my PR for this so any 5.2 installations should come with this by default now. Check out the current `Authenticate` Middleware [here](https://github.com/laravel/laravel/blob/master/app/Http/Middleware/Authenticate.php)
    In the `App\Http\Middleware\Authenticate` middleware, you might want to change the following lines:

    ```php
  5. JacobBennett revised this gist Jan 20, 2016. No changes.
  6. JacobBennett revised this gist Jan 20, 2016. No changes.
  7. JacobBennett revised this gist Jan 20, 2016. 1 changed file with 2 additions and 0 deletions.
    2 changes: 2 additions & 0 deletions gistlog.yml
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,2 @@
    published: true
    preview: I was happy to find that Laravel 5.2 ships with a TokenGuard class that allows users to authenticate by sending an api_token along with their request, but the documentation on getting it to work is a bit thin, so here you go.
  8. JacobBennett revised this gist Jan 20, 2016. 1 changed file with 9 additions and 5 deletions.
    14 changes: 9 additions & 5 deletions blog.md
    Original file line number Diff line number Diff line change
    @@ -1,11 +1,11 @@
    I recently had the need to write a small url shortening application. I am aware that this problem has been solved quite a few times before, but what is being a developer if not reinventing the wheel just for the heck of it? Custom CMS anyone?

    Knowing that this was going to be a tiny RESTful API and also knowing that Laravel 5.2 had API rate limiting built in, I was eager to give it a try.
    Taylor Otwell being Taylor Otwell shipped 5.2 with the rate limiting defaults set up out of the box and I had my application building out short url's in a matter of minutes.
    Knowing that this was going to be a tiny RESTful API and also knowing that Laravel 5.2 had [API rate limiting built in](https://mattstauffer.co/blog/api-rate-limiting-in-laravel-5-2), I was eager to give it a try.
    [Taylor Otwell](https://twitter.com/taylorotwell) being Taylor Otwell shipped 5.2 with the rate limiting defaults set up out of the box and I had my application building out short url's in a matter of minutes.
    The problem for me came when I wanted to start associating those short urls with a user.

    Typically my applications have a UI and authentication is done through a simple login page. Obviously for a RESTful API, having a login page isn't ideal. Instead, my hope was to have users append an `api_token` to the end of their query string and use that to authenticate their request.
    I was happy to find that 5.2 also ships with a `TokenGuard` class that allows you to do exactly that, but the documentation on getting it to work was a bit thin, so here you go.
    I was happy to find that 5.2 also ships with a `TokenGuard`[link](https://github.com/laravel/framework/blob/master/src/Illuminate/Auth/TokenGuard.php) class that allows you to do exactly that, but the documentation on getting it to work was a bit thin, so here you go.

    ## Set up Token based Authenticaton

    @@ -18,7 +18,7 @@ The first think you need to do is to add an `api_token` column to your `users` t
    $table->string('api_token', 60)->unique();
    ```

    **Note:** Be sure to assign an api_token to new users. Something like `str_random(60)` should be sufficient.
    **Note:** Be sure to generate and assign an api_token to new users. Something like `str_random(60)` should be sufficient.


    ### 2. Wrap your routes
    @@ -38,7 +38,7 @@ At this point, any routes wrapped with your `auth:api` middleware are only acces

    ### 3. Getting the User

    To get the authenticated user for this API request, use `Auth::user()` with a small addition.
    To get the authenticated user for this API request, use the following snippet:

    ```php
    Auth::guard('api')->user();
    @@ -70,3 +70,7 @@ This will hopefully return a 401 status code to unauthorized API requests instea

    Lastly, if you are planning on primarily using the `TokenGuard` to authenticate requests, change the default guard in `config/auth.php` to be `api` instead of `web`. That should prevent you from having to tell Laravel to use the `api` version of the middleware or guard since Laravel will use by default what you have set in `config/auth.php`.

    ## Wrapping Up

    Well there you have it, authenticating users to your api using nothing more than an `api_token` in the request and an `api_token` column on your user table. Hopefully this will save you the time it took me digging through the `TokenGuard` and [Issues](https://github.com/laravel/framework/issues/11782) to figure it out.

  9. JacobBennett revised this gist Jan 20, 2016. 1 changed file with 1 addition and 1 deletion.
    2 changes: 1 addition & 1 deletion blog.md
    Original file line number Diff line number Diff line change
    @@ -4,7 +4,7 @@ Knowing that this was going to be a tiny RESTful API and also knowing that Larav
    Taylor Otwell being Taylor Otwell shipped 5.2 with the rate limiting defaults set up out of the box and I had my application building out short url's in a matter of minutes.
    The problem for me came when I wanted to start associating those short urls with a user.

    Typically my applications have a UI and authentication is done through a simple login page. Obviously for a RESTful API, having a login page isn't ideal. Instead, my hope was to have users append an api_token to the end of their query string and use that to authenticate their request.
    Typically my applications have a UI and authentication is done through a simple login page. Obviously for a RESTful API, having a login page isn't ideal. Instead, my hope was to have users append an `api_token` to the end of their query string and use that to authenticate their request.
    I was happy to find that 5.2 also ships with a `TokenGuard` class that allows you to do exactly that, but the documentation on getting it to work was a bit thin, so here you go.

    ## Set up Token based Authenticaton
  10. JacobBennett revised this gist Jan 20, 2016. No changes.
  11. JacobBennett revised this gist Jan 20, 2016. 1 changed file with 3 additions and 3 deletions.
    6 changes: 3 additions & 3 deletions blog.md
    Original file line number Diff line number Diff line change
    @@ -28,8 +28,8 @@ Use the following route group as an example of what your routes might look like.

    ```php
    Route::group(['prefix' => 'api/v1', 'middleware' => 'auth:api'], function () {
    Route::post('/short', 'UrlMapperController@store');
    });
    Route::post('/short', 'UrlMapperController@store');
    });
    ```

    **Note:** Typically when protecting routes from unauthenticated users, we use the `auth` middleware, but by appending `:api` to the end we are telling Laravel that we want to use the driver for the `api` guard which is set up in the `config/auth.php` and is defaulted to `token`.
    @@ -41,7 +41,7 @@ At this point, any routes wrapped with your `auth:api` middleware are only acces
    To get the authenticated user for this API request, use `Auth::user()` with a small addition.

    ```php
    Auth::guard('api')->user();
    Auth::guard('api')->user();
    ```

    Just like when we called the middleware, we have to let Laravel know that we want the `api` guard instead of the default `web` guard.
  12. JacobBennett revised this gist Jan 20, 2016. 1 changed file with 3 additions and 4 deletions.
    7 changes: 3 additions & 4 deletions blog.md
    Original file line number Diff line number Diff line change
    @@ -14,9 +14,8 @@ I was happy to find that 5.2 also ships with a `TokenGuard` class that allows yo
    The first think you need to do is to add an `api_token` column to your `users` table. If you are just starting your application you can likely get away with modifying the user migration that ships with Laravel to include your new column.

    ```php
    // add this to your users_table migration

    $table->string('api_token', 60)->unique();
    // add this to your users_table migration
    $table->string('api_token', 60)->unique();
    ```

    **Note:** Be sure to assign an api_token to new users. Something like `str_random(60)` should be sufficient.
    @@ -28,7 +27,7 @@ Second, we need to make sure that any routes that will be using Token Authentica
    Use the following route group as an example of what your routes might look like.

    ```php
    Route::group(['prefix' => 'api/v1', 'middleware' => 'auth:api'], function () {
    Route::group(['prefix' => 'api/v1', 'middleware' => 'auth:api'], function () {
    Route::post('/short', 'UrlMapperController@store');
    });
    ```
  13. JacobBennett revised this gist Jan 20, 2016. 1 changed file with 1 addition and 1 deletion.
    2 changes: 1 addition & 1 deletion blog.md
    Original file line number Diff line number Diff line change
    @@ -19,7 +19,7 @@ The first think you need to do is to add an `api_token` column to your `users` t
    $table->string('api_token', 60)->unique();
    ```

    Be sure when creating a new user to assign them an api_token. Something like `str_random(60)` should be sufficient.
    **Note:** Be sure to assign an api_token to new users. Something like `str_random(60)` should be sufficient.


    ### 2. Wrap your routes
  14. JacobBennett revised this gist Jan 20, 2016. 1 changed file with 3 additions and 3 deletions.
    6 changes: 3 additions & 3 deletions blog.md
    Original file line number Diff line number Diff line change
    @@ -9,7 +9,7 @@ I was happy to find that 5.2 also ships with a `TokenGuard` class that allows yo

    ## Set up Token based Authenticaton

    ### Add an api_token
    ### 1. Add an api_token

    The first think you need to do is to add an `api_token` column to your `users` table. If you are just starting your application you can likely get away with modifying the user migration that ships with Laravel to include your new column.

    @@ -22,7 +22,7 @@ $table->string('api_token', 60)->unique();
    Be sure when creating a new user to assign them an api_token. Something like `str_random(60)` should be sufficient.


    ### Wrap your routes
    ### 2. Wrap your routes

    Second, we need to make sure that any routes that will be using Token Authentication are being protected by the `auth:api` middleware.
    Use the following route group as an example of what your routes might look like.
    @@ -37,7 +37,7 @@ Route::group(['prefix' => 'api/v1', 'middleware' => 'auth:api'], function () {

    At this point, any routes wrapped with your `auth:api` middleware are only accessible to those that visit the route with a valid `api_token` in their request.

    ### Getting the User
    ### 3. Getting the User

    To get the authenticated user for this API request, use `Auth::user()` with a small addition.

  15. JacobBennett revised this gist Jan 20, 2016. 1 changed file with 48 additions and 8 deletions.
    56 changes: 48 additions & 8 deletions blog.md
    Original file line number Diff line number Diff line change
    @@ -9,25 +9,65 @@ I was happy to find that 5.2 also ships with a `TokenGuard` class that allows yo

    ## Set up Token based Authenticaton

    ### Add an api_token

    The first think you need to do is to add an `api_token` column to your `users` table. If you are just starting your application you can likely get away with modifying the user migration that ships with Laravel to include your new column.
    ```

    ```php
    // add this to your users_table migration

    $table->string('api_token', 60)->index();
    $table->string('api_token', 60)->unique();
    ```

    Second, we need to make sure that any routes that will be using this particular method of Authentication are being protected by the `auth:api` middleware.
    Use the following route group as an example of what your route might look like.
    ```
    Be sure when creating a new user to assign them an api_token. Something like `str_random(60)` should be sufficient.


    ### Wrap your routes

    Second, we need to make sure that any routes that will be using Token Authentication are being protected by the `auth:api` middleware.
    Use the following route group as an example of what your routes might look like.

    ```php
    Route::group(['prefix' => 'api/v1', 'middleware' => 'auth:api'], function () {
    Route::post('/short', 'UrlMapperController@store');
    });
    ```

    **Note:** Typically when protecting routes from unauthenticated users, we use the `auth` middleware, but by appending the `:api` to the end of it we are telling Laravel that we want to use the driver for the `api` guard which is set up in the `config/auth.php` and is defaulted to the `token` guard.
    **Note:** Typically when protecting routes from unauthenticated users, we use the `auth` middleware, but by appending `:api` to the end we are telling Laravel that we want to use the driver for the `api` guard which is set up in the `config/auth.php` and is defaulted to `token`.

    At this point, any routes wrapped with your `auth:api` middleware are only accessible to those that visit the route with a valid `api_token` in their request.

    At this point, any routes wrapped with your `auth:api` middleware are locked down to those that visit the URL with a valid `api_token` in their request.
    ### Getting the User

    To get the authenticated user for this API request, use `Auth::user()` with a small addition.

    ```php
    Auth::guard('api')->user();
    ```

    Just like when we called the middleware, we have to let Laravel know that we want the `api` guard instead of the default `web` guard.

    ## Extras

    In the `App\Http\Middleware\Authenticate` middleware, you might want to change the following lines:

    ```php
    // Original
    if ($request->ajax()) {
    return response('Unauthorized.', 401);
    } else {
    return redirect()->guest('login');
    }

    // Updated
    if ($request->ajax() || $request->wantsJson()) {
    return response('Unauthorized.', 401);
    } else {
    return redirect()->guest('login');
    }
    ```

    My goal however was not to simply protect a route, but to associate any new short urls created with the user that created them. In order to do this, we need to know whose `api_token` was used during the request. Because this is a statelss API we can't rely upon cookies or sessions to tell us who our user is. Thankfully, Laravel makes it easy to work with that.
    This will hopefully return a 401 status code to unauthorized API requests instead of redirect it to a login page.

    Lastly, if you are planning on primarily using the `TokenGuard` to authenticate requests, change the default guard in `config/auth.php` to be `api` instead of `web`. That should prevent you from having to tell Laravel to use the `api` version of the middleware or guard since Laravel will use by default what you have set in `config/auth.php`.

  16. JacobBennett revised this gist Jan 20, 2016. 1 changed file with 10 additions and 50 deletions.
    60 changes: 10 additions & 50 deletions blog.md
    Original file line number Diff line number Diff line change
    @@ -1,73 +1,33 @@
    I; recently had the need to write a small url shortening application. I am aware that this problem has been solved quite a few times before, but what is being a developer if not reinventing the wheel just for the heck of it? Custom CMS anyone?
    I recently had the need to write a small url shortening application. I am aware that this problem has been solved quite a few times before, but what is being a developer if not reinventing the wheel just for the heck of it? Custom CMS anyone?

    Knowing that this was going to be a tiny RESTful API and also knowing that Laravel 5.2 had API rate limiting built in, I was eager to give it a try.
    Taylor Otwell being Taylor Otwell shipped 5.2 with the rate limiting defaults set up out of the box and I had my application building out short url's in a matter of minutes.
    The problem for me came when I wanted to start associating those short urls with a user.

    Typically my applications have a UI and authentication is done through a simple login page. Obviously for a simple RESTful API, having a login page isn't ideal. Instead, my hope was to have users append an api_token to the end of their query string and use that to authenticate their request.
    Typically my applications have a UI and authentication is done through a simple login page. Obviously for a RESTful API, having a login page isn't ideal. Instead, my hope was to have users append an api_token to the end of their query string and use that to authenticate their request.
    I was happy to find that 5.2 also ships with a `TokenGuard` class that allows you to do exactly that, but the documentation on getting it to work was a bit thin, so here you go.

    ## Set up Token based Authenticaton

    ### Add an api_token

    The first think you need to do is to add an `api_token` column to your `users` table. If you are just starting your application you can likely get away with modifying the user migration that ships with Laravel to include your new column.

    ```php
    ```
    // add this to your users_table migration
    $table->string('api_token', 60)->unique();
    $table->string('api_token', 60)->index();
    ```

    Be sure when creating a new user to assign them an api_token. Something like `str_random(60)` should be sufficient.


    ### Wrap your routes

    Second, we need to make sure that any routes that will be using Token Authentication are being protected by the `auth:api` middleware.
    Use the following route group as an example of what your routes might look like.

    ```php
    Second, we need to make sure that any routes that will be using this particular method of Authentication are being protected by the `auth:api` middleware.
    Use the following route group as an example of what your route might look like.
    ```
    Route::group(['prefix' => 'api/v1', 'middleware' => 'auth:api'], function () {
    Route::post('/short', 'UrlMapperController@store');
    });
    ```

    **Note:** Typically when protecting routes from unauthenticated users, we use the `auth` middleware, but by appending `:api` to the end we are telling Laravel that we want to use the driver for the `api` guard which is set up in the `config/auth.php` and is defaulted to `token`.

    At this point, any routes wrapped with your `auth:api` middleware are only accessible to those that visit the route with a valid `api_token` in their request.
    **Note:** Typically when protecting routes from unauthenticated users, we use the `auth` middleware, but by appending the `:api` to the end of it we are telling Laravel that we want to use the driver for the `api` guard which is set up in the `config/auth.php` and is defaulted to the `token` guard.

    ### Getting the User

    To get the authenticated user for this API request, use `Auth::user()` with a small addition.

    ```php
    Auth::guard('api')->user();
    ```

    Just like when we called the middleware, we have to let Laravel know that we want the `api` guard instead of the default `web` guard.

    ## Extras

    In the `App\Http\Middleware\Authenticate` middleware, you might want to change the following lines:

    ```php
    // Original
    if ($request->ajax()) {
    return response('Unauthorized.', 401);
    } else {
    return redirect()->guest('login');
    }

    // Updated
    if ($request->ajax() || $request->wantsJson()) {
    return response('Unauthorized.', 401);
    } else {
    return redirect()->guest('login');
    }
    ```
    At this point, any routes wrapped with your `auth:api` middleware are locked down to those that visit the URL with a valid `api_token` in their request.

    This will hopefully return a 401 status code to unauthorized API requests instead of redirect it to a login page.
    My goal however was not to simply protect a route, but to associate any new short urls created with the user that created them. In order to do this, we need to know whose `api_token` was used during the request. Because this is a statelss API we can't rely upon cookies or sessions to tell us who our user is. Thankfully, Laravel makes it easy to work with that.

    Lastly, if you are planning on primarily using the `TokenGuard` to authenticate requests, change the default guard in `config/auth.php` to be `api` instead of `web`. That should prevent you from having to tell Laravel to use the `api` version of the middleware or guard since Laravel will use by default what you have set in `config/auth.php`.

  17. JacobBennett revised this gist Jan 20, 2016. 1 changed file with 49 additions and 9 deletions.
    58 changes: 49 additions & 9 deletions blog.md
    Original file line number Diff line number Diff line change
    @@ -1,4 +1,4 @@
    I recently had the need to write a small url shortening application. I am aware that this problem has been solved quite a few times before, but what is being a developer if not reinventing the wheel just for the heck of it? Custom CMS anyone?
    I; recently had the need to write a small url shortening application. I am aware that this problem has been solved quite a few times before, but what is being a developer if not reinventing the wheel just for the heck of it? Custom CMS anyone?

    Knowing that this was going to be a tiny RESTful API and also knowing that Laravel 5.2 had API rate limiting built in, I was eager to give it a try.
    Taylor Otwell being Taylor Otwell shipped 5.2 with the rate limiting defaults set up out of the box and I had my application building out short url's in a matter of minutes.
    @@ -9,25 +9,65 @@ I was happy to find that 5.2 also ships with a `TokenGuard` class that allows yo

    ## Set up Token based Authenticaton

    ### Add an api_token

    The first think you need to do is to add an `api_token` column to your `users` table. If you are just starting your application you can likely get away with modifying the user migration that ships with Laravel to include your new column.
    ```

    ```php
    // add this to your users_table migration

    $table->string('api_token', 60)->index();
    $table->string('api_token', 60)->unique();
    ```

    Second, we need to make sure that any routes that will be using this particular method of Authentication are being protected by the `auth:api` middleware.
    Use the following route group as an example of what your route might look like.
    ```
    Be sure when creating a new user to assign them an api_token. Something like `str_random(60)` should be sufficient.


    ### Wrap your routes

    Second, we need to make sure that any routes that will be using Token Authentication are being protected by the `auth:api` middleware.
    Use the following route group as an example of what your routes might look like.

    ```php
    Route::group(['prefix' => 'api/v1', 'middleware' => 'auth:api'], function () {
    Route::post('/short', 'UrlMapperController@store');
    });
    ```

    **Note:** Typically when protecting routes from unauthenticated users, we use the `auth` middleware, but by appending the `:api` to the end of it we are telling Laravel that we want to use the driver for the `api` guard which is set up in the `config/auth.php` and is defaulted to the `token` guard.
    **Note:** Typically when protecting routes from unauthenticated users, we use the `auth` middleware, but by appending `:api` to the end we are telling Laravel that we want to use the driver for the `api` guard which is set up in the `config/auth.php` and is defaulted to `token`.

    At this point, any routes wrapped with your `auth:api` middleware are only accessible to those that visit the route with a valid `api_token` in their request.

    At this point, any routes wrapped with your `auth:api` middleware are locked down to those that visit the URL with a valid `api_token` in their request.
    ### Getting the User

    To get the authenticated user for this API request, use `Auth::user()` with a small addition.

    ```php
    Auth::guard('api')->user();
    ```

    Just like when we called the middleware, we have to let Laravel know that we want the `api` guard instead of the default `web` guard.

    ## Extras

    In the `App\Http\Middleware\Authenticate` middleware, you might want to change the following lines:

    ```php
    // Original
    if ($request->ajax()) {
    return response('Unauthorized.', 401);
    } else {
    return redirect()->guest('login');
    }

    // Updated
    if ($request->ajax() || $request->wantsJson()) {
    return response('Unauthorized.', 401);
    } else {
    return redirect()->guest('login');
    }
    ```

    My goal however was not to simply protect a route, but to associate any new short urls created with the user that created them. In order to do this, we need to know whose `api_token` was used during the request. Because this is a statelss API we can't rely upon cookies or sessions to tell us who our user is. Thankfully, Laravel makes it easy to work with that.
    This will hopefully return a 401 status code to unauthorized API requests instead of redirect it to a login page.

    Lastly, if you are planning on primarily using the `TokenGuard` to authenticate requests, change the default guard in `config/auth.php` to be `api` instead of `web`. That should prevent you from having to tell Laravel to use the `api` version of the middleware or guard since Laravel will use by default what you have set in `config/auth.php`.

  18. JacobBennett created this gist Jan 20, 2016.
    33 changes: 33 additions & 0 deletions blog.md
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,33 @@
    I recently had the need to write a small url shortening application. I am aware that this problem has been solved quite a few times before, but what is being a developer if not reinventing the wheel just for the heck of it? Custom CMS anyone?

    Knowing that this was going to be a tiny RESTful API and also knowing that Laravel 5.2 had API rate limiting built in, I was eager to give it a try.
    Taylor Otwell being Taylor Otwell shipped 5.2 with the rate limiting defaults set up out of the box and I had my application building out short url's in a matter of minutes.
    The problem for me came when I wanted to start associating those short urls with a user.

    Typically my applications have a UI and authentication is done through a simple login page. Obviously for a simple RESTful API, having a login page isn't ideal. Instead, my hope was to have users append an api_token to the end of their query string and use that to authenticate their request.
    I was happy to find that 5.2 also ships with a `TokenGuard` class that allows you to do exactly that, but the documentation on getting it to work was a bit thin, so here you go.

    ## Set up Token based Authenticaton

    The first think you need to do is to add an `api_token` column to your `users` table. If you are just starting your application you can likely get away with modifying the user migration that ships with Laravel to include your new column.
    ```
    // add this to your users_table migration
    $table->string('api_token', 60)->index();
    ```

    Second, we need to make sure that any routes that will be using this particular method of Authentication are being protected by the `auth:api` middleware.
    Use the following route group as an example of what your route might look like.
    ```
    Route::group(['prefix' => 'api/v1', 'middleware' => 'auth:api'], function () {
    Route::post('/short', 'UrlMapperController@store');
    });
    ```

    **Note:** Typically when protecting routes from unauthenticated users, we use the `auth` middleware, but by appending the `:api` to the end of it we are telling Laravel that we want to use the driver for the `api` guard which is set up in the `config/auth.php` and is defaulted to the `token` guard.

    At this point, any routes wrapped with your `auth:api` middleware are locked down to those that visit the URL with a valid `api_token` in their request.

    My goal however was not to simply protect a route, but to associate any new short urls created with the user that created them. In order to do this, we need to know whose `api_token` was used during the request. Because this is a statelss API we can't rely upon cookies or sessions to tell us who our user is. Thankfully, Laravel makes it easy to work with that.