How do I guarantee a single session? - java

I need to prevent the situation where either
1. Two different JSESSIONID's exist for the same user account or,
2. Two tabs of a single browser reference the same JSESSIONID.
Any suggestions? If an existing session is detected, the user can either:
a) Quit the second attempt
b) Kill the existing session (an assassin!) and start a new session.
The preference is for a sever-side solution. That is, I don't want to depend on user's turning cookies off which forces the JSESSIONID into the URL.

Embeding a hidden input field with a unique token in each page sounds like the only solution for a problem like this. This seems to be like the only way to tell one tab from another, even if they're the exact same URL.
Keep in mind though, that what you're doing seems like pretty bad practice; any particular reason to prevent the user from using more than one tab?

Part 1 could be done using a singleton pattern that checks current sessionid for the user against a map of user-SID.
Part 2, which could be understood in transactional webapps where you need to ensure that the user reads the correct info (instead of having a one tab with old values and one tab with newer values- scenario)... it could use the same sessionid map, injecting it in the dom and validate it using javascript.
EDIT. Part 2 validation could be done better in a filter against the map of client-sessionid. And a correct definition of the object guarantees that a true unique singleton instance exists.

Related

Best approach to handle login and authorizations in Vaadin Flow?

I'm using Vaadin Flow to develop a web app with Java. I would like to know the best way to handle login and authorization. I've been giving this a thought and I'm not sure the best way to do this.
I have a login view and a main app view with a content holder for nested layouts.
How do I check that the user is logged in and what permissions does it have to see or not see some part of the app? I've read about BeforeEnterEvent and ReRouting but it's still not very clear.
Do I have to use BeforeEnterEvent for each class I have? Do I have to create a class with user parameters like a boolean to check if it's logged in and a string for the kind of authorization it has? And where do I create or save this instance?
Is there a simple way to do this? Like to start with an empty layout and to start that with the login screen, then the login screen decides to swap for the main app view? And how do I prevent the user to type the address of the main view in the bar and access parts it shouldn't access like: /app/adminsettings
I'm sure this is way simpler but I think I have my head overloaded by now, thanks anyone in advance!
As always, there are no silver bullets. The "best way" always depends on
the requirements and your options range from Basic Auth to some external
OIDC provider.
There are already some tutorials out there with the most prominent from
Vaadin itself about Spring
Security
(which in a previous iteration had a flaw that compromised security,
which of course shows again, that security is no product but a process
and demands constant validation).
So I want to strategize here a bit more about the problems you are
facing and some things to consider:
Be aware, that when you use a security library, that has or allows for
an web path centric approach, that you should only use it for the
root and to open up paths to resources etc. The history API may only
look like you are fetching URLs from a server or web sockets may be
used under the hood and suddenly those rules no longer apply.
If you are using the annotation based way to add routes, you end up
with all the routes, that are there, for your UI per user. So it's
good to familiarize yourself with how to register routes
dynamically.
E.g. only add the routes the user is allowed on login; this usually
also has implications for the UI (e.g. menu entries).
There usually is some initial "declarative" security part (can the
user even enter this view; this usually means some simple role check).
A good place to check for this is a BeforeEnterListener added to the
UI; it will be called before any navigation to any view. See
navigation
livecyle
The next entry point(s) to guard are the BeforeEnterEvent you can
listen on in the view itself and/or maybe it implements
HasUrlParameter. If you take params from the "request" or the path,
the usually mean further checks (e.g. is the acting user allowed to
edit the blog entry with the id 42). See routing and URL
parameters
and also navigation
livecyle.
Deeper into the application you end up with something more imperative,
that libraries often make appear declarative, because they generate
some code for you from some annotation (e.g. some AOP that generates
the code around your #SecurityCheck('${u.owner}==${currentUser}')
void save(User u) method, that checks for the role and whether the
User u belongs to the acting user).
Be very certain, that your IoC system/library/... sees those
annotation and generates the code accordingly. Only #Route e.g.
will get the full DI treatment with Vaadin+Spring - for the rest it's
your job that the DI-framework can do it's job (a NPE from a missed
#Autowired is spotted very quickly, but a security check not being
called, is not). The obvious way around this, is to be imperative and
write the code yourself instead of relying on it to be there.
If you have an anonymous system and then some login, make sure to send
users over to a fresh session (and therefor UI); not only does it
prevent a session fixation attack, but it also allows you put all your
route-setup and UI derivations according to security in one place at
the beginning of the UI creation. If you have state you want to carry
over, make it part of the URL, that your successful login process
sends them back to or park in the browsers local storage.

prototype spring bean with global static variable

I have a question that i have a spring-MVC based project. In which there is a class containing all static variable which is accessible by all users. All Bean are singleton, which creates problems when multiple users access application: the last user to modify the static variable at the same time a previous user is performing their task. So after last user comes the previous user's data, which overlaps with the data from the last user which creates conflict in the report. I also user prototype bean, but I didn't find any solutions because of the static variable. So anyone have solution related to this problem? Thanks.
First: use db, and save data there. If you restart your program all changes by users will be discarded.
Second: you tagged it corectly, since it is a question of concurency: make synchronization block, keep version, upon entrering synchronization block check if change is changing the latest version or previous one:
if you change latest commit - ok, if it's not: handle exception.
third: this smells bad desing. Are you sure you need all users MODIFY one parameter? Do you keep records of who and how modified it? Singletons are primarly used as read-only immutable objects that share information across whole application.
And forth: please, do not use static mutable variables. Seriously.

Is there a way to do input validation in Java as well as with JavaScript using a common code base?

for a java web application, normally we need to do validation at front end using javascript and then on the backend using java, some java validation tools like hibernate validator can be used on the backend side, while on client side there're jquery form vaildation,
but the thing is, is there a simpler way to combine the two? such as, when using springmvc with hiberate validator, the front end valiation will be there automatically?
thx
Don't forget, there are two very different forms of validation.
First, validation to ensure that the user makes sensible entries. Consider the usual password/confirm-password system. The only significance of the confirm-password field is keep the user from accidentally inconveniencing himself.
Similarly, things like checking valid email addresses, required fields, and so forth -- they're just there to make sure the user is entering what he really means.
Second, there is validate to ensure that only legal changes are made to the system. One user cannot change data belonging to another user, employees cannot give themselves raises, and so forth.
Validations of the first kind need only be done in Javascript. The user can defeat them, if he wishes, but he hurts no one but himself.
Validations of the second kind must be done on the back-end. Usually, but not always, there isn't any need to err out gracefully. If the user has weaseled past the UI, or reverse-engineered the AJAX, you don't have to be polite. Just return a 500 and log the intrusion.
There are a few overlaps. For example, if user is creating a (supposedly) unique user-name, that uniqueness check can fail at the very last second, after passing all the Javascript checks, because someone else took a previously unused name.
But that's the exception, not the rule. Most back-end validation is just very thin security or security-like checks, very different from what's done on the front.

How do we effectively prevent concurrent use of a web-application in one session?

We have built a Spring MVC web application that is heavily relying on the user to do things in a certain order, and while it prevents users from circumventing this (without trying very hard) in the usual case (by not offering options to “go to places” you’re not supposed to at the given moment), we’re having some problems when people open another instance of the application in a new tab or browser window.
Since the application stores the domain model in the user’s session, using the program in another window can potentially mess up the model’s data, we’ve already implemented a page-ID mechanism that validates the user using the program in the correct order and not using the browser navigation, but we’re still facing problems when things like resetting the program (this is a feature, redirecting the user to the home screen and clearing the domain model) happen in one window and the user then tries to do something relying on the domain model to be filled with valid data in another window (leading to a NullPointerException quite quickly).
Storing some user details (like id, name, email) in a session might be ok, but storing the user's state (or any data that changes often and/or significantly affects other things in your app) doesn't sound like a good idea.
Hopefully one of the following approaches will fit you:
Don't save state in the session - load it from the database whenever you need it (in your case, whenever the user tries to access one of the steps that should be done in order). If you use caching, this shouldn't have major performance consequences.
Don't save state in the database, only in the session - works for limited cases (for instance, ordering airline tickets) where you can postpone committing your domain object until the process has finished.
Use Ajax for multi-step processes and don't save state at all (except implicitly in the browser). This requires putting all the steps into one page and ajaxifying some of your code.
Regardless, if someone logs in and tries to go to step 3, they shouldn't get an exception thrown at them, but that's a different story.
If I were you, I'd let user to wander around other parts of the website - the parts that don't interfere with your wizard process. However, once they try to restart it - check if there's PageID in session, and remind them they have not finished what they started, and ask if they would like to cancel/restart or continue on from where they left it.
In case anyone ever reads this question again:
Instead of the HttpSession keeping exactly one copy of the domain model it now holds a collection and we transport a reference to a single one of the models through the requests/responses so we can get the right model to work on in our controllers and views.

