让我们说我有一个非常基本的身份验证过程,在此只需输入正确的安全密钥即可。没有诸如用户表之类的东西。我要检查的是,是否输入的字符串与我的安全密钥匹配。使用laravel auth可以实现吗?如果是,怎么办?
答案 0 :(得分:1)
如果您不想使用任何持久性数据(例如数据库),则可以使用会话。覆盖LoginController中的登录方法,并在那里进行检查。
public function login(Request $request)
{
if($request->input('security_key') === 'my_secret_string') {
$request->session()->put('isAuthenticated', true);
return redirect()->intended('success');
}
return back()->withErrors('Invalid secret key');
}
然后创建一个中间件来检查用户是否已通过身份验证。我们称之为check_auth:
public function handle($request, Closure $next)
{
if(!empty(session('isAuthenticated')) && session('isAuthenticated') === true) {
return $next($request);
}
return redirect('/login');
}
并在您的路由中添加中间件:
Route::group(['middleware' => ['web', 'check_auth']], function () {
//your routes here
});
不要忘记将新的中间件添加到kernel.php
文件中:
protected $routeMiddleware = [
'auth' => \App\Http\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,
'can' => \Illuminate\Auth\Middleware\Authorize::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class,
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
'check_auth' => 'App\Http\Middleware\check_auth' //add this
];