如何创建Laravel 5.1 Custom Authentication驱动程序?

vis*_*ion 10 php laravel laravel-5 laravel-5.1

我正在使用socialite在Laravel身份验证登录中工作.现在我可以从社交网站保存用户数据了.但是现在我面临着如何从gmail,github验证用户的问题.

经过一些研究后,我了解到我需要创建自定义身份验证.我用Google搜索,但都是Laravel 4.1主题.如果有人就此工作,请提供您的答案.

我已经阅读了以下主题,但我没有怎么做?

http://laravel.com/docs/5.1/authentication#social-authentication

http://laravel.com/docs/5.1/providers

http://laravel-recipes.com/recipes/115/using-your-own-authentication-driver

http://laravel.io/forum/11-04-2014-laravel-5-how-do-i-create-a-custom-auth-in-laravel-5

更新

public function handleProviderCallback() {
    $user = Socialite::with('github')->user();
    $email=$user->email;
    $user_id=$user->id;

    //$authUser = User::where('user_id',$user_id)->where('email', $email)->first();
    $authUser = $this->findOrCreateUser($user);

    if(Auth::login($authUser, true)) {
        return Redirect::to('user/UserDashboard');
    }   
}

private function findOrCreateUser($user) {
    if ($authUser = User::where('user_id',$user->id)->first()) {
        return $authUser;
    }

    return User::create([
        'user_id' => $user->id,
        'name' => $user->nickname,
        'email' => $user->email,
        'avatar' => $user->avatar
    ]);
}
Run Code Online (Sandbox Code Playgroud)

Ras*_*ash 16

这个答案最适合Laravel 5.1.如果您使用其他版本,请注意.还要记住,恕我直言,这是Laravel的一个相当高级的水平,因此如果你不完全了解你在做什么,你最终可能会崩溃你的应用程序.解决方案不是端到端正确的.这只是您需要做的一般准则才能使其发挥作用.

在Laravel 5.1中添加自定义身份验证驱动程序

提示:此主题的Laravel文档在此处.

提示2:你提到的最后一个链接在我看来非常有用.阅读完该链接后,我学会了所有这些.

http://laravel.io/forum/11-04-2014-laravel-5-how-do-i-create-a-custom-auth-in-laravel-5


在开始之前,我首先要描述一下登录流程,它将帮助您理解该过程.Laravel使用a driver连接数据库来获取记录.两名司机预先捆绑了laravel - eloquent&database.我们想要创建第三个,以便我们可以根据我们的需求进行定制.

Illuminate\Auth\Guard在您的供应商文件夹中是主文件,其中包含用户登录和注销的代码.此文件主要使用两个Contracts (or interfaces)我们需要覆盖的文件,以便我们的驱动程序工作.从Laravel自己的文档中读取:

Illuminate\Contracts\Auth\UserProvider实现仅负责从持久性存储系统(如MySQL,Riak等)中获取Illuminate\Contracts\Auth\Authenticatable实现.这两个接口允许Laravel身份验证机制继续运行,无论如何如何存储用户数据或使用什么类型的类来表示它.

这样的想法是,我们的司机的工作,我们需要实现Illuminate\Contracts\Auth\UserProviderIlluminate\Contracts\Auth\Authenticatable告诉Laravel改为使用默认的这些实现.


让我们开始吧.

Step 1: 选择驱动程序的名称.我说我的名字socialite.然后在您config/auth.phpdriver名称中更改名称socialite.通过这样做,我们告诉laravel使用此驱动程序进行身份验证,而不是eloquent默认情况.

Step 2: 在您app/Provider/AuthServiceProviderboot()方法中添加以下行:

Auth::extend('socialite', function($app) {
    $provider = new SocialiteUserProvider();
    return new AuthService($provider, App::make('session.store'));
});
Run Code Online (Sandbox Code Playgroud)

我们在这里做的是:

  • 我们首先使用Authfacade来定义socialite驱动程序.
  • SocialiteUserProvider是一个实现UserProvider.
  • AuthService是我的Guard课程延伸.此类的构造函数采用的第二个参数是laravel用于获取和设置会话的会话.
  • 所以我们基本上告诉Laravel使用我们自己的Guard类实现而不是默认类.

Step 3: 创造SocialiteUserProvider.如果您阅读Laravel的文档,您将了解每种方法应返回的内容.我已经创建了第一个方法作为样本.如您所见,我使用我的UserService类来获取结果.您可以获取自己的结果,但想要获取它们.然后我创建了一个User对象.这个User类实现了Illuminate\Contracts\Auth\Authenticatable合同.

<?php
namespace App\Extensions;

