基于API调用的Laravel 5.4自定义用户身份验证

时间:2018-05-26 19:09:07

标签: php laravel-5.4

尝试将外部身份验证与Laravel的身份验证相结合,我似乎无法使其正常工作

阅读并尝试了我在stackoverflow Custom user authentication base on the response of an API call中找到的这篇文章,基于这篇文章,我已经成功地将外部认证的用户信息放到Laravel的Auth系统中。

我的问题是当我登录并使用该凭据登录外部API时(假设我们从API成功获取用户信息)并重定向到另一个页面,Auth::user()似乎无法正常工作总是返回null值,看起来会话没有持久...

我还尝试创建自定义会话以将来自API的返回数据放入ApiUserProvider中,以便稍后在其他路由中访问它,但会话会丢失....

我希望有人可以帮助我,谢谢

PS:我正在使用Laravel 5.4

配置/ auth.php

'providers' => [
        'users' => [
            'driver' => 'api',
        ],
    ],

应用/提供者/ AuthServiceProvider

namespace App\Providers;

use Illuminate\Support\Facades\Auth;
use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;

class AuthServiceProvider extends ServiceProvider
{
    protected $policies = [
        'App\Model' => 'App\Policies\ModelPolicy',
    ];

    public function boot()
    {
        $this->registerPolicies();

        Auth::provider('api', function ($app, array $config) {
            return new \App\Providers\ApiUserProvider($this->app['hash']);
        });
    }
}

应用/提供者/ ApiUserProvider.php

namespace App\Providers;

use Illuminate\Support\Facades\Auth;
use Illuminate\Contracts\Auth\UserProvider;
use Illuminate\Contracts\Hashing\Hasher as HasherContract;
use Illuminate\Contracts\Auth\Authenticatable as UserContract;

class ApiUserProvider implements UserProvider
{
    protected $hasher;

    public function __construct(HasherContract $hasher)
    {
        $this->hasher = $hasher;
    }

    public function retrieveByCredentials(array $credentials)
    {

        $user = [];

        $post = [
            'username' => $credentials['username'],
            'password' => $credentials['password']
        ];

        $ch = curl_init();

        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_URL, 'https://sample.com/dev/admin/login'); 
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($post));
        curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type:application/json'));

        $response = curl_exec($ch);
        $response = json_decode($response, true);

        curl_close($ch);

        if(isset($response['successful']) && $response['successful']) {
            $response['claims'] =  json_decode(base64_decode(explode('.', $response['token'])[1]));
            $response['password'] =  bcrypt($credentials['password']);
            $response['username'] =  $credentials['username'];
            $response['id'] =  $response['claims']->client_id;
            $response['remember_token'] =  null;

            $user = $response;
            session()->put($response['claims']->client_id, $response); //<--- I attempt to put it in session
        }

        $user = $user ? : null;

        return $this->getApiUser($user);
    }

    public function retrieveById($identifier)
    {
        //$user = $this->getUserById($identifier);
        $user = session()->get($identifier);  //<---- attempted to retrieve the user, but session don't exists if I go in other route 
        return $this->getApiUser($user);
    }

    public function validateCredentials(UserContract $user, array $credentials)
    {
         return $this->hasher->check(
            $credentials['password'], $user->getAuthPassword()
        );
    }

    protected function getApiUser($user)
    {
        if ($user !== null) {
            return new \App\ApiUser((array) $user);
        }
    }

    protected function getUserById($id)
    {
        $user = session()->get($id);
        return $user ?: null;
    }

    public function retrieveByToken($identifier, $token) { }
    public function updateRememberToken(UserContract $user, $token) { }
}

UserController.php

namespace App\Http\Controllers;

use Illuminate\Support\Facades\Auth;
use Illuminate\Http\Request;
use Illuminate\Contracts\Auth\SessionGuard;

class UserController extends Controller
{ 
     protected function attemptLogin(Request $request)
    {
        return $this->guard()->attempt($this->credentials($request));
    }

    protected function guard()
    {
        return Auth::guard();
    }

    protected function credentials(Request $request)
    {
        return $request->only('username', 'password');
    }

    public function login(Request $request)
    {
         if ($this->attemptLogin($request)) {
             dd(auth());
             return "T";
         }

         return "F";
    }

    public function getCurrentUserInfo(Request $request)
    {
        dd(auth()); //<------------- user info no longer exist here
    }
}

1 个答案:

答案 0 :(得分:0)

我认为这是因为我在登录时使用的是api路由,这就是为什么它未在auth会话中存储在信息中的原因,

我尝试在api路由中添加startsession中间件,但它可以正常工作,但我认为这是不对的,因为api路由必须是无状态的。