Zend_Auth clearidentity and Zend_Session::destroy causing confusion - zend-framework

I have the following logout action:
public function logoutAction() {
Zend_Auth::getInstance()->clearIdentity();
Zend_Session::destroy();
$this->_helper->flashMessenger->addMessage(array('success' =>
_('You were successfully logged out.')));
$this->_redirect('/index/index');
}
If I don't comment out the line: Zend_Session::destroy() I get an error:
Fatal error: Uncaught exception 'Zend_Session_Exception' with message 'The session was explicitly destroyed during this request, attempting to re-start is not allowed.' in /usr/local/share/php/library/Zend/Controller/Plugin/Broker.php on line 336 Zend_Session_Exception: The session was explicitly destroyed during this request, attempting to re-start is not allowed.
I have read about this issue here and here but remain unclear on how I should proceed. Should I just not use Zend_Session::destroy()? What would be the implications and dangers of not using it, and what is the alternative?

What causes you problems is, that right after destroying the session, you are reusing it (by facilitating the FlashMessenger. If not destroying the session after logout bothers you, you could display a logout page instead of redirecting to your frontpage with a flash message.
Leaving some of your session data intact after your user logged out, might have security implications, but that depends on what you store in your session and where and how you use the data. In order to make sure, that you don't keep data, that belonged to the logged in user in your session, just use a specific session namespace for this data and call unsetNamespace() upon logout.

Zend_Auth have its own session namespace and after Zend_Auth::getInstance()->clearIdentity(); it removes it so there is no need to destroy all session nemaspaces if you use them.
Example what here happens:
// logging user
$_SESSION['Zend_Auth'] = 'logged user data';
// after Zend_Auth::getInstance()->clearIdentity();
$_SESSION['Zend_Auth'] = null;
// after Zend_Session::destroy();
session_destroy();

Related

CloudHSM login/logout error

So i was trying to login/logout from AWS CloudHSM multiple times. The flow is the following:
Have an open session (C_GetSessionInfo returns slot id 1, state 3, flags 6 while everything goes fine).
If i'm logged in to this session, call C_Logout on this session.
Call C_Login supplying the correct credentials.
Repeat.
After the first login, the first logout/login cycle goes fine but during the second logout a CKR_DEVICE_REMOVED error is returned and every subsequent calls return CKR_SESSION_HANDLE_INVALID.
Calling C_GetSessionInfo after the error returns slot id, state and flags all set to 0 and C_GetSlotList with token present returns an empty list. This behavior (error on the second logout) is completely consistent and happens every single time. No operations are performed while being logged in.
Does anyone know the possible reason for this error and how to avoid it? Thanks in advance.
You need not logout each time when you do some operation. The best way is: You should re-use the session handle id which you got when you login for the first time.

How to login with user but still stay admin?

I want to implement feature when operator/admin may login as user. Do something under user's credentials and then return back and continue as operator/admin
I try to mount whole application under /as_user/:user_id route. So when request come I adjust session to :user_id.
I try detour
$app->routes->route( '/as_user/:app_user' )->detour( app => $app );
But in this case when GET /as_user/17/packages request come the application fall into infinite loop
Also I think to append ?U=17 query parameter. But I do not know how and where rewrite code in such way: All link should be rendered with ?U=17 appended.
Please advice how to login with another user but still stay admin.
Seems I found the answer:
$r->under( '/as_user/:user_id', sub{
# FIX THE SESSION HERE. Just like:
# $_[0]->session->{ user_id } = _[0]->match->stack->[-1]->{ user_id };
return 1; # Required to not break the dispatch chain
})->route('/')->detour( 'App' );
Instead of application instance you should pass application class and Mojolicious will instantiate it itself.
PS. Infinite loop maybe because of cyclic refs. (But Mojolicious check refs here)
UPD
Infinite loop because of bug

Laravel Socialite: InvalidStateException in AbstractProvider.php line 199:

For some reason I get this exception when I try to log in with Laravel Socialite with either Facebook or Google:
InvalidStateException in AbstractProvider.php line 199:
The exception are thrown from my SocialiteController, when it tries to get the user from the facebook driver.
public function callback(SocialAccountService $service, $provider)
{
try {
var_dump(Socialite::driver('facebook')->user());
Here are the part of AbstractProvider.php that seem to throw the actual exception:
public function user()
{
if ($this->hasInvalidState()) {
throw new InvalidStateException;
}
I have been following this tutorial https://blog.damirmiladinov.com/laravel/laravel-5.2-socialite-twitter-login.html#.WFK0BfnhCUk. The login have worked fine until last week, for some reason.
I read other articles saying I should change config/session.php so domain is not null but my current domain (in my case localhost:8000 since I run local with XAMPP), and refresh Laravel cache etc. But it did not work.
I have discovered that my Laravel application cookies where missing, which caused the InvalidStateException exception.
I also noticed that the cookies were not recreated after each HTTP request. When I changed the domain value in Config/Session.php from my current one ("localhost") to null (the default value), then the cookies were recreated again.
Try
session()->put('state', $request->input('state'));
$user = Socialite::driver('facebook')->user();

passport.socketio's passport "Failed to deserialize user out of session". But passport in my main app (with the same key) deserializes just fine

passport.socketio throwing this error, while failing to authorize the user.
Error: Error: Failed to deserialize user out of session
I've narrowed the problem down to passport.socketio's /lib/index.js.
At line 59
auth.passport.deserializeUser(userKey, function(err, user) {
if (err)
return auth.fail(data, err, true, accept);
...
It throws that error. Debugger tells me the userKey is valid, and should deserialize the user. It's the same key that passport in my main app uses to deserialize the user. (it's the ID of mongoDB object). And passport in my main app has no problem deserializing the user. (details)
So don't know why this still throws the error.
The userKey passed here is the same key passport in my main app uses to deserialize.
I've gone to the extent of making the userKey global and putting it in my main code
passport.deserializeUser(global.userKey, function(err, user) {
if (err)
return auth.fail(data, err, true, accept);
console.log('ok');
Which results in infinite loop (because it's inside outer passport.deserialize) but iut prints 'ok'!, so passport from my main app can atleast deserialize just fine using the same thing that passport from index.js (passport.socketio\lib\index.js) can not! .. for some reason.
Then I've even tried passing the passport object itself from main app
io.set('authorization', require('passport.socketio').authorize({
passport: passport,
...
which actually results in no errors!! but then I don't get the socket.handshake object.
I'm out of ideas to diagnose this any further and would really appreciate any help whatsoever.
What could be causing passport.socketio's passport to not "deserialize user out of session"?
Deleted npm_modules, re-wrote the packages.json with "every_package":"latest", and so basically re-installed every package's latest version. That fixed it.
One problem could be that you have configured your 'passport' instance in the main app to use a specific 'deserializeUser' implementation. look for all the places where your passport has been intiallized in the main app. (If its a framework like mean.io, you will find it in config/passport.js).
Make sure the same initiallization is done to the passport instance in the socket app. Pass it to passportsocketio as such:
passportSocketIo.authorize({
passport: passport,
cookieParser: express.cookieParser,
key: 'connect.sid'
...
});

asp.net mvc azure "Error accessing the data store!"

I've started using the AspProviders code to store my session data in my table storage.
I'm sporadically getting the following error:
Description: Exception of type 'System.Web.HttpException' was thrown. INNER_EXCEPTION:Error accessing the data store! INNER_EXCEPTION:An error occurred while processing this request. INNER_EXCEPTION: ConditionNotMet The condition specified using HTTP conditional header(s) is not met. RequestId:0c4239cc-41fb-42c5-98c5-7e9cc22096af Time:2010-10-15T04:28:07.0726801Z
StackTrace:
System.Web.SessionState.SessionStateModule.EndAcquireState(IAsyncResult ar)
System.Web.HttpApplication.AsyncEventExecutionStep.OnAsyncEventCompletion(IAsyncResult ar) INNER_EXCEPTION:
Microsoft.Samples.ServiceHosting.AspProviders.TableStorageSessionStateProvider.ReleaseItemExclusive(HttpContext context, String id, Object lockId) in \Azure\AspProviders\TableStorageSessionStateProvider.cs:line 484
System.Web.SessionState.SessionStateModule.GetSessionStateItem()
System.Web.SessionState.SessionStateModule.PollLockedSessionCallback(Object state) INNER_EXCEPTION:
Microsoft.WindowsAzure.StorageClient.Tasks.Task1.get_Result()
Microsoft.WindowsAzure.StorageClient.Tasks.Task1.ExecuteAndWait()
Microsoft.WindowsAzure.StorageClient.TaskImplHelper.ExecuteImplWithRetry[T](Func`2 impl, RetryPolicy policy)
Microsoft.Samples.ServiceHosting.AspProviders.TableStorageSessionStateProvider.ReleaseItemExclusive(TableServiceContext svc, SessionRow session, Object lockId) in \Azure\AspProviders\TableStorageSessionStateProvider.cs:line 603
Microsoft.Samples.ServiceHosting.AspProviders.TableStorageSessionStateProvider.ReleaseItemExclusive(HttpContext context, String id, Object lockId) in \Azure\AspProviders\TableStorageSessionStateProvider.cs:line 480 INNER_EXCEPTION:
System.Data.Services.Client.DataServiceContext.SaveResult.d__1e.MoveNext()
Anyone run into this? The only useful information I've found is this, which I'm hesitant to do:
If you want to bypass the validation, you can open TableStorageSessionStateProvider.cs, find ReleaseItemExclusive, and modify the code from:
svc.UpdateObject(session);
to:
svc.Detach(session);
svc.AttachTo("Sessions", session, "*");
svc.UpdateObject(session);
from here
Thanks!
So I decided to change this:
svc.UpdateObject(session);
svc.SaveChangesWithRetries();
to this:
try
{
svc.UpdateObject(session);
svc.SaveChangesWithRetries();
}
catch
{
svc.Detach(session);
svc.AttachTo("Sessions", session, "*");
svc.UpdateObject(session);
svc.SaveChangesWithRetries();
}
So, I'll see how that works...
I've encountered this problem as well and after some investigation it seems to happen more often when you have more than one instance and you try to make calls in rapid succession in the same session. (e.g. if you had an auto complete box and making ajax calls on each key press)
This occurs because when you try to access the session data, first of all the web server takes out a lock on that session. When the request is complete, it releases the lock. With the table service provider, it updates this lock status by updating a field in the table. What I think is happening is that Instance1 loads the session row, then Instance2 loads the session row, Instance1 saves down the updated lock status and when Instance2 attempts to save the lock status it gets an error because the object isn't in the same state as when it loaded it (the ETag doesn't match any more).
This is why the fix that you found will stop the error from occurring, because by specifying the "*" in the AttachTo, when Instance2 attempts to save the lock it will turn off ETag checking (and over write the changes made by Instance1).
In our situation we have altered the provider so that we can turn off session for certain paths (the ajax call that was giving us our problems didn't need access to session data, neither did the loading of images) which may be an option for you depending on what is causing your problem.
Unfortunately the TableStorageSessionStateProvider is part of the sample projects and so isn't (as far as I'm aware, but I'll happily be told otherwise) officially supported by Microsoft. It does have other issues, like the fact that it doesn't clean up it's session data once a session expires, so you will end up with lots of junk in the session table and blob container that you'll have to clean up some other way.