【问题标题】:How do I access the oauth2 authenticated user in a Lumen controller?如何在 Lumen 控制器中访问经过 oauth2 身份验证的用户?
【发布时间】:2016-03-14 02:38:45
【问题描述】:

我已经按照这个优秀的教程Building a Web App with Lumen and OAuth2 来设置 OAuth2 和 Lumen。除了现在一切正常之外,我想访问当前经过身份验证的用户信息/模型。

我的路由在我登录后正确发布了提供的信息,我可以在控制器内与 Netbeans 中断,但我不清楚如何从底层 Auth 框架获取用户。我尝试了Authentication - Laravel 此处指出的三种方法,但无济于事。流明日志显示:

==== routes.php ====

$app->group(['namespace' => 'App\Http\Controllers','prefix' => 'api', 'middleware' => 'oauth'], function($app)
{
    $app->post('info', 'InfoController@send');
}

==== InfoController.php ====
namespace App\Http\Controllers;

// the controllers
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;

use Illuminate\Contracts\Auth\Authenticatable;

class InfoController extends Controller{

    /* /api/info methods */

    public function send(Request $request){

        // can iterate over the entire users table but I just
        // want the current user (must be some method through
        // the authentication stack)
        $users = \App\Auth\User::all();

        foreach ($users as $user) {
           $name = $user->name;
           $key = $user->getAuthIdentifier();
           $pwd = $user->getAuthPassword();
        }

        // CODE GETS HERE BUT how to get the current user?
        // Authenticated OK (request supplies "Access-Token: Bearer ...")
    }
}

【问题讨论】:

    标签: authentication oauth oauth-2.0 lumen


    【解决方案1】:

    这可能不是最干净的解决方案,可能与您的要求不完全匹配,但它确实检索了用户。

    我决定在代理中进行另一个数据库查询,以获取具有客户端请求的相同密钥(在我的情况下为电子邮件地址)的用户。

    在我的例子中,我将用户 ID 与标准 oauth 令牌一起发送。

    您可以使用相同的技术在会话中设置一些值。

    // ../app/Auth/Proxy.php
    namespace App\Auth;
    
    use App\User;   //     -----    added this line 
    use GuzzleHttp\Client;
    
    class Proxy {
    
    ...
    
       private function proxy($grantType, array $data = [])
       {
          ...
    
          $response = json_decode($guzzleResponse->getBody());
    
          if (property_exists($response, "access_token")) {
             ...
            // added the following line to get the user
            $user = User::where('email',$data['username'])->get()->first();
            // untested, but you could add the user to your session here
            $request = app()->make('request');
            $request->session()->put('current_user', $user);
    
            $response = [
                    'accessToken'            => $response->access_token,
                    'accessTokenExpiration'  => $response->expires_in,
                    'userId'                 => $user->id,
            ];
        }
     ...
    

    【讨论】:

      猜你喜欢
      • 2019-12-21
      • 2016-01-15
      • 1970-01-01
      • 2018-05-04
      • 2018-03-03
      • 2017-06-05
      • 2017-09-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多