Laravel 中间件,用于使用单独的管理表登录?



如何在不使用用户表的情况下创建Laravel 5中间件以使用单独的管理表登录?

您可以为admin 定义一个单独的 VerfiyCsrfToken 文件,调用为 VerifyAdminCsrfToken。

您的路由/web.php文件如下所示:

Route::group(array('prefix'=>'Api/v1/admin'),function()
{
Route::post('login','AdminController@login');
});
Route::group(['middleware'=>'admin.csrf','prefix'=>'Api/v1/admin'],function($router){
Route::get('getAdminDetails','AdminController@getAdminDetails');     
/*Call Rest all routes after admin login like this and this request 
goes through the VerifyAdminCsrfToken.php handle request.*/
});

app/Http/Kernel.php看起来像这样

protected $routeMiddleware = [
'auth'       => IlluminateAuthMiddlewareAuthenticate::class,
'auth.basic' => IlluminateAuthMiddlewareAuthenticateWithBasicAuth::class,
'bindings'   => IlluminateRoutingMiddlewareSubstituteBindings::class,
'can'        => IlluminateAuthMiddlewareAuthorize::class,
'guest'      => AppHttpMiddlewareRedirectIfAuthenticated::class,
'throttle'   => IlluminateRoutingMiddlewareThrottleRequests::class,
'admin.csrf' => AppHttpMiddlewareVerifyAdminCsrfToken::class,
];

登录成功后,将id_admin和 csrf 令牌分别设置为标头中的 X-Id-Admin 和 X-Admin-Csrf-Token。

验证AdminCsrfToken.php=> 在登录路由/apis之后处理。

<?php namespace AppHttpMiddleware;
class VerifyAdminCsrfToken {
public function handle($request, Closure $next)
{
$token = Request::header('X-Admin-Csrf-Token');
$id_admin = Request::header('X-Id-Admin');
$adminObject=new AppModelsAdmin();
$adminDetails = $adminObject->checkAdminToken($id_admin,$token); // function to identify the admin in admin model based on id_admin and token.
// echo Session::token() .'==='. $csrfToken; //exit();
if(!$adminDetails&&count($adminDetails)==0)
{
return Response::json(array('error'=>true,'message'=>'Unauthorized 
Request'),401);
}
else{  
$userDet                    =   array();
$userDet['id_admin']        =   $adminDetails->id_admin;
$userDet['name']            =   $adminDetails->name;
$request->userDet=$userDet;
return $next($request);
}
}

管理控制器.php内容如下:

<?php
namespace AppHttpControllers;
class AdminController extends Controller
{
public function login(Request $request){
$admin_email = $request->input('email');
$password = $request->input('password');
$adminObj = new AppModelsAdmin();
$loginCheck=$adminObj->checkAdminLogin($admin_email,$password);// function to identify the admin in admin model based in admin_email and password.  
if($loginCheck&&count($loginCheck)>0){
$token = $loginCheck->token;
return response()->json(['message'=>'Successfully logged 
in','user_detail'=>$loginCheck,'csrf_token'=>$token],200);
}else{
return response()->json(array('message'=>'These credentials did not 
match our record'),403);
}
}

对于 API 调用我的管理员.js文件如下所示。 它是一个角度的JS文件。 这只是处理来自客户端的 API 调用的示例。

var SITE_URL=localhost/projectfolder/+'index.php/Api/v1/admin/';
$scope.credentials={admin_email:'####@gmail.com',password:'###'};
$http({
method: "POST",
timeout: 30000,
url: SITE_URL+'login',
data: $.param($scope.credentials),//posting data from login form
headers: {'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'}
}).success(function (data,status) {
if(status==200)
{
$http.defaults.headers.common['X-Admin-Csrf-Token']   = data.token; //For all $http request it will apply this header.
$http.defaults.headers.common['X-Id-Admin']   = data.user_detail.id_admin; //For all $http request will ll apply this header.
}).error(function (data, status) {
$scope.actionDisabled=false;
if(status==401)
{
console.log(data.message);//invalid credentials
}  
});
$http({
method: "GET",
url: SITE_URL+'getAdminDetails',
headers: {'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'} //with this content type newly set headers(X-Id-Admin,X-Admin-Csrf-Token) will be sent and handled the request thorough Laravel newly created middleware.
}).success(function (response,status) {
console.log(response);//admin detailed response from server
});

最新更新