Laravel 5.7 - Spark API authentication session issues - laravel

Just going to preface this question by saying that I'm diving back into Laravel after a while of not using it, it appears there are a lot of changes, and the current project in question is using A LOT of the baked in "Laravel Ecosystem"... so I could be missing some context here.
The issue : After upgrading from Laravel 5.6 to 5.7, auth-guarded API routes are busting because of session expiry, even immediately after logging in (prompting logout).
The configuration :
/config/auth.php
'guards' => ['api' => ['driver' => 'spark']]
/routes/api.php
Route::group([
'middleware' => 'auth:api'
], function () {
// Routes in here are busting
}
/app/Providers/SparkServiceProvider.php
protected $usesApi = true; // yup
Additional info :
The site uses the Socialite plugin for managing user authentication
There are indeed spark_token's in the request
Vue client making the calls, getting status 401 Unauthorized on the next page load after successfully authenticating via login form
It was working perfectly fine before upgrading from Laravel 5.6 to 5.7
Any ideas? I've poured through the Laravel 5.7 release notes / upgrade guide, not finding any relevant info.

Found a solution that worked for me:
Add to app/Http/Middleware/EncryptCookies.php
/**
* Indicates if cookies should be serialized.
* #var bool
*/
protected static $serialize = false;
Then clear cookies from your browser, and retry logging in.

Related

Lumen directing all routes of specific group to *

I'm developing a website with simple landing page and a few other page such as contacts and news as front end (which uses normal PHP and lumen should be sufficient bythe way) and vuejs as backend. Trying to send all get request from '/admin/' to view('admin'). This is the best I could come up with...
$router->group(['prefix' => 'admin'], function () use ($router) {
$router ->get('/{route:.*}/', function () use ($router) { return view('admin');
});
The problem is all url I do or access, all get request response I get was 404 - not found. Not even any log or anything in lumen log or even in error log apache server. Where did I do wrong?
//using lumen since I need API for vuejs operations.

Laravel Passport Password Reset API route

I'm all set up with Passport in 5.5 and have the auto generated Auth\ForgotPasswordController and Auth\ResetPasswordController controllers.
However whereas /oauth/token was provided magically for me, there don't appear to be such routes for password reset when using the API.
What should my API routes look like?
Currently I've experimented with
Route::group(['prefix' => 'password'], function () {
Route::post('/email', 'Auth\ForgotPasswordController#sendResetLinkEmail');
Route::post('/reset', 'Auth\ResetPasswordController#reset');
});
but I found these in the vendor files when looking at the traits and aren't sure if this is the correct way.
The /password/email route also fails with "message": "Route [password.reset] not defined."
since you don't see any route other then 2 custom, therefore i am assumin you havn't run artisan auth command. First run that. it will add lot of routes in ur project.
Then set api driver to passport.

Enabling session in lumen framework

I have two (but let's image more) micro-services (API) which need to be aware of authenticated user. Ideally I would simple like to resume their sessions.
All micro-services are using same storage for sessions: redis.
All API calls will have Cookie header, so all services will be able to resume sessions based on that cookie. I have successfully implemented this via PHP $_SESSIONs.
Now the question: how would you go about implementing this with Laravel/Lumen?
Last update on 5th of March 2021
(This answer was getting a lot of attention from Laravel community so I thought of updating it.)
Laravel has officially stopped supporting sessions & views in laravel/lumen framework from version 5.2 and on wards.
But laravel still have a component illuminate/session which can be installed in lumen/framework and we can play around with this.
Step - 1
install illuminate/session using
composer require illuminate/session
Step - 2
Now goto bootstrap/app.php and add this middleware
$app->middleware([
\Illuminate\Session\Middleware\StartSession::class,
]);
Purpose of adding the above middleware is to start session on every request and save session before serving response.
Step - 3
Now add config/session.php, since it is not present in Lumen by default. You can take session.php from Laravel official repo.
Step - 4
Create framework session storage directory by
mkdir -p storage/framework/sessions
Thanks to DayDream
Step - 5
In bootstrap/app.php add bindings for \Illuminate\Session\SessionManager
$app->singleton(Illuminate\Session\SessionManager::class, function () use ($app) {
return $app->loadComponent('session', Illuminate\Session\SessionServiceProvider::class, 'session');
});
$app->singleton('session.store', function () use ($app) {
return $app->loadComponent('session', Illuminate\Session\SessionServiceProvider::class, 'session.store');
});
Thanks to #xxRockOnxx for finding loadComponent method.
It takes 3 arguments,
first one is config file name. (file should be present in config/ directory)
second is ServiceProvider FQN
third is return of this method.
loadComponent just calls the $app->register and inject $app while building the ServiceProvider
How to Use
// Save Session
$router->get('/', function (\Illuminate\Http\Request $request) {
$request->session()->put('name', 'Lumen-Session');
return response()->json([
'session.name' => $request->session()->get('name')
]);
});
// Test session
$router->get('/session', function (\Illuminate\Http\Request $request) {
return response()->json([
'session.name' => $request->session()->get('name'),
]);
});
I've also added example over github supporting from lumen framework v5.6 to all the way to current version v8.0.
https://github.com/rummykhan/lumen-session-example
It is important to that you also use $request->session(), otherwise it will not work.
I tried the solution mentioned above, however, it's also required to create a folder storage/framework/sessions if using the default settings.
The accepted answer is outdated.
I answered and explained a bit how to properly do it in my answer on this question
I also posted what is the problem on my question at Laracasts
To quote:
the solution that is found in the link you gave is that, first it tells you to manually register the SessionManager to prevent the unresolvable depedency parameter #0 $app then also register the existing SessionServiceProvider which also binds another instance SessionManager.
Problem with that is, some components use the other instance and other parts use the new one which causes my auth attempt session not being save despite actually being put inside.

Driver [provider] not supported laravel/socialite

I'm using Laravel 5.4 and Socialite 3.0
With every new socialite provider I add I get the error:
Driver [provider] not supported.
for example when adding socialiteproviders/twitch 3.0 I will get the error:
Driver [twitch] not supported.
However I can use a provider that's already built in to Socialite, github for example works as expected.
I have tried three different providers and I get the same result each time, what am I doing wrong?
Here are my routes:
Route::get('/auth/bnet', 'BnetController#redirectToProvider');
Route::get('/auth/bnet/return', function() {
$user = Socialite::driver('battlenet')->user();
dd($user->accessTokenResponseBody);
});
Route::get('/auth/git', function() {
return Socialite::driver('github')->redirect();
});
Route::get('/auth/twitch', function() {
return Socialite::with('twitch')->redirect();
});
Here's my $listen from my EventServiceProvider:
protected $listen = [
\SocialiteProviders\Manager\SocialiteWasCalled::class => [
// add your listeners (aka providers) here
//'SocialiteProviders\Battlenet\BattlenetExtendSocialite#handle',
'Reflex\SocialiteProviders\BattleNet\BattleNetExtendSocialite#handle',
'SocialiteProviders\Twitch\TwitchExtendSocialite#handle',
],
];
I have added SocialiteProviders\Manager\ServiceProvider::class, to my providers array in app.php, I have added the Socialite facade ('Socialite' => Laravel\Socialite\Facades\Socialite::class,) to my aliases array also in app.php and have added the appropriate keys to my .env
I had the same issue and I found solution.
In config/app.php providers array:
'providers' => [
// ...
Laravel\Socialite\SocialiteServiceProvider::class,
\SocialiteProviders\Manager\ServiceProvider::class,
// ...
]
In app/Providers/EventServiceProvider.php:
protected $listen = [
// ...
\SocialiteProviders\Manager\SocialiteWasCalled::class => [
'SocialiteProviders\VKontakte\VKontakteExtendSocialite#handle',
],
]
You missed \ at start of 'SocialiteProviders\Twitch\TwitchExtendSocialite#handle'.
Hopefully this helps someone, but I found that I had to separate the EventServiceProvider.php listen classes with "\\" instead of "\". Laravel 5.6. e.g:
protected $listen = [
\SocialiteProviders\Manager\SocialiteWasCalled::class => [
'SocialiteProviders\\Twitch\\TwitchExtendSocialite#handle',
'SocialiteProviders\\Podio\\PodioExtendSocialite#handle',
],
If you're still struggling, triple-check to ensure all of the packages are installed.
I also found that including...
Laravel\Socialite\SocialiteServiceProvider::class,
...in your config/app.php is not necessary when using SocialiteProviders\Manager.
Make sure that you have updated config/services.php to include the client_id client_secret and redirect from your provider.
Clear your config and try again.
Adding an answer here because this question comes up while searching for the same error as it pertains to Lumen as well and I suspect others may run into the same issue that I did.
The Lumen-specific documentation for additional providers doesn't appear to mention some gotchas (at least, for my version of Lumen) and Lumen needs a little extra configuration to work compared to Laravel.
I'm on Lumen 5.8.2 and had been becoming increasingly frustrated getting Socialite with additional providers set up - all of my configuration in bootstrap/app.php and EventServiceProvider.php seemed correct (and was) until I realized that Lumen wasn't actually registering the EventServiceProvider itself.
To remedy this problem, register the EventServiceProvider within your bootstrap/app.php setup:
$app->register(App\Providers\EventServiceProvider::class);
With the EventServiceProvider registered, just refer to the other answers here to configure events, the provider's service config and registering Socialite in app.php and you ought to be good to go.
I had the same issue, to solve it i change the order of my bootstrap/app.php config, try moving the next lines after the Event ServiceProvider:
$app->register(\SocialiteProviders\Manager\ServiceProvider::class);
class_alias(Laravel\Socialite\Facades\Socialite::class, 'Socialite');
//$app->register(Laravel\Socialite\SocialiteServiceProvider::class);
After:
$app->register(App\Providers\EventServiceProvider::class);
My issue was because i declared all the Socialite and SocialiteProvider stuff before.

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.

Resources