Reputation: 375
I've created code and authenticated user using guard but it doesn't provides me a api_token
/**
* This'll provide login authentication to the user
* @param Request $request
* @return json
*/
public function authenticate(Request $request)
{
//getting and setting locale for the request
$locale = ($request->header('lang-code') == 'KO') ? "ko" : "en";
app()->setLocale($locale);
$credentials = $request->only('email','password');
try {
// verify the credentials and create a token for the user
if (!$token = auth()->attempt($credentials)) {
return response()->json(['success' => parent::FAILURE, 'message' => trans('messages.api.login.failure')],401);
}
} catch (GeneralException $e) {
// something went wrong
return response()->json(['success' => parent::FAILURE, 'message' => trans('messages.api.login.tokenNC')],500);
}
return response()->json(['success' => parent::SUCCESS, 'message' => trans('messages.api.login.success'), 'data' => auth()->user()],200);
}
Above function is working fine but I'm not getting token when I use auth()->guard('api')->user()->api_token
. This column is already within my DB even though I'm not able to generate api_token
what can be the issue over here.
EDITED
routes/api.php:
Route::group(['namespace' => "Api\\v1", 'as' => 'api.v1.', 'prefix' => 'v1'], function () {
Route::any('/login', 'AccessController@authenticate');
});
config/auth.php:
'defaults' => [
'guard' => 'web',
'passwords' => 'users',
],
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'token',
'provider' => 'users',
],
],
Upvotes: 3
Views: 2389
Reputation: 1687
You can use model mutators to do that automatically or override the boot method of your Model Class which is in your case User Model
protected static function boot()
{
parent::boot();
static::creating(function($model)
{
$model->api_token = $model->generateCode();
});
}
protected function generateCode()
{
return bin2hex(openssl_random_pseudo_bytes(16));
//you can use your own random fucntion here or you can use inbuilt Crypt funciton
}
Upvotes: 1
Reputation: 4408
You may need to make sure that any routes that will be using Token Authentication are being protected by the auth:api
middleware.
Like this example :
Route::group(['prefix' => 'api/v1', 'middleware' => 'auth:api'], function () {
Route::post('/authentificate', 'AuthController@authentificate');
});
Upvotes: 1