简体   繁体   中英

How to generate api_token?

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',
        ],
    ],

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');
});

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM