ColdFusion: When to define session variables? - session

When a user requests a page, is this when a session is started for that user? From what I can tell, a session is started as soon as you make a page request...
If this is the case, when do you create session variables? i.e. username, password, preferences, etc... just any time?

Yes the session scope for the user is setup on the first request. However it depends on your preference as to when you want to set various flags and values. You probably don't want to put password in the session scope though.
What I like to do is put user specific values in a user struct. So on request start I'd check for the variable and setup if it doesn't exist. For example...
<cfif not structkeyexists(session, "user")>
<cfset session.user = {
authorized = false
, admin = false
, username = ''
, accountid = ''
<!--- etc --->
} />
</cfif>
When the user logs in you can then fill in the appropriate values and set session.user.authorized = true
When the user logs out the nice thing about this approach is you can just delete the users struct.
<cfset structdelete(session, "user") />
Then on the next page the check will be made again for the user struct and created if it doesn't exist.

The basics of configuring and using session variables are explained here.
A session is basically a logical relationship between a client and an application, so session variables are available from the client's first request to your application, and the session is typically persisted across requests using cookies which uniquely identify the session, although this can be also done by passing the identifiers in the url. It's worth paying attention to your session timeout settings, for example you may want to provide a shorter timeout to bots/crawlers which don't set cookies and will therefore initiate a new session for each page request (more details on this).

Related

Shiro handling user attributes with principals or as session attribute(s)

I'm using Shiro in a JSF application and look for guidance on how to handle user attributes like: Id (from the database), email etc. as part of the information held by the Shiro Subject.
Having read the Shiro manual, it seems to me that there's no reason for me to have a SessionScoped bean to hold the user information, as I already have the Subject. The question is how to best store the user information that is not part of the Subject by default.
I've seen different examples where some use Principals and other put a separate custom made User object in the current Session like:
User user = userDAO.findByName(user.getUsername());
subject.getSession().setAttribute("user", user);
It would be elegant to get hold of - for example - the user id like this:
userId = subject.getUserId();
or email:
email = subject.getEmail();
But I guess that is not likely to be possible - so my question is: What is best practice for this? And I'd also like to ask: is there any good reason to keep a separate SessionScoped bean alive for the purpose of user sessions?
For my understanding the principal is the pure object for identification, authentication or remember me function. So put additional info to session (setAttribute).
When a user logs in, load the data and put it to the session with setAttribute. Or when a user comes back with remember me, use the principal to identify the user, and load the necessary things back to session.
It's up to you to decide how much data you want to hold in session for every user. If you want to keep memory consumption small on server, just store data to identify the user (maybe it's already in the principal) and load the data when needed in every function. This way is typically more cpu and database heavy.
If you don't have that much users, just put it to session and make your life easier.
// Do login
Subject currentUser = SecurityUtils.getSubject();
UsernamePasswordToken token = new UsernamePasswordToken(email, password);
currentUser.login(token);
// load attribues
Long uuid = (Long) currentUser.getPrincipal();
Long ucid = // load other ids;
String email = // maybe load email and other stuff
// set attributes
currentUser.getSession().setAttribute("UUID", uuid);
currentUser.getSession().setAttribute("UCID", ucid);
currentUser.getSession().setAttribute("EMAIL", email);
...
// some function
public void doSomething() {
Long ucid = (Long)SecurityUtils.getSubject().getSession().getAttribute("UCID");
// do something
}
In my example, my principal is just the Unique User Id. That's enough to identify every user. Some Users are also customers, so i save this id too (saves me database access everytime).
You can also save more stuff like email or whatever you need.
I duplicated the UUID from the principal to the session, just for comfort. I don't like mixing up principal casts and session access. This keeps my code clean.

Storing oAuth state token in Flask session

