Laravel 5.2 API Authentication

I am developing a RESTful API with Laravel 5.2. In the token rack located in \Illuminate\Auth\TokenGuard\TokenGuard.php on line 46, the column name for the token is defined as api_token :

 $this->storageKey = 'api_token'; 

I want to change this column name to something else, for example api_key .

How can i do this? I do not want to modify the main TokenGuard.php file.

+5
source share
2 answers

Built-in TokenGuard not able to change the storageKey field. Therefore, you will need to create your own Guard class, which sets this field, and tell Auth use your Guard class.

Start by creating a new Guard class that extends the TokenGuard base class. In this example, it is created in app/Services/Auth/MyTokenGuard.php :

 namespace App\Services\Auth; use Illuminate\Http\Request; use Illuminate\Auth\TokenGuard; use Illuminate\Contracts\Auth\UserProvider; class MyTokenGuard extends TokenGuard { public function __construct(UserProvider $provider, Request $request) { parent::__construct($provider, $request); $this->inputKey = 'api_key'; // if you want to rename this, as well $this->storageKey = 'api_key'; } } 

Once you have created your class, you need to tell Auth about it. You can do this in the boot() method of your AuthServiceProvider service AuthServiceProvider :

 public function boot(GateContract $gate) { $this->registerPolicies($gate); Auth::extend('mytoken', function($app, $name, array $config) { return new \App\Services\Auth\MyTokenGuard(Auth::createUserProvider($config['provider']), $app['request']); }); } 

And finally, you need to tell Auth to use your new mytoken . This is done in the config/auth.php configuration file.

 'guards' => [ 'api' => [ 'driver' => 'mytoken', 'provider' => 'users', ], ], 
+16
source

Unfortunately, there is no way to configure this.

The only way to use another key is to create your own "Guard": Adding custom guards .

You can extend the TokenGuard class and override __constructor with your column names.

+1
source

Source: https://habr.com/ru/post/1240828/


All Articles