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

     2023-03-14     218

关键词:

【中文标题】基于 API 调用响应的自定义用户身份验证【英文标题】:Custom user authentication base on the response of an API call 【发布时间】:2016-01-24 16:57:35 【问题描述】:

说明:

我现在一直在使用 Laravel 进行一系列项目。 在 Laravel 中实现用户认证很简单。现在,我正在处理的结构有点不同 - 我在本地没有 databaseusers 表。我必须调用 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);
    
  

更新

我在 VSE 类中使用简单的 shell_exec 命令连接到 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];
    

我希望我可以在这里向您展示,但它在我本地机器上的 VM 上,所以请留在我这里。基本上,它

执行

curl http://172.16.67.137:1234/vse/accounts

回应

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:"bob@xyzcorp.com"
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:"tom@xyzcorp.com"
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

【问题讨论】:

您可以extend the Laravel authentication system 创建自己的用户提供程序来处理登录验证和用户详细信息,并将其设置为身份验证驱动程序。 如果您发现文档不够详细,那么您可以查看Illuminate\Auth\DatabaseUserProvider 源代码,了解它如何处理数据库存储用户并将逻辑应用到您的远程 API。 如果您提供一些代码来展示您如何连接到 API,以及您为验证和获取用户信息所做的请求,那么我可能能够提供有关如何连接到 API 的答案将 API 调用集成到 Laravel Auth 驱动程序中。 那么身份验证将通过检查用户输入的凭据与 cURL 请求返​​回的凭据来完成? 是的,先生。我知道这很糟糕,但这只是项目的开始。它仅用于演示目的。 【参考方案1】:

按照以下步骤,您可以设置自己的身份验证驱动程序,该驱动程序使用您的 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. 还创建一个用户类,扩展app/Auth/ApiUser.php 中身份验证系统提供的默认GenericUser,其内容如下:

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() 获取用户详细信息,将返回一个包含从远程 API 获取的属性的 ApiUser 实例,如下所示:

ApiUser #143 ▼
  #attributes: array:10 [▼
    "DBA" => ""
    "account_id" => 111
    "account_type" => "admin"
    "display_name" => "BobJ"
    "email_address" => "bob@xyzcorp.com"
    "first_name" => "Bob"
    "last_name" => "Jones"
    "password" => "abc"
    "message" => "Success"
    "status" => 200
  ]

由于您尚未发布用户电子邮件的 API 中不匹配时收到的响应示例,因此我在 getUserDetails 方法中设置了条件,以确定不匹配并返回 @987654335 @ 如果响应不包含 data 属性或 data 属性为空。您可以根据需要更改该条件。


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

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

【讨论】:

我刚刚意识到我连接到了错误的 URL。我想改为向:/vse/accounts 提出请求。我希望你不介意在step 1 上调整你的答案。对此我很抱歉。我只是自己调整它,但它坏了。这是第一次,我正在和司机打交道。 所以应该是'/vse/accounts/user/' . $username? 我测试过了。它完美地工作。我在这里遇到的最后一个小问题是我似乎无法从我的 Auth::user() 实例中获取任何东西。 需要安装 cURL 扩展才能使这些方法可用。要检查这一点,您只需在登台服务器 php -m | grep curl 上运行此命令。如果安装了扩展,它应该输出 "curl",否则它不会输出任何东西。 在 auth.php 中有几行写着“驱动程序”。显示没有上下文的单行与有帮助完全相反。

laravel 基于 API 响应调用的自定义认证

】laravel基于API响应调用的自定义认证【英文标题】:laravelcustomauthenticationbasedonAPIresponsecall【发布时间】:2019-06-2516:56:02【问题描述】:目前我使用Laravel5.7并尝试构建登录机制。类似CustomuserauthenticationbaseontheresponseofanAPIcall的情... 查看详情

Kong API 网关中的自定义身份验证服务

...一。我们发现Kong支持多个身份验证插件,但所有插件都基于存储在Kong数据库本身中的用户。我们需要将此责任委托给我们的自定义身份验证HTTP服务,并且不想将这些用户 查看详情

Api 的自定义身份验证 Azure 移动服务

...ces然后加入上一个链接的代码来创建认证令牌。但是当我调用API时 查看详情

创建通过外部 API 进行身份验证的自定义身份验证提供程序?

】创建通过外部API进行身份验证的自定义身份验证提供程序?【英文标题】:CreateacustomauthproviderthatauthenticatethroughanexternalAPI?【发布时间】:2017-05-1202:06:44【问题描述】:我是Laravel的新手。我已经有一个API可以对用户进行身份验... 查看详情

ServiceStack 对身份验证失败的自定义响应

】ServiceStack对身份验证失败的自定义响应【英文标题】:ServiceStackcustomresponseonfailedauthentication【发布时间】:2018-03-0213:43:29【问题描述】:我为servicestack创建了一个自定义身份验证,效果很好。唯一的问题是,当我未登录时,每... 查看详情

