基于 API 调用响应的自定义用户身份验证

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

描述:

我现在已经在很多项目中使用 Laravel。 在 Laravel 中实现用户身份验证很简单。现在,我正在处理的结构有点不同 - 我本地没有

database
users
表。我必须调用 API 来查询我需要的内容。


我已经尝试过

public function postSignIn(){

    $username     = strtolower(Input::get('username'));
    $password_api = VSE::user('password',$username); // abc <-----
    $password     = Input::get('password'); // abc <-----


    if ( $password == $password_api ) {
        //Log user in
        $auth = Auth::attempt(); // Stuck here <----
    }

    if ($auth) {
      return Redirect::to('/dashboard')->with('success', 'Hi '. $username .' ! You have been successfully logged in.');
    }
    else {
      return Redirect::to('/')->with('error', 'Username/Password Wrong')->withInput(Request::except('password'))->with('username', $username);
    }
  }

已更新

我在我的

shell_exec
类中使用简单的
VSE
命令连接到API

public static function user($attr, $username) {

        $data = shell_exec('curl '.env('API_HOST').'vse/accounts');
        $raw = json_decode($data,true);
        $array =  $raw['data'];
        return $array[$attr];
    }

我希望可以在这里向您展示这一点,但它位于我本地计算机上的虚拟机上,因此请留在此处。基本上,它

执行

curl http://172.16.67.137:1234/vse/accounts
<--- updated

回应

Object
data:Array[2]

0:Object
DBA:""
account_id:111
account_type:"admin"
address1:"111 Park Ave"
address2:"Floor 4"
address3:"Suite 4011"
city:"New York"
customer_type:2
display_name:"BobJ"
email_address:"[email protected]"
first_name:"Bob"
last_name:"Jones"
last_updated_utc_in_secs:200200300
middle_names:"X."
name_prefix:"Mr"
name_suffix:"Jr."
nation_code:"USA"
non_person_name:false
password:"abc"
phone1:"212-555-1212"
phone2:""
phone3:""
postal_code:"10022"
state:"NY"
time_zone_offset_from_utc:-5

1:Object
DBA:""
account_id:112
account_type:"mbn"
address1:"112 Park Ave"
address2:"Floor 3"
address3:"Suite 3011"
city:"New York"
customer_type:2
display_name:"TomS"
email_address:"[email protected]"
first_name:"Tom"
last_name:"Smith"
last_updated_utc_in_secs:200200300
middle_names:"Z."
name_prefix:"Mr"
name_suffix:"Sr."
nation_code:"USA"
non_person_name:false
password:"abd"
phone1:"212-555-2323"
phone2:""
phone3:""
postal_code:"10022"
state:"NY"
time_zone_offset_from_utc:-5
message:"Success"
status:200

如您所见,Bob 的密码是

abc
,Tom 的密码是
abd

php laravel authentication laravel-5.1
2个回答
18
投票

按照以下步骤,您可以设置自己的身份验证驱动程序,使用 API 调用来处理获取和验证用户凭据:

1.

app/Auth/ApiUserProvider.php
中创建您自己的自定义用户提供程序,包含以下内容:

namespace App\Auth;

use Illuminate\Contracts\Auth\UserProvider;
use Illuminate\Contracts\Auth\Authenticatable as UserContract;

