Laravel Rest API中的身份验证和用户管理 [英] Auth and user management in laravel rest api

查看:271
本文介绍了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

推荐答案

我建议您阅读有关laravel上身份验证的文档:

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,
];

这篇关于Laravel Rest API中的身份验证和用户管理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