Laravel Jwt 身份验证尝试总是返回 false

Posted

技术标签:

【中文标题】Laravel Jwt 身份验证尝试总是返回 false【英文标题】:Laravel Jwt auth attempts returns false always 【发布时间】:2020-12-03 16:23:44 【问题描述】:

希望你做得很好。 ;)

但是,我在生成 JWT Auth Token 时遇到了问题

我们有一个名为 somename_users 的自定义用户表,其中电子邮件字段名为 email_id,我们使用 md5 哈希来存储密码(不要判断)。所以首先我尝试做一些测试,它成功了,我成功生成了 JWT 身份验证令牌,所以之后,我试图在我们的开发服务器上实现它。

App\Model\User.php

<?php

namespace App\Model;

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

class User extends Authenticatable implements JWTSubject

    use Notifiable;

    const CREATED_AT = 'created_at';
    const UPDATED_AT = 'modified_at';

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'first_name','middle_name','last_name','email_id','password',[...]
    ];

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


    /**
     * 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 [];
    

App\Http\Controllers\api\v1\TestController.php*


namespace App\Http\Controllers\api\v1;

use Illuminate\Support\Facades\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use JWTAuth;
use App\Model\User;

class TestController extends Controller

  //   public function get()
  //    return User::all();
  //   

  
  //   public  function login(Request $request)
  //   
  //    $creds = array();

  //    $creds["email_id"] = $request->email_id;
  //    $creds["password"] = md5($request->password);

  //    try 
        //     if (! $token = JWTAuth::attempt($creds)) 
        //         return response()->json(['error' => 'invalid_credentials','token'=>$token], 400);
        //     
        //  catch (JWTException $e) 
        //     return response()->json(['error' => 'could_not_create_token'], 500);
        // 

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

  //   

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


    /**
     * Create a new AuthController instance.
     *
     * @return void
     */
    public function __construct()
    
        $this->middleware('auth:api', ['except' => ['login']]);
    

    /**
     * Get a JWT via given credentials.
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function login(Request $request)
    
        $creds = array();
        $creds["email_id"] = $request->email_id;
        $creds["password"] = md5($request->password);


        $creds = array();
        $creds["email_id"] = $request->email_id;
        $creds["password"] = md5($request->password);

        if (! $token = auth()->attempt($creds)) 
            return response()->json(['error' => 'Unauthorized'], 401);
        

        return $this->respondWithToken($token);

    

    /**
     * Get the authenticated User.
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function me()
    
        return response()->json(auth()->user());
    

    /**
     * Log the user out (Invalidate the token).
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function logout()
    
        auth()->logout();

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

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

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


配置/auth.php

<?php

return [

    /*
    |--------------------------------------------------------------------------
    | Authentication Defaults
    |--------------------------------------------------------------------------
    |
    | This option controls the default authentication "guard" and password
    | reset options for your application. You may change these defaults
    | as required, but they're a perfect start for most applications.
    |
    */

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

    /*
    |--------------------------------------------------------------------------
    | Authentication Guards
    |--------------------------------------------------------------------------
    |
    | Next, you may define every authentication guard for your application.
    | Of course, a great default configuration has been defined for you
    | here which uses session storage and the Eloquent user provider.
    |
    | All authentication drivers have a user provider. This defines how the
    | users are actually retrieved out of your database or other storage
    | mechanisms used by this application to persist your user's data.
    |
    | Supported: "session", "token"
    |
    */

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

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

    /*
    |--------------------------------------------------------------------------
    | User Providers
    |--------------------------------------------------------------------------
    |
    | All authentication drivers have a user provider. This defines how the
    | users are actually retrieved out of your database or other storage
    | mechanisms used by this application to persist your user's data.
    |
    | If you have multiple user tables or models you may configure multiple
    | sources which represent each model / table. These sources may then
    | be assigned to any extra authentication guards you have defined.
    |
    | Supported: "database", "eloquent"
    |
    */

    'providers' => [
        //original
        'users' => [
            'driver' => 'eloquent',
            'model' => App\Model\User::class,
            //'table' => 'users',
        ],

        // 'users' => [
        //     'driver' => 'eloquent',
        //     'model' => App\Model\User::class,
        // ],

        /*'users' => [
            'driver' => 'eloquent',
            'table' => 'users',
        ],*/
    ],

    /*
    |--------------------------------------------------------------------------
    | Resetting Passwords
    |--------------------------------------------------------------------------
    |
    | You may specify multiple password reset configurations if you have more
    | than one user table or model in the application and you want to have
    | separate password reset settings based on the specific user types.
    |
    | The expire time is the number of minutes that the reset token should be
    | considered valid. This security feature keeps tokens short-lived so
    | they have less time to be guessed. You may change this as needed.
    |
    */

    'passwords' => [

        //original 
        /*'users' => [
            'provider' => 'users',
            'table' => 'password_resets',
            'expire' => 60,
            'throttle' => 60,
        ],*/

        'users' => [
            'provider' => 'users',
            'table' => 'password_resets',
            'expire' => 60,
        ],

    ],

    /*
    |--------------------------------------------------------------------------
    | Password Confirmation Timeout
    |--------------------------------------------------------------------------
    |
    | Here you may define the amount of seconds before a password confirmation
    | times out and the user is prompted to re-enter their password via the
    | confirmation screen. By default, the timeout lasts for three hours.
    |
    */

    'password_timeout' => 10800,

];

每次我尝试使用电子邮件和密码登录 API 端点时,都会收到未经授权的响应,但凭据绝对完美。

请帮帮我。

提前致谢

【问题讨论】:

【参考方案1】:

laravel 密码登录尝试使用bcrypt 而不是md5,因此必须更改您的代码。

TestController.php

    public function __construct()
    
        ...
        $this->guard = "api"; // add
    

    public function login(Request $request)
    
        $validator = Validator::make($request->all(), [
            'email_id' => 'required|string',
            'password' => 'required|string',
        ]);

        if ($validator->fails()) 
            return response()->json($validator->errors(), 422);
        

        $user = \App\User::where([
            'email_id' => $request->email_id,
            'password' => md5($request->password)
        ])->first();

        if (! $user ) return response()->json([ 'email_id' => ['Unauthorized'] ], 401);

        if (! $token = auth( $this->guard )->login( $user ) ) 
            return response()->json([ 'email_id' => ['Unauthorized'] ], 401);
        

        return $this->respondWithToken($token);
    

【讨论】:

以上是关于Laravel Jwt 身份验证尝试总是返回 false的主要内容,如果未能解决你的问题,请参考以下文章

流明,身份验证尝试总是返回 false(jwt 或 auth)

Jwt 身份验证问题 - 凭据无效

Laravel 护照 oauth 路线总是返回 401 未经授权

护照-jwt 总是返回 401 未授权

JWT 身份验证 Laravel

Laravel 5.7 + Spatie 权限 + JWT 身份验证