Reputation: 609
I'm working with Laravel Passport for the first time. I'm building an API that will be consumed by a mobile application.
For the authentication, this is what i'm doing:
public function login(Request $request)
{
$loginData = Validator::make($request->all(), [
'email' => 'required|email',
'password' => 'required',
]);
if( $loginData->fails() )
{
return response()->json(['error' => $loginData->errors()], 401);
}
if( Auth::attempt(['email' => request('email'), 'password' => request('password')]) )
{
$data = [
'grant_type' => 'password',
'client_id' => $this->client->id,
'client_secret' => $this->client->secret,
'username' => $request->email,
'password' => $request->password,
'scope' => '',
];
$request = Request::create('/oauth/token', 'POST', $data);
return app()->handle($request);
}
else
{
return response()->json(['error' => 'Invalid credentials'], 401);
}
}
Successful login returns the access token as such:
{
"token_type": "Bearer",
"expires_in": 31622400,
"access_token": "access_token",
"refresh_token": "refresh_token"
}
Now the aim is to use this access token by passing it to the header of all routes that need authentication.
For example in my routes/api.php
file, i have this route:
Route::post('/login', 'API\AuthController@login');
Route::apiResource('/tasks', 'API\TaskController')->middleware('auth:api');
In my TaskController
, all the methods in it need to be passed a header that contains the access token so as to authenticate the request. This is where my question is. I can't seem to find a resource so far that explains how to do this. So in every request i need to pass something like this to the header of the request:
Accept: application/json
Authorization: Bearer access_token
This is my TaskController
index
method. How do i pass the access token in here?
public function index()
{
//how do i capture the access token in here so that i can pass it to the request header?
return TaskResource::collection(auth()->user()->tasks()->latest()->paginate(4));
}
Is there a default Passport method that can be used to pass the access token to required requests or how can it be done?
Upvotes: 1
Views: 7454
Reputation: 83
using $request->bearerToken(); method you can get the request token.
use Illuminate\Http\Request;
public function index(Request $request)
{
echo $request->bearerToken();
}
Upvotes: 0
Reputation: 1354
use Illuminate\Http\Request;
public function index(Request $request)
{
$bearerToken = $request->header('Authorization'); // will return "Bearer access_token" string
}
Then you will need to get access_token
from "Bearer access_token"
string.
If you need access_token
to retrieve user, you can use $user = $request->user()
to get user.
Upvotes: 3