Laravel Rest API中的身份验证和用户管理
我正在为移动应用程序编写rest API.我不知道如何在我的应用程序中对用户和管理员进行身份验证. 我有一个名为"用户"的表,并且有一个名为" isAdmin "的字段,该字段为 0 或 1 . 现在,当管理员发送帖子时,用户可以看到帖子.您如何为这两项推荐 auth ? 谢谢
I'm writing a rest API for a mobile app. I don't know how to auth users and admins in my app. I have a table named "users" and have a field called "isAdmin" that is 0 or 1. now when admin sends posts, users can see posts.how do you recommend auth for both of these? thank you
I recommend you read the documentation about authentication on laravel: https://laravel.com/docs/5.5/authentication
您需要设置的内容如下:
- 中间件(用户可以使用哪些路由,管理员可以使用哪些路由)
- 使用 isAdmin()函数编辑模型以确定用户是用户还是管理员
- Middleware (what routes can the user use and what routes can the admin use)
- Edit your model with an isAdmin() function to determine if an user is user or admin
AdminMiddleware文件的示例 -通过命令行创建:php artisan make:middleware AdminMiddleware
<?php
namespace App\Http\Middleware;
use Closure;
use Auth;
class AdminMiddleware
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
if(Auth::check() && Auth::user()->isAdmin()){
return $next($request);
}
else{
return view('your_view')->withErrors('You are not logged in');
}
}
}
用户模型isAdmin函数的示例 -通过命令行创建:php artisan make:model User
public function isAdmin(){
if($this->isAdmin == 1){
return true;
} else {
return false;
}
}
路由文件示例
// @TODO: Set routes for user and admin here...
Route::group(['middleware' => ['admin']], function () {
// @TODO: Set admin routes here, only admin can use this routes.
});
您还必须对Kernel.php进行一些
protected $routeMiddleware = [
// ... add this line
'admin' => \App\Http\Middleware\AdminMiddleware::class,
];