A couple of tutorials on oAuth use the Flask session to store state parameters and access tokens in the flask session. (Brendan McCollam's very useful presentation from Pycon is an example)
I understand that Flask stores the session in cookies on the client side and that they are fairly easy to expose (see Michael Grinberg's how-secure-is-the-flask-user-session). I tried this myself and was able to see the token the expiration, etc.
Is it correct to store the state and tokens in the flask session or they should be stored somewhere else?
Code example:
#app.route('/login', methods=['GET'])
def login():
provider = OAuth2Session(
client_id=CONFIG['client_id'],
scope=CONFIG['scope'],
redirect_uri=CONFIG['redirect_uri'])
url, state = provider.authorization_url(CONFIG['auth_url'])
session['oauth2_state'] = state
return redirect(url)
#app.route('/callback', methods=['GET'])
def callback():
provider = OAuth2Session(CONFIG['client_id'],
redirect_uri=CONFIG['redirect_uri'],
state=session['oauth2_state'])
token_response = provider.fetch_token(
token_url=CONFIG['token_url'],
client_secret=CONFIG['client_secret'],
authorization_response=request.url)
session['access_token'] = token_response['access_token']
session['access_token_expires'] = token_response['expires_at']
transfers = provider.get('https://transfer.api.globusonline.org/v0.10/task_list?limit=1')
return redirect(url_for('index'))
#app.route('/')
def index():
if 'access_token' not in session:
return redirect(url_for('login'))
transfers = requests.get('https://transfer.api.globusonline.org/v0.10/task_list?limit=1',
headers={'Authorization': 'Bearer ' + session['access_token']})
return render_template('index.html.jinja2',
transfers=transfers.json())
I think some tutorials over-simplify in order to show simpler code. A good rule of thumb is to use session cookies only for information that MUST be known by your application and your user's browser, and is not private. That normally translates into a Session ID and possibly other non sensitive information such as a language selection.
Applying that rule of thumb, I'd suggest the next to each of the tokens:
Authorization Token: this data is by definition known to both the user and the application, so it shouldn't be a security concern to expose it in the cookie. However, there really is no need to keep this token once you're given an access code, so I advice against keeping it locally or in your cookies.
Access Code: this data must be considered secret, and must only be known by your application and the provider. There is no reason to make it know to any other parties, including the user, therefore it should NOT be included in cookies. If you need to store it, keep it locally in your servers (perhaps in your database, referencing your users session ID).
CSRF State Token: this data is ideally included as a hidden form field and validated against a server side variable, so cookies seem like an unnecessary complication. But I wouldn't be concerned about this data being in a cookie, since it's part of the response anyways.
Keep in mind there are extensions such as flask-sessions, with which practically the same code uses server side variables instead of cookie variables.

Session in Coldfusion

Since the system I am using has Login and Logout feature, I am inside Session when I Logs in to the system. I am new to Session, my question is whatever variable and its value I have defined in any coldfusion page, would I be able to use it on any page?
For example, while going through the code of my system, I came across the following line one each and every CFML page:
<cfparam name="INPUTID" default="0">
and then later on somewhere in the page, I have seen this variable getting used like #INPUTId# .
Please clarify
To answer the question "whatever variable and its value I have defined in any coldfusion page, would I be able to use it on any page" ... that depends.
If you set a session variable e.g. <cfset session.foo = "bar" > then you can call #session.foo# on any page since it will be stored in the user's session.
However if you simply set a value, e.g. <cfset foo="bar" > then it will end up in the 'variables' scope and only available within that page, or request. (on that note, CF has a specific "request" scope, e.g. request.foo, which is for this purpose, available throughout any code that comes after the place where the value is set, in the same request or page view).
So, if you want to set values that can be used on other pages, use the session. But be careful, you will also need to use cfparam to set defaults, or use structKeyExists() to check for the value, before trying to call it from the user's session, since the value may not exist unless it has been set already. Otherwise, for values used in the same page, use the 'request' scope, or see the CF docs for other scopes e.g. variables, local, etc.

How do I set the session param for multiple namespaces?

If I am handling authentication manually, and am setting session like so:
session[:user_id] = authenticated.user.id
user_id does not show up in my session hash when viewed from another namespace. In this instance I have a namespace :api, and session doesn't show up at api/show/current. How do I set the session hash to be viewed in both namespaces?
The session is completely independent from namespaces, maybe there is something else wrong with your app?
where do you set the user_id?
maybe providing more code helps

How to set a value into a cookie or session in Drupal

I am working on a friend reference function, so I pass the user id through the url like this:
www.example.com?fid=22
I need to set this as a session or cookie with access to all modules in Drupal 6.
If i set the session it returns for the particular module. Setting the cookie is not working at all.
$user->new_property works only on the particular page where it is set, if I move to another page there is no new_property in $user variable object list.
If you want to save a variable in a users session, you can in Drupal (PHP) use the super global varaible $_SESSION.
$_SESSION['fid'] = $_GET['fid'];
The above code is an example of how this could be done.
Since you are getting the info from the URL the user can change it as his whim. So be careful what you use such data for and never trust it blindly. It could become anything, as the user always freely can alter the url any way he want.

Resources