Laravel 5.4 Passport - 从访问令牌获取用户信息后如何重定向到客户端仪表板

时间:2017-09-29 10:15:58

标签: php laravel laravel-5.4 laravel-passport

在Laravel Passport中,从服务器获取访问令牌后,能够从客户端访问用户信息。现在我不知道如何将其重定向到客户端仪表板?

这是我的回调函数:

Route::get('/callback', function (Illuminate\Http\Request $request) {
    $http = new GuzzleHttp\Client;

    $response = $http->post('http://localhost.server:8080/oauth/token', [
        'form_params' => [
            /* Auth code grant*/
            'client_id' => '<client_id>',
            'client_secret' => '<client_secret>',
            'grant_type' => 'authorization_code',
            'redirect_uri' => 'http://localhost.client:8000/callback',
            'code' => $request->code,
        ],
    ]);

        $auth_grant = json_decode((string) $response->getBody(), true);
        $token_type = $auth_grant['token_type'];
        $access_token = $auth_grant['access_token'];

        $user_auth = $http->request('GET', 'http://localhost:8080/api/user', [
            'headers' => [
                'Accept' => 'application/json',
                'Content-Type' => 'application/json',
                'Authorization' => $token_type.' '.$access_token,
            ],
        ]);
        $usrAuth = json_decode((string) $user_auth->getBody(), true);
});

注意: 在重定向到仪表板之前,想要将用户信息存储在Auth中,然后想要通过VarifyUser中间件验证每个其他路由。通过Auth::check验证用户。

Route::group(['middleware' => ['verify_user', 'language']], function(){
// If you want to check loggining user, have to use 'verify_user' middleware
   route::group(['namespace' => 'Index'], function(){
     Route::get('/index', 'IndexController@index');
   });

   route::group(['namespace' => 'Group'], function(){
     // Group page
     Route::get('/group-registration', 'GroupController@index');

     // Register group
     Route::post('/registerGroup', 'GroupController@registerGroup');
  });
}

VerifyUser中间件:

<?php

namespace App\Http\Middleware;

// Requirement
use Illuminate\Support\Facades\Auth;
use Closure;

class VerifyUser
{
  /**
   * Handle an incoming request.
   *
   * @param  \Illuminate\Http\Request  $request
   * @param  \Closure  $next
   * @return mixed
   */
  public function handle($request, Closure $next)
  {
      if(!Auth::check()){
        return redirect('/login');
      }

      return $next($request);
  }
}

1 个答案:

答案 0 :(得分:0)

在方法结束时添加响应重定向

Route::get('/callback', function (Illuminate\Http\Request $request) {
    // callback handle
    ....

    // here, add this to redirect after callback success
    return redirect('dashboard');
});