如何生成api_token?

时间:2016-12-02 10:46:23

标签: php laravel laravel-5.3

我已经使用后卫创建了代码和经过身份验证的用户,但它没有为我提供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);
}

上面的功能工作正常,但是当我使用auth()->guard('api')->user()->api_token时我没有获得令牌。此列已在我的数据库中,即使我无法生成api_token此处可能存在的问题。

EDITED

路由/ api.php:

Route::group(['namespace' => "Api\\v1", 'as' => 'api.v1.', 'prefix' => 'v1'], function () {
    Route::any('/login', 'AccessController@authenticate');
});

配置/ auth.php:

    'defaults' => [
        'guard' => 'web',
        'passwords' => 'users',
    ],

    'guards' => [
        'web' => [
            'driver' => 'session',
            'provider' => 'users',
        ],

        'api' => [
            'driver' => 'token',
            'provider' => 'users',
        ],
    ],

2 个答案:

答案 0 :(得分:1)

您可能需要确保使用令牌身份验证的所有路由都受auth:api中间件的保护。

就像这个例子:

Route::group(['prefix' => 'api/v1', 'middleware' => 'auth:api'], function () {
    Route::post('/authentificate', 'AuthController@authentificate');
});

答案 1 :(得分:0)

您可以使用模型更改器自动执行此操作或覆盖模型类的引导方法(在您的用例模型中)用户模型

data-open