I am learning Laravel Passport and developing an OAuth2 server. After creating a client I made the following call to get the authorization code
Route::get('/', function (Request $request) {
$request->session()->put('state', $state = Str::random(40));
$query = http_build_query([
'client_id' => <Client_Id>,
'redirect_uri' => 'http://<Consumer_App_URL>/callback',
'response_type' => 'code',
'scope' => '',
'state' => $state,
]);
return redirect('http://<OAuth2_Server_URL>/oauth/authorize?'.$query);
});
The call works as expected and I got the authorization code, however when redirecting to the callback route which is defined like so
Route::get('/callback', function (Request $request) {
$state = $request->session()->pull('state');
throw_unless(
strlen($state) > 0 && $state === $request->state,
InvalidArgumentException::class
);
$response = Http::asForm()->post('http://<OAuth2_Server_URL>/oauth/token', [
'grant_type' => 'authorization_code',
'client_id' => <Client_Id>,
'client_secret' => '<Cient_Secret>',
'redirect_uri' => 'http://consumer/callback',
'code' => $request->code,
]);
return $response->json();
});
It didn't work, the response instance is just null. I can't figure out what might be the issue.
So I finally solved the problem, I just have to run php artisan config:cache . [reference]
Related
My gitLab controller. Links taken from the documentation. After submitting the form
returns an error "{"message":"401 Unauthorized"}" . Token is coming, but i want to
get username and email.
My gitLab controller
public function callback(Request $request)
{
$response = Http::withHeaders(['Accept' => 'application/json'])
->asForm()
->post('https://gitlab.com/oauth/token',[
'client_id' => config('oauth.gitlab.client_id'),
'client_secret' => config('oauth.gitlab.client_secret'),
'code' => $request->get('code'),
'grant_type' => 'authorization_code',
'redirect_uri' => config('oauth.gitlab.callback_uri'),
]);
$token = $response['access_token'];
$response = Http::withHeaders(['Authorization' => 'token ' . $token])
->get('https://gitlab.com/api/v4/user');
also link https://gitlab.com/api/v4/projects is work success
dd($response->body());
}
after checking I get an error 401. I don't understand why.
** My class GitlabServices**
public static function link(): string {
$params = [
'response_type' => 'code',
'client_id' => config('oauth.gitlab.client_id'),
'redirect_uri' => config('oauth.gitlab.callback_uri'),
'scope' => 'read_user openid'
];
return 'https://gitlab.com/oauth/authorize?' . http_build_query($params);
}
client_id, secret, redirect_uri store in .env
If you getting 401 in response. Check if the token privileges to request data.
Probably:
Token is not attached with request.
Token don't have privileges.
Adding 'token_type' to the request headers helped me
$token = $response->json('access_token');
$tokenType = $response->json('token_type');
$response = Http::withHeaders(['Authorization' => $tokenType . ' ' . $token])
->get('https://gitlab.com/api/v4/user');
The connection was successful and I received all the necessary information after making above mentioned changes.
I am developing an application like Postman Client in Laravel. For that, I am using Guzzle Client.
For OAuth 2.0 authentication, I have used the below link as reference,
Reference Link
I have tried the below code,
$token_storage = new FileTokenPersistence('/tmp/token.txt');
$baseurl="https://api.tradegecko.com/oauth/token";
$auth_code="";
$client_id="MYCLIENTID";
$client_secret="MYSECRET";
$redirect_uri="http://localhost:81/postman/public/request/instantadd";
if ($token_storage->hasToken() === false) {
$auth_url = 'https://api.tradegecko.com/oauth/authorize?'.http_build_query([
'client_id' => $client_id,
'redirect_uri' => $redirect_uri,
'response_type' => 'code',
'prompt' => 'select_account',
'scope' => '',
'access_type' => 'offline',
]);
echo "Go to the following link in your browser:\n\n";
echo " $auth_url\n\n";
// if(! defined('STDIN')) define('STDIN', fopen("php://stdin","r"));
echo "Enter verification code: ";
$auth_code = trim(fgets(STDIN, 1024));
}
$reauth_client = new \GuzzleHttp\Client(['verify' => 'E:\cacert.pem',
'base_uri' => $baseurl,
]);
$reauth_config = [
'code' => $auth_code,
'client_id' => $client_id,
'client_secret' => $client_secret,
'redirect_uri' => $redirect_uri,
];
$grant_type = new AuthorizationCode($reauth_client, $reauth_config);
$refresh_grant_type = new RefreshToken($reauth_client, $reauth_config);
$oauth = new OAuth2Middleware($grant_type, $refresh_grant_type);
$oauth->setTokenPersistence($token_storage);
$stack = HandlerStack::create();
$stack->push($oauth);
$client = new \GuzzleHttp\Client(['verify' => 'E:\cacert.pem',
'handler' => $stack,
'auth' => 'oauth',
]);
$response = $client->get($requesturl, $options);
$result=json_decode($response->getBody(),true);
I am getting an error in auth code retrieving. When I go to the authurl link, I am getting the token.
The error I am getting is:
"message": "Unable to request a new access token"
Also, I don't know what is the use of STDIN.....How can I put the auth code here?
Please help me.
Regards,Rekha
Laravel Passport Auth Stuck when run on self server and client in same project for password based token authentication
LoginController
public function authenticaterrr(Request $request)
{
$http = new Client();
try{
//dd("Hello");
$response = $http->post(url('oauth/token'), [
'form_params' => [
'grant_type' => 'password',
'client_id' => '2',
'client_secret' => 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
// 'username' => $request->get('username'),
// 'password' => $request->get('password'),
'username' => 'xxxxxx#xxxxx.com',
'password' => 'xxxxx',
'scope' => '*',
],
]);
// $apiResponse = json_decode((string) $response->getBody(), true);
// dd($apiResponse);
$apiResponse = json_decode((string) $response->getBody(), true);
dd($apiResponse);
session(['api'=> $apiResponse]);
session(['api-token'=> $apiResponse['access_token']]);
return json_decode($response->getBody(), true);
}catch (ClientException $exception){
dd("Hello");
return json_decode($exception->getResponse()->getBody(), true);
}
}
IN Web.php
Route::get('/auth/api/validate', 'Auth\LoginController#authenticaterrr');
In PostMan It didn't Get and Stuck Here is Output
If i will create new Project and Use that than it will work for me so what would be solution to run in same project
If you're running your web app on the built-in PHP server / php artisan serve, then the second auth/token Passport request "kills" the first authenticaterrr HTTP request.
This is because the built-in PHP server is single threaded.
Kudos/credits to this comment.
https://stackoverflow.com/a/51010186/8735680
function tokenRequest(Request $request){
$request->request->add([
"grant_type" => "password",
"username" => $request->username,
"password" => $request->password,
"client_id" => "x",
"client_secret" => "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
]);
$tokenRequest = $request->create(
env('APP_URL').'/oauth/token',
'post'
);
$instance = Route::dispatch($tokenRequest);
return json_decode($instance->getContent());
}
The following code works perfectly fine when you are calling your own routes/code inside project. Try this because it don't require Guzzle or curl or any other additional package.
/**
* Checking for server side OAuth authentication
* Place this code in controller where you are performing authorization
* #return Object
*/
public function checkOAuth(Request $req){
try{
$req->request->add([
"grant_type" => "password",
"client_id" => config('services.passport.client_id'), //Get from oauth_clients table
"client_secret" => config('services.passport.client_secret'), //Get from oauth_clients table
"username" => $req->username,
"password" => $req->password,
]);
$tokenRequest = $req->create(
config('services.passport.login_endpoint'), //'YOUR_APP_URL/oauth/token'
'post'
);
$instance = \Route::dispatch($tokenRequest);
return json_decode($instance->getContent());
}
catch(Exception $e){
dd($e->getMessage());
}
}
this will return the ttl, refresh_token and access_token. Use as per your requirements.
Trying to get socialite to work on my app. Facebook returns the The parameter app_id is required error.
Routes:
Route::get('/login/facebook', '\CommendMe\Http\Controllers\AuthController#redirectToProvider');
Route::get('/login/facebook/callback', '\CommendMe\Http\Controllers\AuthController#handleProviderCallback');
services.php:
'facebook' => [
'client_id' => env('426129694395672'),
'client_secret' => env('840fca14fc9fac4b592cd49f285c2ee9'),
'redirect' => 'http://localhost/login/facebook/callback',
],
AuthController.php
public function redirectToProvider() {
return Socialite::driver('facebook')->redirect();
}
public function handleProviderCallback() {
$user = Socialite::driver('facebook')->user();
$user->name;
}
When trying the /login/facebook route, facebook returns this error.
Why is this happening?
Either use as
'client_id' => '426129694395672',
Or
'client_id' => env("FB_APP",'426129694395672'),
and use FB_APP = '426129694395672' in .env file
Instead
'client_id' => env('426129694395672'),
Using env('VarName') is to get value of environment variable named as VarName in .env file
Assuming that you have the following in your .env file:
CLIENT_ID=426129694395672
CLIENT_SECRET=840fca14fc9fac4b592cd49f285c2ee9
The facebook[] in your services.php should be like this:
'facebook' => [
'client_id' => env('CLIENT_ID'),
'client_secret' => env('CLIENT_SECRET'),
'redirect' => 'http://localhost/login/facebook/callback',
],
I'm trying to call a Laravel API using a Laravel Client.
Here is the code:
Route::get('/callback', function (Request $request) {
$http = new GuzzleHttp\Client;
$response = $http->post('http://galaxy.dev/oauth/token', [
'form_params' => [
'grant_type' => 'authorization_code',
'client_id' => '3',
'client_secret' => 'rrhaEv0B6NAFLyMFqvZrY87gkquFF2UwhAHPtd8L',
'redirect_uri' => 'http://galaxy-game.dev/callback',
'code' => $request->code,
],
]);
return json_decode((string) $response->getBody(), true);
});
I get this response from the API:
Client error: POST http://galaxy.dev/oauth/token resulted in a 400
Bad Request response: {"error":"invalid_request","message":"The
request is missing a required parameter, includes an invalid parameter
value, (truncated...)
I have noticed in the API error log this:
Client->request('post', 'http://galaxy.dev/oauth/token',
array('form_params' => array('grant_type' => 'authorization_code',
'client_id' => '3', 'client_secret' =>
'rrhaEv0B6NAFLyMFqvZrY87gkquFF2UwhAHPtd8L', 'redirect_uri' =>
'http://galaxy-game.dev/callback', 'code' => null), 'synchronous' =>
true)) in Client.php line 87
It says that
$request->code = null
Does anyone have any ideas why this might be? This seems to be the reason why it is failing. I have followed the Laravel docs exactly. Any help would be greatly appreciated!
Hi I fixed this by leaving the code value empty like this:
'code' => '',
Since $request->code is null, that probably causes that problem.