Google Authentification Laravel Socialite gives 403 Error when asking for 'profile' scope - laravel

As the title says, I'm getting a 403 Forbidden Error when asking for the 'profile' scope.
Here's my code
// routes/web.php
Route::get('google', 'Auth\GoogleAuth#auth')->name('google-signup');
Route::get('googlecallback', 'Auth\GoogleAuth#callback');
// Auth/GoogleAuth.php methods
public function auth()
{
return Socialite::driver('facebook')->redirect();
}
public function callback()
{
$socialUser = Socialite::driver('facebook')->user();
dd($socialUser);
}
The reason I know it's the 'profile' scope is because when I tried
public function auth()
{
return Socialite::driver('facebook')->setScopes(['email','openid'])->redirect();
}
Everything worked, prefectly, I get the email and the id, only I don't get user info without the 'profile' scope. and I need said information (name, first name, last name ..etc).
I tried the stateless() solution but I kept getting the same 403 Error.
I saw some similar questions here and in github but the solutions didn't work for me either.
Laravel version 7.x
Laravel Socialite version 4.4
I'd appreciate any help.

Okay... This question is out there a lot with few (or wrong) answers. I happened to run into this on 2 different Amazon Lightspeed instances with the exact same code installed and on one server Google login/callback worked fine and on the other 403.
This is MOD SECURITY issue. It's blocking the use of .profile which is in the Laravel code apparently or perhaps required to pull down the Google user data. What you need to be able to do to fix this is turn off the ID for this rule in mod-sec. For me that was 210580.
Message: Access denied with code 403 (phase 2). Matched phrase
".profile" at ARGS:scope. [file
"/etc/apache2/modsecurity.d/rules/comodo_free/08_Global_Other.conf"]
[line "57"] [id "210580"] [rev "2"] [msg "COMODO WAF: OS File Access
Attempt||aeroscale.net|F|2"] [data "Matched Data: .profile found
within ARGS:scope: email profile openid
https:/www.googleapis.com/auth/userinfo.profile
https:/www.googleapis.com/auth/userinfo.email"] [severity "CRITICAL"]
[tag "CWAF"] [tag "Other"] Apache-Error: [file "apache2_util.c"] [line
273] [level 3] [client 73.238.35.209] ModSecurity: Access denied with
code 403 (phase 2). Matched phrase ".profile" at ARGS:scope. [file
"/etc/apache2/modsecurity.d/rules/comodo_free/08_Global_Other.conf"]
I added that to my Plesk exception list in Mod Security and it started working on this server. Ironically I don't have that rule installed on the other server and it works fine. It's a slightly lower end server though so perhaps Amazon runs a different rule set on them.

Related

User authenticating but not staying logged in Laravel 8.x

When testing my application and trying to create a new user then on form submission I am getting error 419.
If I use a helper to log in using Auth::loginUsingId(x) for an existing user then dd(auth()->user()) is successful but when I redirect to another page the user is no longer logged in. eg running the following code, you end up getting redirected to /login:
Route::get('/logInAs/{id}', function ($id) {
Auth::loginUsingId((int) $id);
dd(\auth()->user());
return redirect()->route('dashboard');
});
I would share more code but I'm not sure what would be useful at this point?
I've probably spent about seven hours trying to fix this so far. It's driving me up the wall!
The app works fine on other environments, such as staging. I've even gone so far as to re-download it from github as a fresh install (in case I was messing about in vendor directory and changed something), but that hasn't fixed it.
I get the same issue on Chrome, using different signed in users on Chrome, using incognito mode on Chrome, using Firefox, and using valet share and accessing my local version on another device, like a phone, so I don't think it is to do with browser caching.
When other devs working on the project run it locally on their machines I haven't had reports of this issue, so it seems to just me my local environment.
I've variously tried changing CACHE_DRIVER and SESSION_DRIVER in .env to no joy, but I'm beginning to lose the will to live so don't really know if I'm doing the right thing there - please help if you can!!
Edit to add more detail:
Middleware on the dashboard route:
Route::middleware(['auth:sanctum', 'verified'])->group(function(){
Route::get('/dashboard', DashboardController::class)->name('dashboard');
});
If I remove the middleware then I just get an error that user is null on dashboard.blade.php, ie the user is still not staying logged in.
A custom middleware:
class VerifyUserIsMerchant
{
public function handle(Request $request, Closure $next)
{
if ($request->user()->isMerchant()) {
return $next($request);
}
throw new AccessDeniedHttpException('You must be a merchant to access this page');
}
}
If I dd($request->user()) in this middleware it returns null.
The issue got fixed with the help of Laracasts. The full answer is here.
In short, I needed to remove the http:// protocol from SESSION_DOMAIN in .env and set it to match APP_URL.
This was the correct answer for this issue. It was deleted by a moderator. Moderator, before you delete this answer as well please can you explain why?
It provides the full answer to the issue raised in the question. I did not find this answer to this issue anywhere else (hence why it took me several days of debug to fix).
If I can know why it was deleted, I can then understand how to avoid making answers in the future that also would be deleted. Thank you.

Trying to set up CAS with my Laravel project

I am using subfission/cas for my application. I have followed all installation steps. I am using windows, if that matters. More precisely, I have configured the following:
I ran the following in my terminal
composer require "subfission/cas" "dev-master"
I configured my Kernel.php accordingly, adding the following:
'cas.auth' => 'Subfission\Cas\Middleware\CASAuth',
'cas.guest' => 'Subfission\Cas\Middleware\RedirectCASAuthenticated',
I ran the following command:
php artisan vendor:publish
I also set up my cas server in my cas.php config file:
'cas_hostname' => env('CAS_HOSTNAME', 'cas.myserver.me'),
'cas_real_hosts' => env('CAS_REAL_HOSTS', 'cas.myserver.me'),
What I want is a middleware for all my routes, so I added the following route rule in my routes:
Route::middleware(['cas.auth'])->group(function ()
{
Route::get('/', function ()
{
return view('welcome');
});
});
Basically, I want to redirect everyone who is not logged in to the login page whenever I access the main page (for now, I will add more routes in the future). What happens is that the users are redirected to the login page when they are not logged in, but after the login I receive the following error:
ErrorException (E_WARNING)
DOMDocument::loadXML(): Opening and ending tag mismatch: hr line 1 and body in Entity, line: 1
No matter what view I'm redirecting the user to. I tried the default welcome page as well as an empty view, but I still get the same error.
EDIT: I have used the dev-master branch from subfission/cas for the above error and after switching to 2.1.1, I get a different error:
session_name(): Cannot change session name when headers already sent
EDIT 2: I did some more digging and I enabled internal errors in my cas client class with:
libxml_use_internal_errors(true);
And now I get the following:
Authentication failure: SA not validated Reason: bad response from the CAS server
And the cas response is:
The thing is that I use the same cas server for another 2 projects and it works well for those (but those aren't laravel projects.
I know it's been a while, but for anyone else having issues like this, the issue is the protocol selected for which your web service communicates with your CAS(Central Authentication Service) provider. There are two main protocols used for SSO/CAS in this package:
SAML(Security Assertion Markup Language) version 1.1 & 2
CAS Protocol v3.0
[Confusingly enough, CAS protocol shares the same namespace as the service.]
The idea is to match the protocol and version with your identity provider. It sounds like your provider is using CASv3.0, which is why disabling SAML worked.
Also, if you enable debug mode, you will see further error details in your log file to help your troubleshoot.
Best of luck!
I managed to solve the issue by disabling the SAML in the cas configure file:
'cas_enable_saml' => env('CAS_ENABLE_SAML', true),
change to
'cas_enable_saml' => env('CAS_ENABLE_SAML', false),

Laravel Socialite InvalidStateException in AbstractProvider.php line 200

I'm building a web app in my local system (Ubuntu-14.04 64Bit) using laravel 5.3. I used Socialite to signin from social networks. I configured G+, Facebook, GitHug. I'm using Chromium as my default browser. Finally the problem is i'm getting
InvalidStateException in AbstractProvider.php line 200
frequently. i tried
php artisan cache:clear
php artisan config:clear
composer dump-autoload
these are helping to solve the issue temporarily, again the problem raising.
please help me in this issue..
I have the same issue and I've read a lot about this, that depend if the URL where you are at the moment of the login request has www. at the beginning or not.
Into config\services.php, if you have the redirect set as http://sitename.tld/callback/facebook the oauth works if you send the login request from sitename.tld, while if you try from www.sitename.tld you get the exception.
I haven't yet understood how to have it working with and without www at the beginning.
If the AbstractProvider.php line 200 fires the exception when the state of the user is not present means that the User cannot be created.
First check your code when you get the details from the provider(facebook, github) if you create a user and you return it.
If you have managed and logged in your app and you deleted the user from the user table remember to delete also the data from the socialite account table.
I was getting that exception because 'state' wasn't saved in session. But I was using asPopup method - Socialite::driver('facebook')->asPopup()->redirect(); so I saved session then - $request->session()->save();. So I solved this issue.
or try
session()->put('state', $request->input('state'));
$user = Socialite::driver('facebook')->user();
it works
I have same issue and solved in 3 steps;
add request on the top
use Illuminate\Http\Request;
Pass request object to function
public function handleProviderCallback(Request $request)
{
try {
$user = Socialite::driver('facebook')->user();
} catch (Exception $e) {
throw new Exception;
}
}
Clear cache.
php artisan cache:clear
I had the same error but my solution was a little different. I am posting here just in case someone else keeps hitting this post like I did for a possible answer.
I develop on Ubuntu 18.04 desktop since it is a server with a GUI. Socialite works great locally but as soon as I pushed/pulled the changes through git to the server, it quit.
I was running traces by recording what was sent to and from google. I "dd($_GET)" to get a raw dump before Socialite had a chance to get the info so I knew what was stored and ready for use. All info was there but Socialite didn't seem to "see" it. That is when I reasoned it was my apache2 header configuration interfering with the cookies/session data.
I had set header security in my apache2 configs. One of the settings was
Header always edit Set-Cookie ^(.*) "$1;HttpOnly;Secure;SameSite=Strict"
This setting was interfering with the cookie information that socialite needed. I removed that setting from my apache2 header config(by commenting out) and restarted Apache. Finally I removed all sessions in storage/framework/session/* and cleared them from my browser just to be sure. That worked for me.
After I got it working, one by one enabled and tested each of the following settings to have the framework secure what header info it can:
SESSION_SECURE_COOKIE=true
in my .env file
'http_only' => true, and
'same_site' => 'lax'(setting to "strict" did not seem to work)
in my config/session.php file.
Now it is back to testing security and tweaking things back if need be.

Bitbucket - Webhook keep returning error 500

Would like to check, I am fairly new to Bitbucket's new introduced webhook where previously i was using services where Bitbucket will execute a link to my site thus triggering a deployment script.
So since the old service is going to be depreciated soon, we all migrated to webhook instead. With the same implementation, I keep getting an error 500 upon commit/push/merge and there is no way for us to see the details for the error given. At first I thought it was my server giving problem but when i call the link manually via browsers and everything was fine. The deployment script can be executed successfully so then why bitbucket's webhook keeps telling me error 500?
Subsequently I find the guide given by Bitbucket was not helpful. There is no specified call method to the url stated so is the webhook initiates a GET or POST request? previously using services initiates a POST request. Then, are there any necessary payloads i need to include into the webhook URL? None is stated. Then, if there is an error at least let me see the error so I can fix it instead of telling me error 500.
I hope someone here can help me with this issue. Below are some specification of the site.
Server : Ubuntu LEMP 14.04 x64 Laravel framework 5.0
Webhook Url: bot.example.com/bitbucket/deploy/{Site API}
Method : GET
And when the abode link is call, it reaches a controller that does
public function attemptDeploy($site_api)
{
$script = 'nohup setsid php ~/scripts/deploy.php ' . $site_api. ' > /dev/null 2>&1 &';
exec($script);
return response('Deploy running.', 200);
}
Note that when i call this link manually either form browser or console everything works perfectly except from bitbucket's webhook. How can i solve this issue?
I was in the same situation. Bitbucket trims the body of the response and I couldn't see the error given by my server.
I've looked into the logs storage/logs/laravel.log and saw TokenMismatchException. Webhooks being API calls they don't store cookies or sessions so CSRF from Laravel breaks.
You need to add an exception from CSRF for the bitbucket deploy route. You can add this exception in app/Http/Middleware/VerifyCsrfToken.php. For example if your link is www.your_site.com/bit_deploy you will have:
<?php
namespace App\Http\Middleware;
use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as BaseVerifier;
class VerifyCsrfToken extends BaseVerifier
{
/**
* The URIs that should be excluded from CSRF verification.
*
* #var array
*/
protected $except = [
'bit_deploy'
];
}
Hope that this helps you ... as I've lost 3 hours on this.
PS: at the time of writing this answer, bitbucket webhooks performs POST calls (not GET)

"Server Error" when users try to create a new account - Magento 1.7

I'm setting up our Magento 1.7 store, hoping to be ready for launch soon. I've noticed a problem:
When users try to create a new account, they fill out their info on /customer/account/create page just fine, then when they click submit, they get this 500 Error:
The website encountered an error while retrieving
http://example.com/customer/account/createpost/.
the account is actually created, however.
Similar deal on when users submit their email on the Forgot Password page, they press submit and get this:
The website encountered an error while retrieving
http://example.com/customer/account/forgotpasswordpost/.
no email is sent.
If you see this and know how to help with this prob, your advice would be much appreciated, truly.
In case it helps, we are using a theme, rather than default.
EDIT - (I was asked if I had checked server error)
My server errors show as this, for the above situations:
Forgot Password submit shows this error:
Fatal error: Call to undefined method Mandrill_API::addTo() in
D:\Magento\app\code\core\Mage\Core\Model\Email\Template.php on line
438
and
Create Account submit shows this error:
Fatal error: Call to undefined method Mandrill_API::addTo() in
D:\Magento\app\code\core\Mage\Core\Model\Email\Template.php on line
438
as well.
Here is 6 lines(437-442) of that Template.php file:
foreach ($emails as $key => $email) {
$mail->addTo($email, '=?utf-8?B?' . base64_encode($names[$key]) . '?=');
}
$this->setUseAbsoluteLinks(true);
$text = $this->getProcessedTemplate($variables, true);
[UPDATE]
I've learned that when I enter a random, fake email for Forgot Password, and press submit, a confirmation appears, saying something like "If this email exists, then a new email was sent to that email!", but when I submit an email of a real existing customer, then it gives me the 500 error I've mentioned.
Still nothing - if anyone out there sees this, and you have a bit of time to help solve this perhaps, may Talos bless you!
[SOLVED]
I turns out this was a problem with transaction emails.
Cause by an extension, Mandrill, which is added to magento when I installed the MailChimp extension, called "MageMonkey - MailChimp Integration by ebizmarts"
Once I enabled Mandrill, in config, advanced, all transactions and transaction emails work perfectly fine!
It's possible that it's a .htaccess or server configuration problem. Where is it hosted? Do you have a .htaccess file in the root of the installation?

Resources