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

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.

Related

How can I generate access token and refresh token in laravel 9 using passport?

Simply I am able to generate access token .
How can I generate refresh token ?
$token = $user->createToken('MyApp')->accessToken;
In $token I got accessToken. Also I need refresh Token .
public function refreshToken($password, $email)
{
$response = Http::asForm()->post('http://localhost:8000/oauth/token', [
'grant_type' => 'password',
'client_id' => 'my_client_id',
'client_secret' => 'my_client_secret',
'username' => $email,
'password' => $password,
'scope' => '',
]);
return $response->json();
}
When using this code it will work only when application run on ports 8000 and 8001.
When I call this in postman I got the following error,
Illuminate\Http\Client\ConnectionException: cURL error 28: Operation timed out after 30001 milliseconds with 0 bytes received

Send a message to a Channel in Teams via Graph

I try to send a message to a specific channel in teams.
It works perfectly with 'https://developer.microsoft.com/de-de/graph/graph-explorer'.
For reciving the access token i do the following. This part works, because i can retrieve user information and other things with it.
$guzzle = new \GuzzleHttp\Client(['verify' => false]);
$tenantId = '<tenant_id>';
$clientId = '<client_id>';
$clientSecret = '<client_secret>';
$url = 'https://login.microsoftonline.com/' . $tenantId . '/oauth2/token?api-version=1.0';
$token = json_decode($guzzle->post($url, [
'form_params' => [
'client_id' => $clientId,
'client_secret' => $clientSecret,
'resource' => 'https://graph.microsoft.com/',
'grant_type' => 'client_credentials',
],
'verify' => false
])->getBody()->getContents());
$accessToken = $token->access_token;
This part now is the one that produces the error
$graph = new Graph();
$graph->setAccessToken($accessToken);
$url = '/teams/<team_id>/channels/<channel_id>/messages';
$queryParams = [
'body' => [
'content' => 'foo'
]
];
$info = $graph->setApiVersion("beta")->createRequest("POST", $url)
->addHeaders(array("Content-Type" => "application/json"))
->attachBody($queryParams)
->setReturnType(BetaModel\User::class)
->execute();
echo '<pre>';
print_r($info);
This produces the following error
{
"error": {
"code": "UnknownError",
"message": "",
"innerError": {
"date": "2020-11-11T10:14:03",
"request-id": "<request_id>",
"client-request-id": "<client_request_id>"
}
}
}
The teams id and the channel id are correct, i can retrieve them by using
/users/<user_id>/joinedTeams
and
/teams/<teams_id>/channels
and as mentioned earlier, it works in the graph explorer page.
I know that i somehow need to send the message in an user context, but i can't make it work, and i can't find useful informations, so i am pleased for any. Thanks in advance!
This api call currently does not support application permissions, so you cannot use the client credential flow to obtain a token. You need to grant delegated permissions to the application, and then use the auth code flow to obtain the token. see:here.

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