how to handle laravel socialite "Missing authorization Exception" - laravel

In Laravel Socialite We are redirected to facebook. But When User Cancels (not allowing facebook to access public profile) it is giving error Missing Authorization exception
ClientException in RequestException.php line 107: Client error: GET
https://graph.facebook.com/oauth/access_token?client_id=1309844325833234&client_secret=1304bbdd28400tret49a295d324d577c&redirect_uri=http%3A%2F%2Flocalhost%3A8000%2Fauth%2Ffacebook%2Fcallback`
resulted in a 400 Bad Request response: {"error":{"message":"Missing
authorization
code","type":"OAuthException","code":1,"fbtrace_id":"Aq9wMwG6ewl"}}
I dont want to display this Instead I Want to return to my site home page by giving a message "Facebook Login Failed" like what shown in stackoverflow facebook login.

Finally i got answer.Here it is
public function handleProviderCallback()
{
try {
$user = Socialite::driver('facebook')->user();
} catch (\Exception $e) {
//Here you can write excepion Handling Logic
}
}

Try catch didn't give good result to me. I used below methods to catch this error. If you're using Laravel Socialite library definitely it has function call handleProviderCallback. In that use this code
handleProviderCallback Method
/**
* Obtain the user information from GitHub.
*
* #return Response
*/
public function handleProviderCallback()
{
$error_code = Input::get('error_code');
if ($error_code == 200)
{
return redirect()->route('sign-in')->with('error','You\'ve chose not to grant us permission to connect with your Facebook account.');
}
else
{
$fbUser = Socialite::driver('facebook')->user();
# rest of your code
}
}
Where does this error_code come from ??
Well, If you look at the error page(Laravel Black screened) come to you check the URL of that page. It has the these get methods error , error_code , error_description , error_reason , state.
Ex : http://localhost:8000/login/facebook/callback?error=access_denied&error_code=200&error_description=Permissions+error&error_reason=user_denied&state=mIxNjoDCogT2piMV5LX1Imk6GWNzqPUt3JZaqsIo#_=_
What I can do this to optimize this
You can use a switch statement based on error Check this Facebook error codes, with an error message and pass it.

Related

Redirect Laravel Email verification with expired token - 403 | Invalid Signature

I noticed that when an email verification token expires in Laravel, it shows an error page which says
403 | Invalid Signature
I don't think its a good user experience for users, because the information is not clear to the user and they don't know what to do next.
Is it possible to redirect to /email/verify
or customize the error message?
If you still wanted to keep that behavior of what the trait is providing but you want to catch that exception and do something specific instead you can define your own verify method and aliasing the verify method from the trait so you can still use it:
use Illuminate\Auth\Access\AuthorizationException;
use Illuminate\Foundation\Auth\VerifiesEmails;
use Illuminate\Http\Request;
class VerificationController extends Controller
{
use VerifiesEmails {
verify as verifyTrait;
}
...
public function verify(Request $request)
{
try {
return $this->verifyTrait($request);
} catch (AuthorizationException $e) {
return ; // what ever you would like to do on failure
}
}
}

Laravel socialite 3.0 google return 403 - Forbidden

I am using Laravel 5.6 and socialite 3.0. I have created google API from developer console and enable for Gmail API and google plus. please check screen shot.
Also, I have to make setup inside .env file.
Google callback return 403 error code
I have created class and method
public function redirect($provieder)
{
return Socialite::driver($provieder)->redirect();
}
public function callback($provieder)
{
try{
$user = Socialite::driver($provieder)->stateless()->user();
if (isset($user)) {
$social = $this->createUser($user,$provieder);
return redirect()->route('profile.fill','location');
}
return redirect()->route('user.signup');
}catch (Exception $e) {
return redirect('auth/google');
}
}
I have create route file
Route::get('auth/{provider}', 'OAuth\SocialController#redirect');
Route::get('auth/{provider}/callback', 'OAuth\SocialController#callback');
You had to activate the Google+ API from the Google Developers Console.
It was indeed an HTTP 403 Forbidden response.
I learned a bit more about "ClientException"... it is thrown by Guzzle's HTTP client, and it contains a few useful properties, mainly request and response:
try {
$user = Socialite::driver('google')->user();
}
catch (GuzzleHttp\Exception\ClientException $e) {
dd($e->response);
}
This error says that the server could understand the request from the client, but it refuses to proceed with further actions with the request. It is often displayed when the server is configured to deny the client’s request for some reason.
The causes behind 403 error page
If the URL you’ve entered is correct, then it can be any of the following three reasons.
1) No index page
2) Empty html directory
3) Poor permission configuration or ownership issues.
The above listed are the most common reasons of 403 forbidden error.
check that link for how to fix it

