首页 > 编程 > PHP > 正文

Laravel权限控制整理 Auth

2020-03-22 17:54:45
字体:
来源:转载
供稿:网友
  • 用户认证

    1. 自带用户认证

    简介

    Laravel 让实现认证机制变得非常简单。事实上,几乎所有的设置默认就已经完成了。有关认证的配置文件都放在 config/auth.php 里,而在这些文件里也都包含了良好的注释描述每一个选项的所对应的认证服务。

    Laravel 默认在 app 文件夹内就包含了一个使用默认 Eloquent 认证驱动的 App/User模型。
    注意:当为这个认证模型设计数据库结构时,密码字段至少有60个字符宽度。同样,在开始之前,请先确认您的 users (或其他同义) 数据库表包含一个名为 remember_token 长度为 100 的string类型、可接受 null 的字段。这个字段将会被用来储存「记住我」的 session token。也可以通过在迁移文件中使用 $table-rememberToken(); 方法。 当然, Laravel 5 自带的 migrations 里已经设定了这些字段。

    假如您的html' target='_blank'>应用程序并不是使用 Eloquent ,您也可以使用 Laravel 的查询构造器做 database 认证驱动。

    认证

    Laravel 已经预设了两个认证相关的控制器。 AuthController 处理新的用户注册和「登陆」,而 PasswordController 可以帮助已经注册的用户重置密码。

    每个控制器使用 trait 引入需要的方法。在大多数应用上,你不需要修改这些控制器。这些控制器用到的视图放在 resources/views/auth 目录下。你可以依照需求修改這些视图。

    表结构

    Laravel 自带的认证包括:用户注册、登录、密码重置,也自带整理了这几个功能所需要的数据结构,位于:
    database migrations 下,配置好数据库后,执行所有迁移:

    php artisan migrate

    数据库会自动生成:users(用户表)、password_resets(重置密码表)、migrations(迁移表)

    用户注册

    要修改应用注册新用户时所用到的表单字段,可以修改 App/Services/Registrar 类。这个类负责验证和建立应用的新用户。

    Registrar 的 validator 方法包含新用户时的验证规则,而 Registrar 的 create 方法负责在数据库中建立一条新的 User 记录。你可以自由的修改这些方法。Registrar 方法是通过AuthenticatesAndRegistersUsers trait 的中的 AuthController 调用的。
    可以看一下源码:

    class Registrar implements RegistrarContract {    /**     * Get a validator for an incoming registration request.     *     * @param  array  $data     * @return /Illuminate/Contracts/Validation/Validator     */    public function validator(array $data)    {        return Validator::make($data, [            'name' => 'required|max:255',            'email' => 'required|email|max:255|unique:users',            'password' => 'required|confirmed|min:6',        ]);    }    /**     * Create a new user instance after a valid registration.     *     * @param  array  $data     * @return User     */    public function create(array $data)    {        return User::create([            'name' => $data['name'],            'email' => $data['email'],            'password' => bcrypt($data['password']),        ]);    }}

    2. 手动用户认证

    如果你不想使用预设的 AuthController,你需要直接使用 Laravel 的身份验证类来管理用户认证。别担心,这也很简单的!首先,让我们看看 attempt 方法:

    <?php namespace App/Http/Controllers;use Auth;use Illuminate/Routing/Controller;class AuthController extends Controller {    /**     * Handle an authentication attempt.     *     * @return Response     */    public function authenticate()    {        if (Auth::attempt(['email' => $email, 'password' => $password]))        {            return redirect()->intended('dashboard');        }    }}

    attempt 方法可以接受由键值对组成的数组作为第一个参数。password 的值会先进行 哈希。数组中的其他 值会被用来查询数据表里的用户。所以,在上面的示例中,会根据 email 列的值找出用户。如果找到该用户,会比对数据库中存储的哈希过的密码以及数组中的哈希过后的 password值。假设两个哈希后的密码相同,会重新为用户启动认证通过的 session。

    如果认证成功, attempt 将会返回 true。否则则返回 false。

    ** 注意:在上面的示例中,并不一定要使用 email 字段,这只是作为示例。你应该使用对应到数据表中的「username」的任何键值。

    intended 方法会重定向到用户尝试要访问的 URL , 其值会在进行认证过滤前被存起来。也可以给这个方法传入一个预设的 URI,防止重定向的网址无法使用。

    以特定条件验证用户

    在认证过程中,你可能会想要加入额外的认证条件:

    if (Auth::attempt(['email' => $email, 'password' => $password, 'active' => 1])){    // The user is active, not suspended, and exists.}

    如你说看到的,这个验证中加入了一个active 字段的验证。

    认证用户并且「记住」他

    假如你想要在应用中提供「记住我」的功能,你可以传入布尔值作为 attempt 方法的第二个参数,这样就可以保留用户的认证身份(或直到他手动登出为止)。当然,你的 users 数据表必需包括一个字符串类型的 remember_token 列來储存「记住我」的标识。

    if (Auth::attempt(['email' => $email, 'password' => $password], $remember)){    // The user is being remembered...}

    假如有使用「记住我」功能,可以使用 viaRemember 方法判定用户是否拥有「记住我」的 cookie 來判定用户认证:

    if (Auth::viaRemember()){    //}

    3. 判断用户是否已验证

    判断一个用户是否已经登录,你可以使用 check 方法:

    if (Auth::check()){    // The user is logged in...}

    4. 只验证不登录

    validate 方法可以让你验证用户凭证信息而不用真的登陆应用

    if (Auth::validate($credentials)){    //}

    5. 在单一请求内登陆用户

    你也可以使用 once 方法來让用户在单一请求内登陆。不会有任何 session 或 cookie 产生:

    if (Auth::once($credentials)){    //}

    6. 用户实例登录

    假如你需要将一个已经存在的用户实例登陆应用,你可以调用 login 方法并且传入用户实例:

    Auth::login($user);

    安全退出

    当然,假设你使用 Laravel 內建的认证控制器,预设提供了让用户登出的方法。

    Auth::logout();

    取得通过验证的用户实例

    1. 从 Auth facade 取得
    <?php namespace App/Http/Controllers;use Illuminate/Routing/Controller;class ProfileController extends Controller {    /**     * Update the user's profile.     *     * @return Response     */    public function updateProfile()    {        if (Auth::user())        {            // Auth::user() returns an instance of the authenticated user...        }    }}

    2. Illuminate/Http/Request 实例取得
    <?php namespace App/Http/Controllers;use Illuminate/Http/Request;use Illuminate/Routing/Controller;class ProfileController extends Controller {    /**     * Update the user's profile.     *     * @return Response     */    public function updateProfile(Request $request)    {        if ($request->user())        {            // $request->user() returns an instance of the authenticated user...        }    }}

    3.使用 Illuminate/Contracts/Auth/Authenticatable contract 类型提示
    <?php namespace App/Http/Controllers;use Illuminate/Routing/Controller;use Illuminate/Contracts/Auth/Authenticatable;class ProfileController extends Controller {    /**     * Update the user's profile.     *     * @return Response     */    public function updateProfile(Authenticatable $user)    {        // $user is an instance of the authenticated user...    }}

    参考地址:http://laravel-china.org/docs/5.0/authentication

    PHP编程

    郑重声明:本文版权归原作者所有,转载文章仅为传播更多信息之目的,如作者信息标记有误,请第一时间联系我们修改或删除,多谢。

  • 发表评论 共有条评论
    用户名: 密码:
    验证码: 匿名发表