JWT-auth продолжает выдавать ошибку 401 при входе в систему. Учетные данные верны, я даже дошел до того, что заменил зашифрованный пароль на простой пароль в БД, и он все равно вернул 401. Метод регистрации работает просто отлично, я до сих пор не дошел до других методов.
Для справки вот мой код:
Обратите внимание, мои пользователи находятся в таблице под названием consumers
Потребительская миграция
class CreateConsumerTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('consumers', function (Blueprint $table) {
$table->increments('con_id', 11);
$table->string('con_fname', 50);
$table->string('con_lname', 50);
$table->string('email', 50);
$table->string('password', 100);
$table->binary('con_cover_photo')->nullable();
$table->binary('con_profile_pic')->nullable();
$table->double('total_earned', 10, 2)->default('0');
$table->timestamps();
$table->rememberToken();
$table->engine = 'InnoDB';
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('consumers');
}
}
миграция user_verification
class CreateUserVerificationsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('user_verifications', function (Blueprint $table) {
$table->increments('id');
$table->integer('con_id')->unsigned();
$table->string('token');
$table->foreign('con_id')->references('con_id')->on('consumers');//->onDelete('cascade');//onUpdate();
});
Schema::table('consumers', function (Blueprint $table) {
$table->boolean('is_verified')->default(0);
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('user_verifications');
Schema::table('consumers', function (Blueprint $table) {
$table->dropColumn('is_verified');
});
}
}
AuthController.php (только методы регистрации, verifyUSer и входа в систему)
public function register(Request $request)
{
$credentials = $request->only('con_fname', 'con_lname', 'email', 'password', 'password_confirmation');
$rules = [
'con_fname' => 'required|max:255',
'con_lname' => 'required|max:255',
'email' => 'required|email|max:255|unique:consumers',
'password' => 'required|string|min:6|confirmed',
'password_confirmation' => 'same:password'
];
$validator = Validator::make($credentials, $rules);
if($validator->fails()) {
return response()->json(['success'=> false, 'error'=> $validator->messages()]);
}
$fname = $request->con_fname;
$lname = $request ->con_lname;
$email = $request->email;
$password = $request->password;
$user = Consumer::create(['con_fname' => $fname, 'con_lname' => $lname, 'email' => $email, 'password' => Hash::make($password)]);
$verification_code = str_random(30); //Generate verification code
DB::table('user_verifications')->insert(['con_id'=>$user->con_id,'token'=>$verification_code]);
$subject = "Please verify your email address.";
Mail::send('email.verify', ['con_fname' => $fname, 'con_lname' => $lname, 'verification_code' => $verification_code],
function($mail) use ($email, $fname, $subject){
$mail->from(getenv('FROM_EMAIL_ADDRESS'), "From User/Company Name Goes Here");
$mail->to($email);
$mail->subject($subject);
});
return response()->json(['success'=> true, 'message'=> 'Thanks for signing up! Please check your email to complete your registration.']);
}
public function verifyUser($verification_code)
{
$check = DB::table('user_verifications')->where('token',$verification_code)->first();
if(!is_null($check)){
$user = Consumer::find($check->con_id);
if($user->is_verified == 1){
return response()->json([
'success'=> true,
'message'=> 'Account already verified..'
]);
}
$user->update(['is_verified' => 1]);
DB::table('user_verifications')->where('token',$verification_code)->delete();
return response()->json([
'success'=> true,
'message'=> 'You have successfully verified your email address.'
]);
}
return response()->json(['success'=> false, 'error'=> "Verification code is invalid."]);
}
public function login(Request $request)
{
$credentials = $request->only('email', 'password');
$rules = [
'email' => 'required|email',
'password' => 'required',
];
$validator = Validator::make($credentials, $rules);
if($validator->fails()) {
return response()->json(['success'=> false, 'error'=> $validator->messages()]);
}
$credentials['is_verified'] = 1;
try {
// attempt to verify the credentials and create a token for the user
if (! $token = JWTAuth::attempt($credentials)) {
return response()->json(['success' => false, 'error' => 'Invalid username or password'], 401);
}
} catch (JWTException $e) {
// something went wrong whilst attempting to encode the token
return response()->json(['success' => false, 'error' => 'Failed to login, please try again.'], 500);
}
// all good so return the token
return response()->json(['success' => true, 'data'=> [ 'token' => $token ]]);
}
/**
* Log out
* Invalidate the token, so user cannot use it anymore
* They have to relogin to get a new token
*
* @param Request $request
*/
}
jwt.php
вернуть [
'secret' => env('JWT_SECRET'),
'keys' => [
'public' => env('JWT_PUBLIC_KEY'),
'private' => env('JWT_PRIVATE_KEY'),
'passphrase' => env('JWT_PASSPHRASE'),
],
'ttl' => env('JWT_TTL', 60),
'refresh_ttl' => env('JWT_REFRESH_TTL', 20160),
'algo' => env('JWT_ALGO', 'HS256'),
'required_claims' => [
'iss',
'iat',
'exp',
'nbf',
'sub',
'jti',
],
'persistent_claims' => [
// 'foo',
// 'bar',
],
'blacklist_enabled' => env('JWT_BLACKLIST_ENABLED', true),
'blacklist_grace_period' => env('JWT_BLACKLIST_GRACE_PERIOD', 0),
'providers' => [
'jwt' => Tymon\JWTAuth\Providers\JWT\Namshi::class,
'auth' => Tymon\JWTAuth\Providers\Auth\Illuminate::class,
'storage' => Tymon\JWTAuth\Providers\Storage\Illuminate::class,
],
];
Задача ещё не решена.
Других решений пока нет …