0

我知道如果我将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() 有人可以帮我吗?

4

1 回答 1

0

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

于 2017-07-23T19:44:23.680 回答