This page isn't working redirected you too many times

I am trying to use Socialite library in Laravel 5 and Facebook API to create a "login with Facebook" feature. I followed all of the steps in the tutorial and created an app on Facebook developers, but when I click on the login button, it crashes with the error "This page isn't working redirected you too many times." Below is my callback code. Why isn't this working?
public function handleFacebookCallback()
{
try {
$user = Socialite::driver('facebook')->user();
$create['name'] = $user->getName();
$create['email'] = $user->getEmail();
$create['facebook_id'] = $user->getId();
$userModel = new User;
$createdUser = $userModel->addNew($create);
Auth::loginUsingId($createdUser->id);
return redirect()->route('home');
} catch (Exception $e) {
dd($e);
return redirect('auth/facebook');
}
}
You're getting this error message because the code in try block is failing and executing the catch block which is redirecting the request back to the server which is sending it back to the browser over and over. Die and dumping (dd) the exception reveals this error message:
General error: 1364 Field 'password' doesn't have a default value
The "create new user" function isn't working because the database is sending back a fatal error. The database is dying because there is no value for the password in the insert and the table requires it. Which makes sense when you think about it because the user is creating an account via Facebook and not creating a user ID and password.
Making the password column in the user table able to be null fixes this "[x] redirected you too many times" error.

Laravel passport custom error message and status code when user unauthorized

my project is running on Laravel 5.4 and I use passport to make authentication via api with bearer token. everything works fine, but when unauthorized user tries to reach resource that require authentication, the user gets error message 405 method not allowed
but I want response to be 401 unauthorized .
how can change this, and send only response with message, instead of exception? I did research, but couldn't find anything. I use standard laravel middleware for authorization auth:api. my routes grouped in middleware
Route::group(['middleware' => 'auth:api'], function () {
// these routes should return 401 if user not authenticated
}
Well method not allowed exception happens because you are hitting the wrong endpoint. You are posting to a get or vice verca.
However you can modify your exceptions if you go to App\Exception open up handler.php in render() method there you can adjust exceptions as you want example:
public function render($request, Exception $exception)
{
if ($exception instanceof \Illuminate\Auth\AuthenticationException) {
return response('unauthorized', 401);
}
return parent::render($request, $exception);
}
On handler() method just check if $exception is instance of any exception object, if so you can modify the response as you want. For laravel exceptions follow link

How to get Facebook user detail from Access Token using Codeigniter?

I'm really struggling to understand what's happening here. I can get a Users details fine in the OpenGraph tester or just hitting the URL https://graph.facebook.com/me?access_token=VALID_TOKEN or using file_get_contents, but when trying the Codeigniter Facebook Library I get error "An active access token must be used..." and if I just try a CURL GET I get no output. I know the access_token is valid so why aren't they working? The overall objective is to get an access_token from iOS App and use this to do a Like via the web server using og.likes.
My test function:
function me_test(){
$access_token = "VALID_TOKEN";
$url = 'https://graph.facebook.com/me?access_token=';
$url_full = $url.$access_token;
$result = file_get_contents($url_full);
echo $result;
// Try Codeigniter Facebook Library
try {
$user = $this->facebook->api('/me?access_token='.$access_token);
} catch (Exception $e) {
print_r($e);
}
// Codeigniter CURL Library
$this->load->library('curl');
echo $this->curl->simple_get($url_full);
$info = $this->curl->info;
print_r($info);
}
I have also faced this issue and find the alternate way to get userdata. You can try this
function me_test(){
$userId = $this->facebook->getUser(); //This will return the current user id
// Try Codeigniter Facebook Library
try {
$user = $this->facebook->api('/'.$userId);
//When you pass the userid you dont need to provide access token
} catch (Exception $e) {
print_r($e);
}
}

Resources