Yii Session Variables and Memcached - yii

I am building a forum website using Yii PHP framework . I am also using Memcached for session maintenance and for storing some data objects .
For every user request I have to get some user information to check some thing ( to check if he is member of the particular group or not and also other checks )
So the two approaches what I am planing are
1) Don't store any thing in the session other than the user id and after user session established get the object from memcached and check it - Here one user object and two calls to memcached server
( One is session call and other to get user object)
2) Store all the required user information in the session using setState method . After successful login user gets the information from session object and checks it . Here there are two user objects one in memcached and one in user session ( of course this again stores in memcached) . But I feel when the session establishes with one call we get all the required details of the user ( really is this the case ?)
Not sure what is the best approach . Thanks for your help on this.

From a perfomance perspective it makes no difference, because you also save the sessions in memached (that's at least what you said). So it's most logical to use the session for this kind of information. Otherwhise you'd have to create and store unique cache keys for each user - which kind of reinvents what the session already does for you.

Related

how to restrict multiple login of the user

We want to restrict users to multiple login sessions at a time, there should be a single active login session.
Users should be allowed to be logged in to one application from only one browser at a time. When the user log in the server should check his current active sessions to the same application from other browsers. If there is then log out from everywhere else and keep only the newest session.
ASP.Net Core's default authentication cookie middleware has a handy hook (via the CookieAuthenticationOptions.SessionStore property and ITicketStore interface) to allow you to implement custom backend storage for the cookie payload (claims). The end result is a protected cookie containing just basic AuthenticationProperties values and the session ID as a claim and everything else stored in the DB, keyed off the user ID and session ID etc.
With this in place you can automatically invalidate any existing session for a given user account (the ID of which being an indexed field/property in your backing store) by deleting or otherwise expiring any other sessions.
This also has the advantage of allowing you to invalidate sessions based on other circumstances like a password or other security settings changing.
You could also implement something to trigger back channel logout calls to client applications if you also track which clients they've signed into in the given session in the backing store too.
Note: The SessionStore property is a singleton concurrently accessed instance so ensure your implementation handles database connectivity appropriately if you go this route. Note also that the wireup is best done via an implementation of IPostConfigureOptions<CookieAuthenticationOptions>
Change the security stamp SecurityStamp.AbpUsers when the user logins.
The previous logins becomes invalid.
https://github.com/aspnetboilerplate/aspnetboilerplate/issues/4821#issuecomment-524732321

Cookie Authentication for Client - is session store needed?

I am creating an application and I am looking for a solution for user authentication (checking if the user is logged in, basically). I am reading online and it seems that many people recommend using a session store/table in your db (store roles, views etc..) vs. just storing the cookie id in the DB in that users column. My question is, what is the difference between storing this data in a "session" store, which is basically just another table and storing this data in your database alongside the other user data (username, passwordHash etc..). I understand that this is useful for data that may change when the user logs in and out again, but are there any advantages to having a session store if my applications state stays consistent across log ins. Thanks.
You need a way to store user data between HTTP requests and sessions helps you to do so.When a user visits our site, it creates a new session for the user and assigns them a cookie. Next time the user comes to the site , the cookie is checked and the session id which is stored in the cookie is retrieved and searched in the session store .Session store is a place where you store all your data regarding your session.So using a session store automates this method and it eases your work.So whenever someone pings your server it will add the session id of the user in your database. I will recommend foe you to look into JWT which is also a interesting way to do authentication.

Is asp.net core session not user specific?

When i was working with classic ASP.NET or even with old web forms the HttpContext.Current.Session was User specific. So when user makes the request he receives the session cookie and then onward that session belongs to that user only. So two different users can have session key with the same name in their respective session.
I am reading the documenation on session in ASP.NET Core and looks like it has the same concept as old asp.net however certains notes in the documentation is confusing.
here it says
Session storage relies on a cookie-based identifier to access data
related to a given browser session (a series of requests from a
particular browser and machine). You can’t necessarily assume that a
session is restricted to a single user, so be careful what kind of
information you store in Session. It is a good place to store
application state that is specific to a particular session but which
doesn’t need to be persisted permanently
also here it says
Session is non-locking, so if two requests both attempt to modify the
contents of session, the last one will win. Further, Session is
implemented as a coherent session, which means that all of the
contents are stored together. This means that if two requests are
modifying different parts of the session (different keys), they may
still impact each other.
so lets say i have User1 logged in and upon some action i set
`Session.SetInt32("key1", 123)`
now User2 logs in from some other machine and upon some action i set
`Session.SetInt32("key1", 999)`
Question 1
Will this overwrite User1's key?
Also note here says
ASP.NET ships with several implementations of IDistributedCache,
including an in-memory option (to be used during development and
testing only)
Question 2
What are the other implementation of IDistributedCache that i can use in production?
For Question 1.
No, one user modifying a session key will not overwrite a different user's key. The session is unique to each visitor/user because of the .AspNetCore.Session cookie that is created.
All of the Session.Set calls get stored per that unique identifier.
#1
Session isn't tied to a user because session is only identified by it's session key, so if someone gets possession of the session key/cookie, he can access it.
Asp.Net Core Identity has its own cookie (if you are using cookie authentication) and Session middle ware use its own cookie too.
Naturally, you can also use Sessions without a user. Take Google.com for example. When you first visit Google, it shows you policies and set a session cookie. All settings you do (i.e. maturity filter), will be saved in the session which gets accessed each time you perform a search.
This all without being logged in, so there is no user at all.
#2
Open Source is your friend:
https://github.com/aspnet/Caching/tree/dev/src
Redis and SqlServer are the default distributed caches, with InMemory being for development / single-node only. There also may be other third party libraries which add support.

How to implement "remember me" using ServiceStack authentication

I am trying to implement a Remember me feature in a ServiceStack-based project. I don't want to use Basic Authentication because it requires storing password in clear text in a browser cookie, so I need to come up with an alternative approach that will be easy to maintain and customized to my existing database.
I understand that ServiceStack's own support for Remember me is based on caching the IAuthSession instance in the server-side cache, which by default is an in-memory data structure that is wiped out when the website restarts (not good). Alternatively, the cache can also be based on Redis or Memcached, which is better (cached data survives website restarts) but adds more moving parts to the picture than I care to add to it.
Instead, I would like to implement the this functionality using my own database:
Table Users:
UserID (auto-incremented identity)
Username
Password
Email
Name
etc...
Table Sessions:
SessionID (auto-incremented identity)
UserID (FK to Users)
StartDateTime
EndDateTime
SessionKey (GUID)
The way I see things working is this:
On login request, AuthService creates an empty instance of my UserAuthSession class (implements IAuthSession) and calls my custom credentials provider's TryAuthenticate method, which authenticates the user against the Users table, populates UserAuthSession with relevant user data and inserts a new record into the Session table.
Then the auth session is cached in the in-memory cache and ServiceStack session cookies (ss-id and ss-pid) are created and sent to the browser.
If the user checks Remember me then additionally my custom credential provider's OnAuthenticate method creates a permanent login cookie that contains the user's username and the auto-generated Sessions.SessionKey. This cookie will help us track the user on subsequent visits even if the auth session is no longer in the cache.
Now, suppose the site has been restarted, the cache is gone, so when our user returns to the site his auth session is nowhere to be found. The current logic in AuthenticateAttribute redirects the user back to the login screen, but instead I want to change the flow so as to to try to identify the user based on my custom login cookie, i.e.:
look up the latest Sessions record for the username extracted from the login cookie
check if its SessionKey matches the key in the login cookie
if they match, then:
read the user's data from the Users table
create my custom auth session instance, fill it with user data and cache it (just like at initial login)
insert a new Sessions record with a new SessionKey value
send back to the browser a new login cookie to be used next time
if the keys don't match then send the user back to the login screen.
Does the above logic make sense?
Has anyone already implemented anything similar using ServiceStack?
If I were to proceed with this approach, what is the best course of action that doesn't involve creating my own custom version of AuthenticateAttribute? I.e. which hooks can I use to build this using the existing ServiceStack code?
This is already built for you! Just use the OrmLiteCacheClient.
In your AppHost.Configure() method, add this:
var dbCacheClient = new OrmLiteCacheClient {
DbFactory = container.Resolve<IDbConnectionFactory>()
};
dbCacheClient.InitSchema();
container.Register<ICacheClient>(dbCacheClient);
I am not sure when this particular feature was added, perhaps it wasn't available when you originally asked. It's available in v4.0.31 at least.

ExtJs:How to get Session variable

In my Java web application,when a user gets logged in,i store the user name and other details in session as follows,
session.setAttribute("userName",username);
I am using ExtJs4 for UI.How to get the session variables in extJs?
Thanks
I can second #Geronimo approach. You need to get user Id and/or permissions when you authenticate the user. However...
You can't rely just on the username/permissions that you store somewhere in your JS code because it can't be easily spoofed. If you present user with some information that can be different for different levels of access you still need to do server side validation of the user identity.
You can't get session variables off the server web container using javascript only.
I do the same thing (storing userId as a session variable in java). I use Ext.Request to perform an Ajax request to a java servlet to get it (along with other data about the user like permission settings for the webapp to enable or disable features they wouldn't be able to use).
EDIT:
I second sha's answer also, the only reason I pass the authentication information back to the client is for cosmetic reasons - so that user doesn't think he can use a feature in javascript that would be denied by my server side authentication. If he were to spoof the userId or permissions and try to use the feature, the real authentication on the server side would stop him.
I understand that the question has been asked for a long time ago, but despite the large number of views and the absence of an plain answer, I decided to offer this answer:
Assume that the session variable is registered like /index.php?PHPSESSID=9ebca8bd62c830d3e79272b4f585ff8f
In this case, you can get the variable PHPSESSID through JS object "location" and transform it through Ext.Object.fromQueryString()
So:
console.log( Ext.Object.fromQueryString( location.search ) );
will prepare PHPSESSID variable for your needs.