简体   繁体   中英

laravel own api consumption from controller with bearer token

I like to do crud operation through api in Laravel. so both mobile application / web application can hit same api end for crud operation.For api security purpose i am using passport. 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. I am trying to use bearer token.

In front I have laravel blade views.I have installed passport within laravel. I have created few api endpoint inside api.php one of them are /user/{id} which has auth:api middleware enabled.

I have web.php having

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

so my idea is from profile controller a request send to /api/user/1 with bearer token

For getting bearer token I use Request create /oauth/token from login controller

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

$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

While i call through 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

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

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. How can I give an api call from controller along with bearer token

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());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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