调用受保护的端点时,Laravel Auth JWT令牌崩溃

时间:2020-09-06 19:06:07

标签: php laravel authentication jwt

我正在使用以下方式进行JWT身份验证:

“ tymon / jwt-auth”:“ ^ 1.0”

登录,注销和令牌生成工作正常,受保护的路由也正常,但是当我添加授权承载令牌时,api崩溃并显示以下消息:

SQLSTATE [42S22]:[Microsoft] [用于SQL Server的ODBC驱动程序17] [SQL 服务器]无效的列名“ id”。 (SQL:从中选择前1 * [Dim_UserLogin],其中[id]为空)

我知道它崩溃了,因为在我的身份验证表上我没有列ID,并且也将其发送为null,但是我真的不明白为什么如果我已经登录了它又要再次调用该表而且我有我的令牌。 Laravel不会在比较我的令牌吗?这是我构建的第一个Laravel API,如果我输入错了,请纠正我。

我的代码:

auth.php

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

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

    'api' => [
        'driver' => 'jwt',
        'provider' => 'users',
        'hash' => false,
    ],
],

'providers' => [
    'users' => [
        'driver' => 'eloquent',
        'model' => App\ Dim_UserLogin::class,
    ],

JWTAuthController.php

<
? php

namespace App\ Http\ Controllers;

use App\ Dim_UserLogin;
use Illuminate\ Support\ Facades\ Auth;
use App\ Http\ Controllers\ Controller;
use Illuminate\ Support\ Facades\ Validator;
use Illuminate\ Http\ Request;
use App\ User;

use Tymon\ JWTAuth\ Facades\ JWTAuth;
use Tymon\ JWTAuth\ Exceptions\ JWTException;

class JWTAuthController extends Controller {
    public
    function __construct() {
        $this - > middleware('auth:api', ['except' => ['login', 'logout', 'refresh']]);
    }

    public
    function login(Request $request) {
        $login = $request - > input('login');
        $password = $request - > input('password');

        function pbkdf2($algorithm, $password, $salt, $count, $key_length, $raw_output = false) {
            $algorithm = strtolower($algorithm);
            if (!in_array($algorithm, hash_algos(), true))
                trigger_error('PBKDF2 ERROR: Invalid hash algorithm.', E_USER_ERROR);
            if ($count <= 0 || $key_length <= 0)
                trigger_error('PBKDF2 ERROR: Invalid parameters.', E_USER_ERROR);

            if (function_exists("hash_pbkdf2")) {
                // The output length is in NIBBLES (4-bits) if $raw_output is false!
                if (!$raw_output) {
                    $key_length = $key_length * 2;
                }
                return hash_pbkdf2($algorithm, $password, $salt, $count, $key_length, $raw_output);
            }

            $hash_length = strlen(hash($algorithm, "", true));
            $block_count = ceil($key_length / $hash_length);

            $output = "";
            for ($i = 1; $i <= $block_count; $i++) {
                // $i encoded as 4 bytes, big endian.
                $last = $salt.pack("N", $i);
                // first iteration
                $last = $xorsum = hash_hmac($algorithm, $last, $password, true);
                // perform the other $count - 1 iterations
                for ($j = 1; $j < $count; $j++) {
                    $xorsum ^= ($last = hash_hmac($algorithm, $last, $password, true));
                }
                $output. = $xorsum;
            }

            if ($raw_output)
                return substr($output, 0, $key_length);
            else
                return bin2hex(substr($output, 0, $key_length));
        }

        try {
            $user = Dim_UserLogin::where('Login', '=', $login) - > first();
            if (!$user) return response() - > json(['error' => 'invalid_credentials'], 401);
            $hash = pbkdf2('SHA256', $password, $user - > Salt, 1000, 16);
            // attempt to verify the credentials and create a token for the user
            if (!$userLogin = Dim_UserLogin::where('Login', '=', $login) - > first() - >
                where('Hash', '=', $hash) - > first()) {
                return response() - > json(['error' => 'invalid_credentials'], 401);
            }
            $token = JWTAuth::fromUser($userLogin);

        } catch (JWTException $e) {
            // something went wrong whilst attempting to encode the token
            return response() - > json(['error' => 'could_not_create_token'], 500);
        }

        // all good so return the token
        return response() - > json(compact('token'));
    }

    public
    function logout() {
        auth('api') - > logout();


        return response() - > json(['message' => 'Successfully logged out'], 200);
    }

    /**
     * Refresh a token.
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public
    function refresh() {
        return $this - > createNewToken(auth() - > refresh());
    }

    /**
     * Get the token array structure.
     *
     * @param  string $token
     *
     * @return \Illuminate\Http\JsonResponse
     */
    protected
    function createNewToken($token) {
        return response() - > json([
            'access_token' => $token,
            'token_type' => 'bearer',
            'expires_in' => auth() - > factory() - > getTTL() * 60
        ]);
    }

}

Dim_UserLogin.php

<
? php


namespace App;


use Illuminate\ Contracts\ Auth\ MustVerifyEmail;
use Illuminate\ Foundation\ Auth\ User as Authenticatable;
use Illuminate\ Notifications\ Notifiable;
use Tymon\ JWTAuth\ Contracts\ JWTSubject;

class Dim_UserLogin extends Authenticatable implements JWTSubject {
    use Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $table = 'Dim_UserLogin';
    public $fillable = [
        'Login', 'Hash', 'Salt',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'Hash', 'remember_token',
    ];

    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];


    /**
     * Get the identifier that will be stored in the subject claim of the JWT.
     *
     * @return mixed
     */
    public
    function getJWTIdentifier() {
        return $this - > getKey();
    }

    /**
     * Return a key value array, containing any custom claims to be added to the JWT.
     *
     * @return array
     */
    public
    function getJWTCustomClaims() {
        return [];
    }

}

LayoutController.php

public function __construct()
{
    $this->middleware('auth:api');
}

.......

所以我在进行像这样的http://xxx.xxx.xx.xx/xx/xxxxx/api/layout

的POST调用后收到提及错误

0 个答案:

没有答案