use App\User;
use App\Services\UserService;
use Illuminate\Contracts\Auth\Authenticatable;
use Illuminate\Contracts\Auth\UserProvider;

class SocialiteUserProvider implements UserProvider
{
    private $userService;

    public function __construct(UserService $userService)
    {
        $this->userService = $userService;
    }

    public function retrieveById($identifier)
    {
        $result = $this->userService->getUserByEmail($identifier);
        if(count($result) === 0)
        {
            $user = null;
        }
        else
        {
            $user = new User($result[0]);
        }

        return $user;
    }

    public function retrieveByToken($identifier, $token)
    {
        // Implement your own.
    }

    public function updateRememberToken(Authenticatable $user, $token)
    {
        // Implement your own.
    }

    public function retrieveByCredentials(array $credentials)
    {
        // Implement your own.
    }

    public function validateCredentials(Authenticatable $user, array $credentials)
    {
        // Implement your own.
    }
}
Run Code Online (Sandbox Code Playgroud)

Step 4: 创建User实现的类Authenticatable.此类必须实现此接口,因为Guard该类将使用此类来获取值.

<?php
namespace App;

use Illuminate\Contracts\Auth\Authenticatable;

class User implements Authenticatable
{
    protected $primaryKey = 'userEmail';
    protected $attributes = [];

    public function __construct(array $attributes)
    {
        $this->attributes = $attributes;
    }

    public function getUserAttributes()
    {
        return $this->attributes;
    }

    public function getAuthIdentifier()
    {
        return $this->attributes[$this->primaryKey];
    }

    public function getAuthPassword()
    {
        // Implement your own.
    }

    public function getRememberToken()
    {
        // Implement your own.
    }

    public function setRememberToken($value)
    {
        // Implement your own.
    }

    public function getRememberTokenName()
    {
        // Implement your own.
    }
}
Run Code Online (Sandbox Code Playgroud)

Step 5: 最后创建将调用Guard方法的AuthService类.这是我自己的实现.您可以根据自己的需要自行编写.我们在这里做的是扩展Guard该类以实现两个自我解释的新函数.

<?php
namespace App\Services;

use Illuminate\Auth\Guard;

class AuthService extends Guard
{
    public function signin($email)
    {
        $credentials = array('email' => $email);
        $this->fireAttemptEvent($credentials, false, true);
        $this->lastAttempted = $user = $this->provider->retrieveById($email);

        if($user !== null)
        {
            $this->login($user, false);
            return true;
        }
        else
        {
            return false;
        }
    }

    public function signout()
    {
        $this->clearUserDataFromStorage();

        if(isset($this->events))
        {
            $this->events->fire('auth.logout', [$this->user()]);
        }

        $this->user = null;
        $this->loggedOut = true;
    }
}
Run Code Online (Sandbox Code Playgroud)

Step 6: Bonus Step 为了完成我的答案,我还将解释该UserService课程所期望的结构.首先让我们了解这个课程的作用.在上面的步骤中,我们创建了所有内容,让laravel知道如何使用我们的身份验证驱动程序,而不是他们的.但我们仍然没有告诉laravel应该如何获取数据.我们告诉laravel,如果你打电话给userService->getUserByEmail($email)方法,你将得到你的数据.所以现在我们只需要实现这个功能.

你正在使用Eloquent.

public function getUserByEmail($email)
{
    return UserModel::where('email', $email)->get();
}
Run Code Online (Sandbox Code Playgroud)

Eg2您正在​​使用Fluent.

public function getUserByEmail($email)
{
    return DB::table('myusertable')->where('email', '=', $email)->get();
}
Run Code Online (Sandbox Code Playgroud)

更新:2016年6月19日

谢谢@skittles指出我没有清楚地显示文件的放置位置.所有文件都按照给定的命名空间放置.例如,如果名称空间是App\Extensions,并且类名是SocialiteUserProvider则文件的位置是App\Extensions\SocialiteUserProvider.php.将App在laravel目录是app文件夹.


nat*_*mac 0

在此处设置 Laravel Socialite 的好教程:https://mattstauffer.co/blog/using-github-authentication-for-login-with-laravel-socialite

Auth::login不返回布尔值,您可以尝试执行Auth::attempt

if(Auth::login($authUser, true)) {
    return Redirect::to('user/UserDashboard');
}
Run Code Online (Sandbox Code Playgroud)

按照教程执行此操作,只需在主路由上配置中间件

$authUser = $this->findOrCreateUser($user);

Auth::login($authUser, true);

return Redirect::to('home');
Run Code Online (Sandbox Code Playgroud)