How to use a binding framework efficiently

I've been using binding frameworks for a while now and i'd like to know how you handle this cases.
You have a newspaper that has some attributes like
(String) headline
(Boolean) published
(Date) publishmentDate
On your view, you have a list of newspapers, than can be edited all in the same time. This means you can change the headlines of all newspapes, or all their state "published" in a single request.
The matter is that, as we are using a binding framework, you will edit the newspapers' data a bit like if you were editing the data in a DB... binding each value to a field, independently from each others.
But... what i'd like to do is that when i publish a newspaper, the publishmentDate is updated to the current date.
I could for sure put a publishmentDate field on the form, or even a hidden field setted to the current date... But this is neither clean or secure.
I think it's better to have an action publish() that will set the flag to true, but also update the publishmentDate (and other logic if needed...)
I just wonder how do you handle that?
I've seen and thought about different approaches:
1) Sometimes we bind the new parameters to an existing persistent ORM entity.
This means we retrieve the entity just before the binding, so that we bind the values to an existing, "already filled" entity object. This is sometimes called "hydrating the entity"
Thus the only way to know if you have to launch a "publish action" is by comparing the old field with the new one, so that you know if it was edited and in which direction (false->true = publish)
It's possible to use an ORM listener, (like #PostLoad, a Hibernate Interceptor/EventListener or anything else) so that you keep these "before binding" values you need.
This works nice but it's quite "weird" to launch a publish action on the vehicle, while the binding already set the published flag to true.
2) It's possible to do nearly the same thing but to use another flag... for exemple a flag that represents the user wish to publish a newspaper.
Thus you don't have to compare with the previous value, you just check if the user wish to publish a newspaper and then launch the action... (and the real published flag was still = false when you launched the action this time...)
The matter is that as you are using a binding framework, you want the published checkbox to be checked on your view for newspapers that have already been published.
So if the attribute for binding is now published_wish, you'll have to set it a value or all your checkboxes will always be unchecked...
This means that you'll have, before showing the view, do something like published_wish = published
Most times the wish flag will not be persisted, but i've seen some cases where the "wish" MUST BE persisted, thus no need to do published_wish = published
3) Use an empty non persisted entity for the binding, then recopy the values of this non persisted entity to the real persisted object.
So when you recopy the values from one object to the other, you can launch any action you want, customize everything...
But it's a bit heavy to have to recopy all these parameters...
There may be other ways to do...
How would you do that? So that it doesn't just work well, but it is also elegant, maintenable... i don't see any perfect solution here
I agree with you and I would also use a Publish button in this case (with possibly an "Unpublish" button as well), allowing the user to select multiple articles and publish them all at once. I wouldn't allow the user to edit the Published checkbox and the publication date directly.
The question did not open me very well, but if the case is that you want to elegantly save publish dates, why don't you leave database to do it for you. On Mysql you have example here where the database saves the lastChanged data automatically for user.
Also database triggers may make sence for you. At least I see automatical exact database queries better solution than a bunch of hacks inside the code making those things.
I do hope these answered your question or even the right question in mind.

Categories

Resources