Laravel Jwt身份验证尝试始终返回false

时间:2020-08-13 18:59:39

标签: laravel jwt laravel-jwt

希望您一切都好。 ;)

但是,在生成JWT身份验证令牌时遇到了问题

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

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
        ]);
    }

}

Config / 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 个答案:

答案 0 :(得分:-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);
    }