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

问题描述 投票:2回答:1

一直在尝试将外部身份验证与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
    }
}
php laravel-5.4
1个回答
0
投票

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

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

© www.soinside.com 2019 - 2024. All rights reserved.