I want to integrate facebook with my app. I'm using laravel/socialite package to get access to facebook page. At all it works but I'm doing it with logged in user and I want to add info from his facebook profile to exsisting account. I'm using Oauth 2 to login to laravel app via user credentials because it's Angular/Laravel app. I need to retrive logged in user to add info to his account but i can't get logged user id. I need to pass extra parameter to get method in facebook callback route. And my question is is there any way to add extra parameters to facebook callback url? Here is what I have:
Route::group(['middleware' => ['web']], function () {
Route::get('/facebook/login', function(){
Config::set('services.facebook.redirect', 'http://taggers.dev/facebook/callback?access_token='.Session::get('access_token'));
return Socialite::driver('facebook')->with(['asdadad' => 'asd'])->redirect();
});
Route::get('facebook/callback', ['middleware' => ['oauth', 'oauth-user'], function(Authorizer $authorizer){
$user = Socialite::driver('facebook')->user();
$uid = $user->getId();
if ($uid == 0) return Redirect::to('/')->with('message', 'There was an error');
$profile = Profile::whereUid($uid)->first();
if (empty($profile)) {
// $user_id= Authorizer::getResourceOwnerId(); // the token user_id
$auth_user = User::where('idUser', $user_id)->first();
$profile = new Profile();
$profile->uid = $uid;
$profile->username = $user->getName();
$profile = $auth_user->profiles()->save($profile);
}
dd($auth_user);
}]);
});
And here is my error:
Client error: `GET https://graph.facebook.com/oauth/access_token?client_id=1001186793295886&client_secret=b792ea0354c3846225bc70ac7185e54f&code=AQA1xjbQ25a9qE0loN-yjhmOBYBZLtNVcnCLIeCwJV1enion4ysKkpuBqBmZLhpT2I4VkemXr6R9IwcgSVVzqOLMmzvz_SHga9KrK3ny5cLGi0VGmEibNqGSHA9B9jJ9aFt6vA8lQ1r0IqdN94S-KFjpBimzVmT1OoeI-pCayVRG_v_6uYzeQfZAtDXh3BDVTutLaDXUdJEY3sQhop7Qr8n6jARGBYRZgDcXS6Ci69vY3aRoCLsrFdAQlD7Kid0W9QqeSBxbWrc76Ldp06PtdVLMRdQ54qQepwG4mOhOiy40-azn3YIBriSx7o0PcNBBE_f_8vmnbiESlo7R-8Su_7vs&redirect_uri=http%3A%2F%2Ftaggers.dev%2Ffacebook%2Fcallback` resulted in a `400 Bad Request` response:
{"error":{"message":"Error validating verification code. Please make sure your redirect_uri is identical to the one you (truncated...)
Related
I am using Laravel Passport to Auth user in my Laravel API. I would like to know if it is possible to add custom data to the token generated by Passport:
// /login endpoint
Auth::attempt($credentials);
$user = $request->user();
$token = $user->createToken('ACCESS_TOKEN')->accessToken;
return response()->json(['token' => $token]);
// /me endpoint
$user = $request()->user();
return response()->json(['user_data' => $user]);
This is how I'm actually using it, however, I'm just able to retrieve User Model information. I would like to add custom information to the JWT token and be able to retrieve that information in all endpoints, like /me, something like that:
// /login
... login logic
$token->customKey = 'custom value';
$token->foo = 'bar';
// /me
$user = $request->user();
$token = $user->token(); // returns the token
$customKey = $token->customKey; // this don't work
$foo = $token->foo; // this don't work
Is there any way to achieve this?
I'm using Laravel 8.0 and Laravel Passport 10.0.
I am trying to add social authentication to a laravel 5.8 API application using socialite. Following the documentation here https://laravel.com/docs/5.8/socialite#routing I created a SocialAuthController that wiill redirect the user to the provider auth page and handle the callback like this
...
use Socialite;
...
public function redirectToProvider($provider)
{
return Socialite::driver($provider)->redirect();
}
public function handleProviderCallback($provider)
{
// retrieve social user info
$socialUser = Socialite::driver($provider)->stateless()->user();
// check if social user provider record is stored
$userSocialAccount = SocialAccount::where('provider_id', $socialUser->id)->where('provider_name', $provider)->first();
if ($userSocialAccount) {
// retrieve the user from users store
$user = User::find($userSocialAccount->user_id);
// assign access token to user
$token = $user->createToken('string')->accessToken;
// return access token & user data
return response()->json([
'token' => $token,
'user' => (new UserResource($user))
]);
} else {
// store the new user record
$user = User::create([...]);
// store user social provider info
if ($user) {
SocialAccount::create([...]);
}
// assign passport token to user
$token = $user->createToken('string')->accessToken;
$newUser = new UserResource($user);
$responseMessage = 'Successfully Registered.';
$responseStatus = 201;
// return response
return response()->json([
'responseMessage' => $responseMessage,
'responseStatus' => $responseStatus,
'token' => $token,
'user' => $newUser
]);
}
}
Added the routes to web.php
Route::get('/auth/{provider}', 'SocialAuthController#redirectToProvider');
Route::get('/auth/{provider}/callback', 'SocialAuthController#handleProviderCallback');
Then I set the GOOGLE_CALLBACK_URL=http://localhost:8000/api/v1/user in my env file.
When a user is successfully authenticated using email/password, they will be redirected to a dashboard that will consume the endpoint http://localhost:8000/api/v1/user. So in the google app, I set the URI that users will be redirected to after they are successfully authenticated to the same endpoint http://localhost:8000/api/v1/user
Now when a user tries to login with google, the app throws a 401 unauthenticated error.
// 20190803205528
// http://localhost:8000/api/v1/user?state=lCZ52RKuBQJX8EGhz1kiMWTUzB5yx4IZY2dYmHyJ&code=4/lgFLWpfJsUC51a9yQRh6mKjQhcM7eMoYbINluA58mYjs5NUm-yLLQARTDtfBn4fXgQx9MvOIlclrCeARG0NC7L8&scope=email+profile+openid+https://www.googleapis.com/auth/userinfo.profile+https://www.googleapis.com/auth/userinfo.email&authuser=0&session_state=359516252b9d6dadaae740d0d704580aa1940f1d..10ea&prompt=none
{
"responseMessage": "Unauthenticated",
"responseStatus": 401
}
If I change the URI where google authenticated users should be redirect to like this GOOGLE_CALLBACK_URL=http://localhost:8000/auth/google/callback the social user information is returned.
So how should I be doing it. I have been on this for a couple of days now.
That is because you haven't put authorization in your header with your request.
you don't need to redirect user if you are working with token, your app should be a spa project, so you will redirect him from your side using js frameworks.
You need to send Authorization in your headers plus you need to specify it with your token which you returned it in your response like this:
jQuery.ajaxSetup({
headers: {
'Authorization': 'Bearer '+token
}
});
or if you are using axios
axios.defaults.headers.common['Authorization'] = 'Bearer ' + token;
I am using Cosenary Instagram-PHP-API (https://github.com/cosenary/Instagram-PHP-API) and have been able to successfully retrieve user media from user accounts. However, when I redirect clients to another php page (e.g. 'action.php'), I loose all the authentication and get the '400' error message saying that: The access_token provided is invalid.' I have tried passing authCode and access_token to the second page and used them for authentication but still couldn't retrieve data. How should I store and pass authentication to the second page? I am trying to delete comments and unfollow people on the second pages.
Here is the code I am using (from examples folder):
$instagram = new Instagram(array(
'apiKey' => '####',
'apiSecret' => '#####',
'apiCallback' => '...../success.php'
));
// receive OAuth code parameter
$code = $_GET['code'];
// check whether the user has granted access
if (isset($code)) {
// receive OAuth token object
$data = $instagram->getOAuthToken($code);
$username = $data->user->username;
// store user access token
$instagram->setAccessToken($data);
// now you have access to all authenticated user methods
$result = $instagram->getUserMedia();
} else {
// check whether an error occurred
if (isset($_GET['error'])) {
echo 'An error occurred: ' . $_GET['error_description'];
}
}
How can i get user name and surname from facebook authentication. I do login with facebook and i want to do signup. I need Name, Surname and birthday from user. I read about this but cant find concrete information.
my controller is here:
public function oAuthSuccess($client) {
// get user data from client
$userAttributes = $client->getUserAttributes();
$user = User::find()->where(['Email' => $userAttributes['email']])->one();
if (!$user) {
$model = new \frontend\modules\settings\models\ProfileForm();
$model->Name = $userAttributes['name'];
$model->Email = $userAttributes['email'];
if ($model->saveFacebookClient()) {
Yii::$app->user->login($model);
}
return $this->redirect('index.php?r=content/news');
}
Yii::$app->user->login($user);
}
This is the API call:
/me?fields=first_name,last_name,birthday
Of course you need to authorize the user with the user_birthday permission. Information about the login process in general can be found in the docs: https://developers.facebook.com/docs/facebook-login
I suggest using the JavaScript SDK for login, hereĀ“s one tutorial: http://www.devils-heaven.com/facebook-javascript-sdk-login/
If you really want to login with PHP, here are more links:
https://developers.facebook.com/docs/php/howto/example_facebook_login
http://www.devils-heaven.com/facebook-php-sdk-5-tutorial/
After reading: http://laravel.com/docs/5.0/authentication I was able to retrieve the user details from the OAuth provider (Facebook) using Socialite:
$user->getNickname();
$user->getName();
$user->getEmail();
$user->getAvatar();
But I couldn't find any further documentation on how to save the user in the database or log the user in.
I want to do the equivalent to:
Auth::attempt(['email' => $email, 'password' => $password])
But for the details retrieved via Socialite (I don't have a password)
Can you please show me an example on using "Auth" with user data retrieved via Socialite?
Add to "users" table new column: facebook_user_id. Every time when user tries to login through Facebook, Facebook will return the same user id.
public function handleProviderCallback($provider)
{
$socialize_user = Socialize::with($provider)->user();
$facebook_user_id = $socialize_user->getId(); // unique facebook user id
$user = User::where('facebook_user_id', $facebook_user_id)->first();
// register (if no user)
if (!$user) {
$user = new User;
$user->facebook_id = $facebook_user_id;
$user->save();
}
// login
Auth::loginUsingId($user->id);
return redirect('/');
}
How Laravel Socialite works?
public function redirectToProvider()
{
// 1. with this method you redirect user to facebook, twitter... to get permission to use user data
return Socialize::with('github')->redirect();
}
public function handleProviderCallback()
{
// 2. facebook, twitter... redirects user here, where you write code to log in user
$user = Socialize::with('github')->user();
}