Session and Auth in Nuclio. How to use it in proper way? - nuclio

When i try to called:
Auth::getInstance()->authenticate($email,$password)
for authenticate in login controller, i called Auth::getInstance()->isAuthenticated() and get result bool(true). Then i go redirect to another page, Auth::getInstance()->isAuthenticated() give bool(false). After i use this authentication, how can i get the session is already bool(true) at any page after that until i'm Auth::getInstance()->unauthenticate() that session or make it global for the session? Currently i'm using session database.
Problem : How to authenticate the current user after redirect to another page?

Without knowing more about your code, I can predict a couple of possible sources of this type of behavior...
1) You're not writing the fact that the user is authenticated to your session/cookie, so the second page request isn't aware of the result of the first one.
2) If the authentication is successful on the first page (and you record this in the session/cookie), and the redirection happens, but you redirect back to a page already seen by the user (e.g. Homepage -> Login page -> Homepage) then your browser might be loading it out of it's local cache rather than fetching the new (authenticated) page from the server.
Try dumping your session variables to the browser to see if the authentication result is being preserved between requests, and try appending a timestamp on the redirection url or using headers to prevent client side caching. This will at least allow you to narrow down, or eliminate these two options.

The Auth plugin already manages all session control for authentication without any additional effort from the developer.
The problem you are facing could likely be because the session is not starting for some reason. This could be because Nuclio isn't detecting that it is being run from a browser. Nuclio detects this by checking REMOTE_HOST and HTTP_HOST values in $_SERVER. If both are null, it won't start the session (to avoid generating headers on a command line).
Also make sure that your base application class is extending the Nuclio Application plugin class and NOT overriding the __construct method without calling the parent construct method as this would cause all the initialization to fail and no session will be created/resumed.

Related

Preventing multiple simultaneous logins with Cognito

We have React Native app that uses Cognito for authentication. We would like to prevent the same user ID from logging in simultaneously from multiple devices.
We were hopefully that we could use a Cognito pre-authentication trigger for this. Unfortunately it seems that we can't just call globalSignOut for the user since that wouldn't invalidate tokens that have already been issued and are currently active (see https://github.com/amazon-archives/amazon-cognito-identity-js/issues/21#issuecomment-331472144).
The other idea was to reject the login if the user is logged in elsewhere. But we can't see a reliable way to tell whether the user is already logged in. We can see if there are valid tokens issued for that user but not if they are currently associated with an active session.
We also thought of maintaining our own DB of active sessions but there is no sign-out trigger so we wouldn't know when to remove a session from the DB.
You can use a token authentication system,
Issue a brand new token for each login, and check for available tokens.
if any token is available for the user that means He/She is logged in some other device, for this case you can prompt user that You are logged in other device.. are you sure you want to log out from that device ? and after clicking yes, you can clear all tokens for that user. And issue a brand new token.
AUTO LOGOUT : this token should be passed all over the back-end i.e. in headers of each and every API call token should be there... and should be checked before doing anything in back-end. if token is not available then throw 401. In your app if any API throws 401 then it means user is UNAUTHORIZED and should be logged out.
or
your app should be listening to one socket that responds to log out when it receives a message of same. so whenever your user logs in, a logout message will be passed across sockets and appropriate device with some token id or unique id will get that message and will log out a particular user from all other devices.
or
have a notification receiver which will be used to log out whenever necessary same as socket.
Reading the link you provided the API token / session system seems being faulty by design since long time already.
So without an own token-system inside cognito you won't have reliable results probably, at least in the current state of the system (as the repository is archived it won't be developed further by the owner).
What I propose is an own field in the database-table for users where each login is honored with an own token. A second own field in the same table with a timestamp, where the last access is saved.
If last access is older than a predefined time of 30, 60 or 120 minutes any user gets logged out.
If the last access is younger than the time-limit then the login-mask has to provide a random access token which is compared with that in the database:
- if the access-token in the database is too old for an active session, or just no access-token is stored, then access can be granted which means login is successful.
- the comparison of the current time with the time-stamp saved in the database is for cases where users never have been logged out by purpose but just by being disconnected or passive. I think this case will happen regularly, so it's no exception.
- logging out by click on a button should destroy the access-token in the database, so that the user can immediately login from any device, even from another one then before.
- if there exists a valid access-token in the database then no new access will be granted and the user should get shown a message that he has to sign out first at another login.
- The access-token could be stored together with a third own field for the session-id to make it more reliable and safe. On logout that session-token-field can be cleared too. The session-token can be copied from the global session if required to be saved in the user-record.
- Any checks are only done on login, tokens never have to be included on every page.
- On active logout the token(s) have to be destroyed to allow a direct login again, else the users had to wait till the max. age of the time-limit is reached to login again - at least on another device then before.
As the login itself is currently done independent from the check that has to be implemented, it would be possible to leave the new access-token completely away but use only the session-id as that differs on any device and browser. But perhaps there exists a situation where one of session-id and access-token can change but the other one not - I don't think so but perhaps I missed something in my considerations.
If you provide the access-token on every page like proposed by #Jadeep Galani or in a cookie - beside the corresponding check - you also can offer a button to sign out from all devices. This would enable the users to change login any time even without logging out at the last used device. Without access-token on every page or in a cookie this general logout-function solution is not possible as else access is only checked on login but not on all pages.
A general question is if it's still worth it to rely on the buggy cognito for login or just replace it completely by an own solution. You even could implement the desired authentication in your site in form of a wrapper-class and the concrete login-system could be replaced without changing that implementation.
You can use the UUID of the device to identify whether it is the same user. Add a UUID to each request header to record it in the DB, and then you can do what you want.

