如何在流明控制器中访问oauth2认证用户?

时间:2015-12-08 23:56:11

标签: authentication oauth oauth-2.0 lumen

我已经按照这个优秀的教程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 ...")
    }
}

1 个答案:

答案 0 :(得分:0)

这可能不是最干净的解决方案,可能不完全符合您的要求,但确实会检索用户。

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

在我的情况下,我发送了用户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,
        ];
    }
 ...