I have recently developed a password grant API to be used by my client application. It is successfully generating access tokens for users after the client has been authorized.
The problem I'm facing now is how to pass the access token back from client application to Laravel with each request? (as done by Headers in passport) I have gone through the laravel API Authentication by passport documentation.
What I'm trying to do
I have already tested the work flow of the API on postman. It was working fine. But now I'm trying to hard code everything. SO now I'm trying to fetch posts for the users who are having the access tokens.
api.php (Routes file)
Route::post('login', 'API\UserController@userSignIn')->name('login');
Route::middleware('auth:api')->get('/posts', function() {
$accessToken = Cookie::get('accessToken');
$client = new \GuzzleHttp\Client;
$response = $client->request('GET', 'http://tcc.devp/api/posts', [
'headers' => [
'Accept' => 'application/json',
'Authorization' => 'Bearer '.$accessToken,
],
]);
return $accessToken;
})->name('posts');
API/UserController.php
public function userSignIn(Request $request){
if(Auth::attempt(['email' => $request['email'], 'password' => $request['password']])){
$http = new \GuzzleHttp\Client;
$response = $http->post('http://tcc.devp/oauth/token', [
'form_params' => [
'grant_type' => 'password',
'client_id' => 'client_id',
'client_secret' => 'client_secret',
'username' => $request['email'],
'password' => $request['password'],
'scope' => '*'
],
]);
$response_array = json_decode((string) $response->getBody()->getContents(), true);
$accessToken = $response_array['access_token'];
$refreshToken = $response_array['refresh_token'];
Cookie::queue('accessToken', $accessToken, 60);
Cookie::queue('refreshToken', $refreshToken, 60);
// return redirect()->route('posts');
}
else{
return response()->json(['error'=>'Unauthorised'], 401);
}
}
While doing so, I'm getting this error MethodNotAllowedHttpException. I got to know that it is because I'm redirecting my post request to some other page in the controller. network tab is showing 302 status.
I have two questions to ask you-
- How can I get rid of MethodNotAllowedHttpException error?
- Is my way of passing the access token to the request correct? If not how can I do that? I have found no resources on the internet to guide me in this direction