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;
Related
I am pulling User Information from an external site with external API. I have completed the user login route on the Laravel and I get the data from the controller file. There is no problem in terms of pulling and displaying data from an external user API link.
How to do token and session operation like regular Laravel user to the user logged in with external API without the database. Note that I can use the same token part of the user API token available
In addition, I don't want to transfer the information by assigning session between the controller each time the user was login. How do I assign tokens in all transactions after user login?
It comes to these controls via post method from login screen
public function loginData(Request $request)
{
$password = $request->password;
$email = $request->email;
$apiman = "Bearer {$this->accesstokenApi()}";
$client = new Client();
$response = $client->post('https://testapi.com/api/v3/Profile', [
'headers' =>
[
'cache-control' => 'no-cache',
'authorization' => $apiman,
'content-type' => 'application/json'
],
'json' =>
[
'Email' => $email,
'Password' => $password
],
]);
$data = json_decode((string) $response->getBody(), true);
if ($data['ResponseType']=="Ok") {
session()->put('token', $data);
return redirect('/user-detail');
} else {
return response()->json([
'success' => false,
'message' => 'Invalid Email or Password',
], 401);
}
}
User logged in OK . After that, what token should the machine give, or where can the session be given to that user in one place? Besides, if the user is logged in, how do I get him to see the home page instead of showing the login form again, just like in Laravel login processes ?
Maybe you can create new middleware that will check if there is a token in the session
Here is the example that you can use and adapt it based on your needs.
namespace App\Http\Middleware;
use Closure;
class Myauth
{
public function handle($request, Closure $next, $guard = null)
{
if(session()->has('token')) {
return $next($request);
} else {
return response('Unauthorized.', 401);
//OR return redirect()->guest('/');
}
}
}
I am trying to add social authentication to a Laravel 5.8 API project using socialite.
When trying to handle a social provide callback, the ArgumentCountError is thrown here
Too few arguments to function App\Http\Controllers\SocialAuthController::handleProviderCallback(), 0 passed and exactly 1 expected
The error is referring to the very first line of this code block
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('Pramopro')->accessToken;
// return access token & user data
return response()->json([
'token' => $token,
'user' => (new UserResource($user))
]);
} else {
// store the new user record
$user = User::create([
'name' => $socialUser->name,
'username' => $socialUser->email,
'email_verified_at' => now()
]);
...
// assign passport token to user
$token = $user->createToken('******')->accessToken;
// return response
return response()->json(['token' => $token]);
}
}
Below is how I have set up other code. Frist in env I added
GOOGLE_CLIENT_ID=******
GOOGLE_CLIENT_SECRET=*******
GOOGLE_CALLBACK_URL=https://staging.appdomain.com/api/v1/user
Then modified web.php
Auth::routes(['verify' => true]);
Route::get('/auth/{provider}', 'SocialAuthController#redirectToProvider');
Route::get('/auth/{provider}/callback', 'SocialAuthController#handleProviderCallback');
Lastly in the google app, I added the uri path where users will be redirected to after successful authentication
https://staging.appdomain.com/api/v1/user
How do I fix this?
The callback uri that user should be redirected to after successful authentication was apparently not being cached. So running php artisan route:cache fixed it.
I have created an API Authentication system in Laravel using passport package. when a user log in every time create a personal access token and when logout token is revoked. I have tested it in Postman. but when I try to this from frontend I can't manage the personal access token for every request and response. now, I want to know How can i manage the Personal Access Token from frontend and add the token for every request an upcoming request.
Here is my code sample.
public $successStatus = 200;
public function login()
{
if(Auth::attempt(['email' => request('email'), 'password' => request('password')])){
$user = Auth::user();
$success['token'] = $user->createToken('Personal Access Token')->accessToken;
return response()->json(['success' => $success], $this->successStatus);
}
else{
return response()->json(['error'=>'Unauthorised'], 401);
}
}
You have to add below headers for every request
[
'Accept' => 'application/json',
'Authorization' => 'Bearer '.$accessToken,
]
For more information, refer here
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...)
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();
}