springboot 微服务中的自定义 JWT 令牌

...后从外部系统加载信息(特定于用户),为了避免每次api调用到外部系统的往返,我们计划首先创建一个带有用户特定信息的自定义JWT令牌当用户通过身份验证时,然后使用http拦截器在每个响应标头中将令牌发送给用户, 查看详情

Web API 的基于角色的身份验证不起作用

】WebAPI的基于角色的身份验证不起作用【英文标题】:RoleBasedAuthenticationforwebAPInotworking【发布时间】:2020-12-2116:59:40【问题描述】:我在为WebAPi使用基于角色的身份验证时遇到问题。我有一个控制器类,其中控制器有一个名为Mya... 查看详情

使用 JWT 进行护照身份验证:如何将护照的默认未经授权响应更改为我的自定义响应?

】使用JWT进行护照身份验证:如何将护照的默认未经授权响应更改为我的自定义响应?【英文标题】:PassportauthenticationwithJWT:HowcanIchangepassport\'sdefaultunauthorizedresponsetomycustomresponse?【发布时间】:2019-05-3020:08:26【问题描述】:我... 查看详情

Azure 门户的自定义身份验证

】Azure门户的自定义身份验证【英文标题】:CustomAuthenticationforAzurePortal【发布时间】:2016-02-2212:40:50【问题描述】:我有一个AzureEnterprise订阅,我正在开发一个Asp.NetMVCWeb应用程序并有以下问题我的Web应用程序将维护用户存储,... 查看详情

使用基于适配器的身份验证实现时,无法实现基于用户订阅的推送通知

】使用基于适配器的身份验证实现时,无法实现基于用户订阅的推送通知【英文标题】:UnabletoimplementusersubscriptionbasedPushNotificationswhenimplementedwithAdapterbasedauthentication【发布时间】:2015-09-1113:15:23【问题描述】:我已经定义了一... 查看详情

使用 API 调用的 ZAP 身份验证

...在上下文中(context/includeContext)2.将身份验证方法更改为基于表单 查看详情

与 Django Rest Framework 的非用户连接的自定义身份验证

】与DjangoRestFramework的非用户连接的自定义身份验证【英文标题】:CustomAuthenticationfornon-userconnectionwithDjangoRestFramework【发布时间】:2015-09-1000:06:41【问题描述】:我已使用TokenAuthentication通过DRF启用用户身份验证REST_FRAMEWORK=\'DEFAULT... 查看详情

使用 aws amplify cognito 的自定义身份验证流程

】使用awsamplifycognito的自定义身份验证流程【英文标题】:CustomAuthenticationflowwithawsamplifycognito【发布时间】:2021-03-2305:25:53【问题描述】:我想在awsamplifycognito服务中创建自定义注册身份验证流程我有什么1.输入用户名2.输入密码3... 查看详情

Symfony2 - 安装了 FOS 用户包的自定义身份验证提供程序

】Symfony2-安装了FOS用户包的自定义身份验证提供程序【英文标题】:Symfony2-customauthenticationproviderwithFOSUserBundleinstalled【发布时间】:2015-11-0604:30:46【问题描述】:我在Symfony2项目中构建自定义身份验证方面需要帮助。我已经阅读... 查看详情

spring rest API 的所有查询的自定义验证

】springrestAPI的所有查询的自定义验证【英文标题】:CustomvalidationforallthequeryofspringrestAPI【发布时间】:2020-02-2119:15:03【问题描述】:我正在使用SpringRestAPI,并且我想在进入restapi查询之前应用自定义验证(更具体地说,我想检查... 查看详情

Squid 基于 Web 的代理身份验证

】Squid基于Web的代理身份验证【英文标题】:Squidwebbasedproxyauthentication【发布时间】:2011-04-0102:59:46【问题描述】:我是Squid的新手,目前我已经使用外部ACL成功设置了基本身份验证来验证用户名和密码。这很好用,但我希望有一... 查看详情

KeyCloak 中的自定义提供程序,可以根据用户名和密码进行身份验证

】KeyCloak中的自定义提供程序,可以根据用户名和密码进行身份验证【英文标题】:CustomproviderinKeyCloakwhichcandotheauthenticationbasedonusernameandpassword【发布时间】:2019-06-1701:42:29【问题描述】:我有一个WebApp,它使用Grant-Type:password发... 查看详情

没有用户模型的 Django 基于令牌的身份验证

】没有用户模型的Django基于令牌的身份验证【英文标题】:Django\'sTokenbasedAuthenticationwithoutUsermodel【发布时间】:2017-11-0200:59:00【问题描述】:我正在使用基于Django令牌的身份验证。(JWTToken由AWSCognito等第三方服务生成,我们只... 查看详情