Setting session variables vs setting variable in browser cookie (Django app)

I need to clear a concept.
I'm tracking unauthenticated users in my Django social networking web-app via setting a temp_id that's set in the request.session dictionary as soon as a new user hits the web-app's landing page. The code is is simply:
temp_id = request.session.get('temp_id',None)
if not temp_id:
request.session['temp_id'] = get_temp_id()
So far so good.
Apart from saving a temp_id in request.session, another technique I could have used is setting a browser cookie explicitly for unauthenticated users like so:
if not request.session.exists(request.session.session_key):
request.session.create()
The concept I'd like to clarify is are these approaches equivalent?
I feel they are. My reasoning is: if a browser cookie is just a reference to a Session stored in the DB, then if cookies were turned off, matching a Session for that user would be impossible. So regardless of whichever approach I take, I'll be relying on the browser's ability to store a cookie.
Or in other words, both methods of allotting a temp_id to an unauthenticated user are, under the hood, quite similar. The only difference is that browser cookies are less secure than session variables (over HTTPS).
Can someone point out whether this line of thinking is correct? Or is my approach wrong? I'm essentially trying to ascertain which approach to take for reliably tracking unauthenticated users once they hit my app's landing page and move about.

Django close sessions if users moves another site or after browser close

How can I close sessions in Django if a user moves from my site to another or if he close the browser.
From both the question and comments, seems you would like to "close" session when user exits your site without any aid from JS. The answer is it depends how you define "close".
Root of the problem is that HTTP is stateless. Each request coming into the server is completely independent request without any relation to any other requests which means there cannot be any state. Since state is very useful we hack HTTP to add state by using sessions. The idea is that browser sends some identifier to some state stored on the server which allows the server to retrieve that state hence give some context to the request. The key there is that the browser is sending that data. In other words, if the browser at some point will stop sending requests, (e.g. user closes the tab), the server will never know that. Therefore if you define "close" session as removing session from the server, no that cannot be possible without some JS help.
If however all you are trying to achieve is log the user out when they exit your site, that can partially be done in Django with the use of SESSION_EXPIRE_AT_BROWSER_CLOSE setting. Here are additional docs about that. The idea here is that when Django sends the session cookie back to the browser, it will indicate to it that the session cookie should expire when the browser is closed. In that case when the browser is closed, the browser itself will invalidate the session hence the user will be forced to create new session on next visit. This is partial solution since the session will still be stored on the server and I believe only works when browser is completely closed (I dont think closing tabs works but not certain). To mitigate the issue of the server accumulating old sessions, Django provides a management command clearsessions which you should run on regular basis.

Session management in Apache JMeter

I would like to have a simple performance test which logs in multiple users, the sessions are created and do not expire until n minutes (where n is a parameter).
Is it possible to do this with JMeter? Do JMeter invalidate sessions at the end of the test?
In general, the expiration times of your cookies have to be set on the server side. The actual implementation will vary depending on your server side technology stack (see e.g. here for PHP's session docs), but it should be feasible, for example, to make a simple page that recognizes an "incoming" GET parameter value (from jMeter) for setting the cookie's expiration time when issuing the cookie.
On the client side (jMeter) the straight forward way for managing sessions is by using the CookieManager component. Each thread will have its own session cookie until the end of the test (or until the end of the iteration, if you configure the CookieManager accordingly).
If your test targets a typical web application that uses login forms for user logins, you could login each user (i.e. thread) e.g. by reading credentials from a username/password list in the form of a csv file (see CSV Data Set Config) and posting these credentials to the login form's action URL.
see httpd.conf (in Apache) for information on setting the duration of the session before timeout. This timeout is offset from the last request from a given session.

Auto logout using sessions in Django (outside views)

I'm trying to build a auto-logout function in a Django application.
Basically, with each request to the site I want to set the current timestamp in the session (if not set), and then checking that value with the current time. If the difference is too great, it should redirect to logout.
Is there a easy way to set the session on each request without adding a function to each of my views?
I know it's possible to use sessions outside views, but then I have to supply the session_key, and I'm not sure where I should get it from, or generate it myself.
I'm not sure what timestamp you are comparing with what here, or why.
The usual way to manage auto-logout is to simply set a short expiry on the session cookie, via the SESSION_COOKIE_AGE setting. If the cookie expires, the user will automatically be redirected to the login page if they try and access a page that requires authentication.