【发布时间】:2019-01-10 16:43:59
【问题描述】:
我正在使用 Laravel 5.4 和 Passport 4。我只想使用 First-Party-App。因此,正如answer 所建议的那样,我想远离将 ClientID 和 ClientSecret 放在应用程序中。我已经输入了AuthServiceProvider 的boot() 方法:
Passport::routes();
Passport::tokensExpireIn(Carbon::now()->addDays(30));
Passport::refreshTokensExpireIn(Carbon::now()->addDays(60));
我在api.php 中添加了自己的路由以接受来自 App 的登录:
Route::post('login', 'Auth\LoginController@apiLogin');
这是我的行动:
public function apiLogin(Request $request)
{
$credentials = $request->only('email', 'password');
if (Auth::attempt($credentials)) {
// Authentication passed...
$user = Auth::user();
$token = $user->createToken('API Access')->accessToken;
return response()->json(["token_type" =>"Bearer","expires_in" => 2592000,"access_token" => $token]);
}
return response()->json(["error" => "invalid_credentials", "message" => "The user credentials were incorrect."], 401);
}
是否有任何方法可以检索expires_in(30 天 => 2592000 秒)的秒数或日期时间,以便我可以自动进行计算?
【问题讨论】:
-
您应该能够访问
$token上的expiry属性。access_token的 JSON 响应是什么样的?此外,如果您无法访问它,您可以随时使用$expire = Carbon::now()->diffInSeconds(Carbon::now()->addDays({days}));并返回它而不是2592000,但这似乎距离获得{days} * 86400还很遥远 -
非常感谢蒂姆刘易斯!我可以使用 $token 访问它,它是一个包含令牌的 Eloquent 模型:
$objToken = $user->createToken('API Access');,我做了$expire = $objToken->token->expires_at->diffInSeconds(Carbon::now());。但是Passport::tokensExpireIn((new DateTime())->add(new DateInterval('P30D')));不起作用,似乎是 Laravel 5.4 中的一个错误,许多讨论忽略了它。我想从物业本身获得它的机会……但这是另一个问题。无论如何,我将其发布为答案,然后我会选择它作为答案。 -
不错;真高兴你做到了。对于第二个问题,在使用 Laravel 时,您可以访问
Carbon,因此您不必使用DateTime和DateInterval类;你有什么理由尝试那个特定的代码 vsCarbon::now()->addDays(30)?另外,继续发布自我答案;我只是指出你正确的方向:) -
感谢 Carbon 的建议。当我使用 Laravel 4 时,我对 Carbon 了解不多。现在我更喜欢 Laravel 5+,我正在改变一些习惯。
标签: laravel laravel-5.4 laravel-passport