【问题标题】:how to store JWT token in database如何将 JWT 令牌存储在数据库中
【发布时间】:2017-12-25 14:53:46
【问题描述】:

我知道如果我将 jwt 令牌存储在我的数据库中,我会失去目的,但由于某种原因,我想存储它,我该怎么做?

控制器

<?php

namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Tymon\JWTAuth\JWTAuth;

class AuthController extends Controller
{
/**
 * @var \Tymon\JWTAuth\JWTAuth
 */
protected $jwt;

public function __construct(JWTAuth $jwt)
{
    $this->jwt = $jwt;
}

public function postLogin(Request $request)
{
    $this->validate($request, [
        'email'    => 'required|email|max:255',
        'password' => 'required',
    ]);

    try {

        if (! $token = $this->jwt->attempt($request->only('email', 'password'))) {
        $create_token = User::where('user_id', $login->user_id)->update(['token' => $token]);
            return response()->json(['user_not_found'], 404);
        }
        else {
        $create_token = User::where('user_id', auth()->user()->user_id)->update(['token' => $token]);
        }

    } catch (\Tymon\JWTAuth\Exceptions\TokenExpiredException $e) {

        return response()->json(['token_expired'], 500);

    } catch (\Tymon\JWTAuth\Exceptions\TokenInvalidException $e) {

        return response()->json(['token_invalid'], 500);

    } catch (\Tymon\JWTAuth\Exceptions\JWTException $e) {

        return response()->json(['token_absent' => $e->getMessage()], 500);

    }

    return response()->json(compact('token'));
}

    public function logout(Request $request) 
{
    $this->jwt->invalidate($this->jwt->getToken());
    return response()->json([
        'message' => 'User logged off successfully!'
    ], 200);
}
}

我尝试了上面的方法,但我收到错误提示 Call to undefined function App\Http\Controllers\auth() 谁能帮帮我??

【问题讨论】:

  • 尝试Auth::user()-&gt;id从laravel默认用户表中获取用户id
  • 它确实保存了令牌,但每当我获得新令牌时,我都不会更新令牌
  • 如果你有token那么你不需要访问postlogin函数。您可以在令牌更新时更新
  • 如果有人想通过访问postlogin 来刷新他们的token,我可以保存更新后的令牌吗?我该怎么做?
  • 你会在patchRefresh函数中得到newtoken,你可以从那里更新token到数据库

标签: php api jwt lumen lumen-5.3


【解决方案1】:

不建议看到 json 网络令牌对时间敏感,但我确实写了类似的东西,但使用的是 redis。查看您的代码,我建议您为tokens 创建行并将其添加到public $hidden = ['password','token']。创建用户时,您会创建令牌并将其保存到数据库中。

【讨论】:

    猜你喜欢
    • 2021-09-23
    • 2018-05-04
    • 2015-09-15
    • 2016-09-13
    • 1970-01-01
    • 2022-01-15
    • 2021-01-21
    • 1970-01-01
    • 2018-11-12
    相关资源
    最近更新 更多