简体   繁体   English

Laravel自己的API使用带有令牌的控制器的消耗

[英]laravel own api consumption from controller with bearer token

I like to do crud operation through api in Laravel. 我喜欢通过Laravel中的api进行粗操作。 so both mobile application / web application can hit same api end for crud operation.For api security purpose i am using passport. 因此,两个移动应用程序/ Web应用程序都可以在同一个api端进行原始操作。出于api安全目的,我使用护照。 I am successful while calling api end using postman, whereas i am getting null output while I am trying to call api end from laravel controller. 我在使用邮递员调用api end时很成功,而在尝试从laravel控制器调用api end时却得到了空输出。 I am trying to use bearer token. 我正在尝试使用不记名令牌。

In front I have laravel blade views.I have installed passport within laravel. 前面有laravel刀片视图,我在laravel中安装了通行证。 I have created few api endpoint inside api.php one of them are /user/{id} which has auth:api middleware enabled. 我在api.php内创建了一些api端点,其中之一是/user/{id} ,其中启用了auth:api中间件。

I have web.php having 我有web.php

 Route::get('profile', 'UserController@profile')->middleware('auth');

so my idea is from profile controller a request send to /api/user/1 with bearer token 所以我的想法是从配置文件控制器发送带有承载令牌的请求到/ api / user / 1

For getting bearer token I use Request create /oauth/token from login controller 为了获取承载令牌,我使用登录控制器中的Request create /oauth/token

if (Auth::attempt(['email' => request('email'), 'password' => 
request('password')])) {
        $user = Auth::user();
    if(Auth::check()) {  
           $req = Request::create('/oauth/token', 'POST',[
                     'grant_type' => 'password',
                     'client_id' => 2,
                     'client_secret' => 'WDv6wrY9Tf9HuixaiQjDWGy7yBqEG1IrmsLucAUI',
                    'username' => request('email'),
                    'password' => request('password'),
                    'scope' => '*' 
           ]);
                    $res = app()->handle($req);
                   $responseBody = json_decode($res->getContent()); // convert to json object
                  return response()->json(['success' => $responseBody], $res->getStatusCode());

           } else {
            return response()->json(['error' => 'Not logged in '], 401);
          }

    }

It return me bearer token. 它返回我不记名令牌。 I am passing this bearer token and trying to consume own api from laravel profile controller 我正在传递此承载令牌并尝试从laravel配置文件控制器使用自己的api

$token  ='eyJ0eXAiOiJKV1QiLCJhbGciOi...';
$req = Request::create('/api/user/1', 'GET',[
      'headers' => [
    'Accept' => 'application/json',
    'Authorization' => 'Bearer '.$token,

      ],

    ]);
    $res = app()->handle($req);
   $profile_details = json_decode($res->getContent()); // convert to json object


    return response()->json(['profile' =>$profile_details], $res->getStatusCode());

Output is 输出是

 {"profile":null} 

and status code is 302 status code302

While i call through post man http://localhost:8000/api/user/1 当我通过post man http://localhost:8000/api/user/1打电话时

Put Authorization Bearer Token value same as before 将授权承载令牌值设置为与以前相同

eyJ0eXAiOiJKV1QiLCJhbGciOi.....

I got following response 我得到以下回应

{
"data": {
    "id": 1,
    "first_name": "rajib",
    "last_name": "chow",
    "address": "207 Eryn Coves",
    "city": "South Treva",
    "country": "Luxembourg",
    "phone": "(397) 400-2302 x6997",
    "fax": "82928",
    "user_id": 1,
    "created_at": "2019-06-26 15:03:31",
    "updated_at": "2019-06-26 15:03:31"
    }
}

My api route is 我的api路线是

Route::get('/user/{id}', function ($id) {
return new UserResource(User::find($id)->customer);
})->middleware('auth:api');

if I remove middleware('auth:api') from the code again it works from my controller 如果我再次从代码中删除中间件('auth:api'),它将在我的控制器上正常工作

Route::get('/user/{id}', function ($id) {
return new UserResource(User::find($id)->customer);
}); 

Above give me expected output 以上给我预期的输出

But for security purpose, i think i should pass bearer token along with the api call. 但是出于安全目的,我认为我应该将承载令牌与api调用一起传递。 How can I give an api call from controller along with bearer token 如何从控制器发出API调用以及承载令牌

Try with this code 尝试使用此代码

$request = Request::create('/api/user/1', 'GET');
    $request->headers->set('Accept', 'application/json');
    $request->headers->set('Authorization', 'Bearer '.$token);
    $res = app()->handle($request);
    $profile_details = json_decode($res->getContent()); // convert to json object


    return response()->json(['profile' =>$profile_details], $res->getStatusCode());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM