Symfony RedirectResponse Getting /code/ parameter - php

My question is: how to get 'code' parameter from the response giving by my little piece of code:
$clientID = "clientID...";
$clientSecret = "clientSecret...";
$url = 'https://myweb.com/oauth/authorize/?'.http_build_query(array(
'response_type' => 'code',
'client_id' => $clientID,
'redirect_uri' => 'http://www.mywebhttp.dyndns.org/',
'scope' => array('user')
));
$status = 302;
$response = new RedirectResponse($url,$status,$headers = array());
So what i see going on is that when i'm being given the response, the code parameter exists only in an url in my web explorer, so i can copy it and use. But how to get it directly from php code?
Thank you in advance!

Related

PHP HTTP Request Ignoring Parameter

Before I begin with my question, I will mention that I am re-learning PHP after a long time away from the language. Please be gentle. Also, I know that I could use a library like curl to do some of these things, but I would like to understand how PHP works natively.
I am trying to submit an http GET request to a Microsoft API (Identity Platform). The following is my code:
<?php
$data = array (
'client_id' => '6731de76-14a6-49ae-97bc-6eba6914391e',
'state' => '12345',
'redirect_uri' => urlencode('http://localhost/myapp/permissions')
);
$streamOptions = array('http' => array(
'method' => 'GET',
'content' => $data
));
$streamContext = stream_context_create($streamOptions);
$streamURL = 'https://login.microsoftonline.com/common/adminconsent';
$streamResult = file_get_contents($streamURL, false, $streamContext);
echo $streamResult;
?>
When I try and execute the above code, I get this:
Error snip
Conversely, with the following code, the http request works fine:
<?php
$streamURL = 'https://login.microsoftonline.com/common/adminconsent?client_id=6731de76-14a6-49ae-97bc-6eba6914391e&state=12345&redirect_uri=http://localhost/myapp/permissions';
$streamResult = file_get_contents($streamURL);
echo $streamResult;
?>
Can anyone provide insight as to why the first example fails while the second succeeds? My thought is that there must be some kind of syntactical error. Thanks in advance.
The content parameter is for the request body, for POST and PUT requests. But GET parameters don't go in the body, they go right on the URL. So your first example is simply making a GET request to the base URL with no parameters at all. Note also that the method parameter already defaults to GET, so you can just skip the whole streams bit.
You can build your URL like:
$urlBase = 'https://login.microsoftonline.com/common/adminconsent';
$data = [
'client_id' => '...',
'state' => '12345',
'redirect_uri' => 'http://localhost/myapp/permissions',
];
$url = $urlBase . '?' . http_build_query($data);
And then just:
$content = file_get_contents($url);
Or just cram it all into one statement:
$content = file_get_contents(
'https://login.microsoftonline.com/common/adminconsent?' .
http_build_query([
'client_id' => '...',
'state' => '12345',
'redirect_uri' => 'http://localhost/myapp/permissions',
])
);
Or use $url to feed curl_init() or Guzzle or similar.

GitLab oauth2 Laravel "{"message":"401 Unauthorized"}"

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.

Laravel OAuth 2.0 Authentication using Guzzle Client

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

Setting post data with a Laravel request object

I'm trying to test a Laravel API endpoint and want to call it in code.
$request = Request::create( $path, $method );
$response = Route::dispatch( $request );
This snippet works fine for GET but I need to be able to set up POST calls too. Setting the $method to POST works as well, but I can't find documentation detailing how to attach post data.
Any advice?
As you mentioned in the comments, you could use $this->call() but you can actually do it with your current code too. If you take a look at the signature of the Request::create() function you can see that it takes $parameters as third argument:
public static function create($uri, $method = 'GET', $parameters = array(), $cookies = array(), $files = array(), $server = array(), $content = null)
And the docblock says: The query (GET) or request (POST) parameters
So you can simply add the data to Request::create()
$data = array('foo' => 'bar');
$request = Request::create( $path, $method, $data );
$response = Route::dispatch( $request );
I've spent nearly a day trying to get this working myself for social authentication with passport and Angular front-end.
When I use the Restlet API Client to make the request I always get a successful response.
Restlet Client Request
Restlet client response
However using the following method of making internal requests always gave me an error.
$request = Request::create(
'/oauth/token',
'POST',
[
'grant_type' => 'social',
'client_id' => 'your_oauth_client_id',
'client_secret' => 'your_oauth_client_secret',
'provider' => 'social_auth_provider', // e.g facebook, google
'access_token' => 'access_token', // access token issued by specified provider
]
);
$response = Route::dispatch($request);
$content = json_decode($response->getContent(), true);
if (! $response->isSuccessful()) {
return response()->json($content, 401);
}
return response()->json([
'content' => $content,
'access_token' => $content['access_token'],
'refresh_token' => $content['refresh_token'],
'token_type' => $content['token_type'],
'expires_at' => Carbon::parse(
$content['expires_in']
)->toDateTimeString()
]);
This specific error:
{
error: "unsupported_grant_type",
error_description: "The authorization grant type is not supported by the
authorization server.",
hint: "Check that all required parameters have been provided",
message: "The authorization grant type is not supported by the authorization server."
}
I had the feeling it has to do with the way the form data is sent in the request, so while searching for a proper way to make such internal requests in laravel I came across this sample project with a working implementation: passport-social-grant-example.
In summary here's how to do it:
$proxy = Request::create(
'/oauth/token',
'POST',
[
'grant_type' => 'social',
'client_id' => 'your_oauth_client_id',
'client_secret' => 'your_oauth_client_secret',
'provider' => 'social_auth_provider', // e.g facebook, google
'access_token' => 'access_token', // access token issued by specified provider
]
);
return app()->handle($proxy);
Hope this helps.

I need some solution with Google API Oauth

I'm trying to pull my list of Google contacts and display on a page the name and phone number.
I found an interesting post made by Lorna Jane and tried her code. I get a token returned, but every time I revisit the page, it asks me to authenticate again. With current code, no data array is pulled:
$id = 'secret.apps.googleusercontent.com';
$scope = 'https://www.google.com/m8/feeds/default/full/';
$uri = 'http://example.com/callback.php';
$params = array(
'response_type' => 'code',
'client_id' => $id,
'redirect_uri' => $uri,
'scope' => $scope
);
$query = 'https://accounts.google.com/o/oauth2/auth?' . http_build_query($params);
header('Location: ' . filter_var($query, FILTER_SANITIZE_URL));
if (isset($_GET['code']))
{
$code = $_GET['code'];
$token = 'https://accounts.google.com/o/oauth2/token';
$params = array(
'code' => $code,
'client_id' => $id,
'client_secret' => 'clientsecret',
'redirect_uri' => $uri,
'grant_type' => 'authorization_code'
);
$request = new HttpRequest($token, HttpRequest::METH_POST);
$request->setPostFields($params);
$request->send();
$responseObj = json_decode($request->getResponseBody());
var_dump($responseObj);
}
Please let me know what I'm missing. I prefer the pecl_http implementation, over the Google API library.

Categories