php - 如何生成api_token?

标签 php laravel laravel-5.3

我已经使用 guard 创建了代码并验证了用户身份,但它没有为我提供 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 时,我没有获得 token 。此列已在我的数据库中,即使我无法生成 api_token 这可能是这里的问题。

已编辑

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

最佳答案

您可能需要确保任何将使用 token 身份验证的路由都受到 auth:api 中间件的保护。

像这个例子:

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

关于php - 如何生成api_token?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40930362/

相关文章:

php - 计算两个日期时间之间的差异

javascript - 从 Ajax POST 到 DB 插入的带有特殊字符的字符串

php - PHP 中无限循环的成语?

php - Laravel 5 withInput old 总是空的

php - Laravel Eloquent : Nested Query Builder?

php - 如何在laravel中选择特定的列

php - 如何在 Laravel 中添加和更新配置变量

php - 此分发未配置为允许 HTTP 请求

php - 使用 Laravel 在 MySQL 中导入大型 CSV 文件

laravel - 自定义文件名,同时保留扩展名