我在Laravel 5.3自定义身份验证中遇到问题,当我检查Auth::check()
它返回false
时,想要使用我自己的函数或页面。
这是用户控制器:
namespace App\Http\Controllers;
use App\User;
use Illuminate\Support\Facades\Session;
use validatior;
use Auth;
use Illuminate\Http\Request;
class UserController extends Controller
{
public function postSignUp(Request $request)
{
$validation = \Validator::make($request->all(), [
'email' => 'email|required|unique:users',
'password' => 'required|min:4'
]);
if ($validation->fails()) {
return redirect()->back()->withErrors($validation->errors());
} else {
$user = new User();
$user->email = $request->get("email");
$user->password = bcrypt($request->get['password']);
$user->save();
}
return redirect('signupPage');
}
public function postSignIn(Request $request)
{
$this->validate($request, [
'email' => 'required',
'password' => 'required',
]);
if (Auth::attempt(['email' => $request['email'], 'password' => $request['password']])) {
return redirect('users/profile');
}
dd(Auth::check());
exit;
}
}
登录后我想在个人资料页面重定向,但我的情况不起作用。我的路线是:
Route::group(['prefix' => 'users'], function(){
Route::group(['middleware' => 'guest'], function(){
Route::get('/signupPage','UserController@getSignUp');
Route::post('/register',array ('as'=>'signup', 'uses' =>'UserController@postSignUp', ));
Route::get('signInPage', array('as' => 'signInPage', 'uses' => 'UserController@getSignIn'));
Route::post('/postLogin', array('as' => 'postLogin', 'uses' => 'UserController@postSignIn'));
});
Route::group(['middleware' => 'auth'], function(){
Route::get('/profile', array('as' => 'profile', 'uses' => 'UserController@getProfile'));
Route::get('/logout', array('as'=>'logout', 'uses'=> 'UserController@logout'));
});
});
答案 0 :(得分:1)
以下是代码的一些修改
public function postSignUp(Request $request) { $email = $request->input('email'); $pass = $request->input('password'); $validation = \Validator::make($request->all(), [ 'email' => 'email|required|unique:users', 'password' => 'required|min:4' ]); if ($validation->fails()) { return redirect()->back()->withErrors($validation->errors()); } else { $pas = bcrypt($pass); $user = new User(); $user->email = $email; $user->password = $pas; $user->save(); } return redirect('users/signInPage'); }
注册用户时请使用bcrypt,因为此功能默认由Auth
Attempt
功能使用
public function postSignIn(Request $request) { $this->validate($request, [ 'email' => 'required', 'password' => 'required', ]); $email= $request->input['email']; $password= $request->input['password']; if (Auth::attempt(['email'=>$email,'password'=>$password'])) { return redirect('users/profile'); } return redirect('users/signInPage')->withErrors(['failure' => 'The credentials you entered did not match our records. Try again!',]); }
最后,当您使用默认中间件时,这会给您带来太多的重定向错误,因为您的逻辑现在与默认的逻辑不同,这就是您必须编写自定义中间件的原因,为此运行此命令
php artisan make:middleware CutomAuth
这将创建您的自定义中间件,现在由您的逻辑在其中编写代码并在app/Http/Kernel.php
中注册为\ n
'customauth' => \Illuminate\Auth\Middleware\CutomAuth::class,
你很高兴