class ApiUserProvider implements UserProvider
{
    /**
     * Retrieve a user by the given credentials.
     *
     * @param  array  $credentials
     * @return \Illuminate\Contracts\Auth\Authenticatable|null
     */
    public function retrieveByCredentials(array $credentials)
    {
        $user = $this->getUserByUsername($credentials['username']);

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

    /**
     * Retrieve a user by their unique identifier.
     *
     * @param  mixed  $identifier
     * @return \Illuminate\Contracts\Auth\Authenticatable|null
     */
    public function retrieveById($identifier)
    {
        $user = $this->getUserById($identifier);

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

    /**
     * Validate a user against the given credentials.
     *
     * @param  \Illuminate\Contracts\Auth\Authenticatable  $user
     * @param  array  $credentials
     * @return bool
     */
    public function validateCredentials(UserContract $user, array $credentials)
    {
        return $user->getAuthPassword() == $credentials['password'];
    }

    /**
     * Get the api user.
     *
     * @param  mixed  $user
     * @return \App\Auth\ApiUser|null
     */
    protected function getApiUser($user)
    {
        if ($user !== null) {
            return new ApiUser($user);
        }
    }

    /**
     * Get the use details from your API.
     *
     * @param  string  $username
     * @return array|null
     */
    protected function getUsers()
    {
        $ch = curl_init();

        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_URL, env('API_HOST') . 'vse/accounts');

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

        curl_close($ch);

        return $response['data'];
    }

    protected function getUserById($id)
    {
        $user = [];

        foreach ($this->getUsers() as $item) {
            if ($item['account_id'] == $id) {
                $user = $item;

                break;
            }
        }

        return $user ?: null;
    }

    protected function getUserByUsername($username)
    {
        $user = [];

        foreach ($this->getUsers() as $item) {
            if ($item['email_address'] == $username) {
                $user = $item;

                break;
            }
        }

        return $user ?: null;
    }

    // The methods below need to be defined because of the Authenticatable contract
    // but need no implementation for 'Auth::attempt' to work and can be implemented
    // if you need their functionality
    public function retrieveByToken($identifier, $token) { }
    public function updateRememberToken(UserContract $user, $token) { }
}

2. 还创建一个用户类,扩展

GenericUser
中身份验证系统提供的默认
app/Auth/ApiUser.php
,其中包含以下内容:

namespace App\Auth;

use Illuminate\Auth\GenericUser;
use Illuminate\Contracts\Auth\Authenticatable as UserContract;

class ApiUser extends GenericUser implements UserContract
{
    public function getAuthIdentifier()
    {
        return $this->attributes['account_id'];
    }
}

3. 在您的

app/Providers/AuthServiceProvider.php
文件的引导方法中,注册新的驱动程序用户提供程序:

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

    // The code below sets up the 'api' driver
    $this->app['auth']->extend('api', function() {
        return new \App\Auth\ApiUserProvider();
    });
}

4. 最后在您的

config/auth.php
文件中将驱动程序设置为您的自定义驱动程序:

    'driver' => 'api',

您现在可以在控制器操作中执行以下操作:

public function postSignIn()
{
    $username = strtolower(Input::get('username'));
    $password = Input::get('password');

    if (Auth::attempt(['username' => $username, 'password' => $password])) {
        return Redirect::to('/dashboard')->with('success', 'Hi '. $username .'! You have been successfully logged in.');
    } else {
        return Redirect::to('/')->with('error', 'Username/Password Wrong')->withInput(Request::except('password'))->with('username', $username);
    }
}

成功登录后调用

Auth::user()
获取用户详细信息,将返回一个
ApiUser
实例,其中包含从远程 API 获取的属性,看起来像这样:

ApiUser {#143 ▼
  #attributes: array:10 [▼
    "DBA" => ""
    "account_id" => 111
    "account_type" => "admin"
    "display_name" => "BobJ"
    "email_address" => "[email protected]"
    "first_name" => "Bob"
    "last_name" => "Jones"
    "password" => "abc"
    "message" => "Success"
    "status" => 200
  ]
}

由于您尚未发布当 API 中不匹配用户电子邮件时收到的响应示例,因此我在

getUserDetails
方法中设置了条件,以确定不存在匹配并返回
null
if响应不包含
data
属性或者
data
属性为空。您可以根据您的需要更改该条件。


上面的代码使用模拟响应进行了测试,该响应返回您在问题中发布的数据结构,并且效果非常好。

最后一点:您应该强烈考虑修改 API 以尽快处理用户身份验证(也许使用 Oauth 实现),因为发送密码(更令人担忧的是作为纯文本)并不是什么事情你想推迟做。


-1
投票

@Bogdan 已经很好地回答了这个问题。我有同样的问题,需要找到解决方案。如果有任何帮助,您可以参考我必须构建并记录在我们如何在 Laravel 中实现自定义仅 API 身份验证 的解决方案。我认为它在原理上与 Bogdan 提供的优秀的没有太大区别。

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