Java equivalent of session_start(), session_destroy(), and $_SESSION['username'] - java

In PHP when a user logs into her account, I do the following in order to remember the user as she navigates through the site:
session_start();
...
$_SESSION['username'] = $username;
On any other page that may require sensitive data, I check that $_SESSION['username'] is valid.
When a use logs out, I do the following
unset($_SESSION['username']
session_destroy();
How do I do the same thing in Java? I have a REST API which uses Jersey and EJB. In case the following is important, I am persisting with JPA, Hibernate, Glassfish, and mysql.
UPDATED FOR VERIFICATON:
Is this correct?
#Path("login")
public class UserLoginResource {
#EJB
private LoginDao loginDao;
#Context
HttpServletRequest request;
#POST
public Response login(JAXBElement<Login> jaxbLogin){
Login login = jaxbLogin.getValue();
loginDao.authenticateUserLogin(login);
HttpSession session = request.getSession();
session.setAttribute("username", login.getUsername());
return Response.ok().build();
}
}

Java is very different from php, so in java You will get session from only HttpRequest 's getSession() method, In php it is all time assumed, your code is run by some server(ie apache), In java, you will obtain it from ServletContainer(ie Apache Tomcat).
You do not have to start session in java unlike php, As long as you are in servlet container and giving request, for this client servlet container is responsible to start if there is not session for it
So for above actions:
reqest.getSession().setAttribute("udername","Elbek");
//later
reqest.getSession().removeAttribute("udername");
//destroy it
reqest.getSession().invalidate();
Here request is object of HttpRequest class
You may have a look to this HttpSession
I strongly recommend you to have a look java scopes
There is not this kind of thing in php, I wish there is, BUT there is NO
Here is how you get request object into your jersey action(method), ie by injecting #Context HttpServletRequest httpRequest
EDIT:
You do not create HttpRequest object by yourself, Instead you will get it from servlet container, Your server creates it from clients request and gives for your.

+elbek describes plain servlet situation - however, nowadays almost nobody writes plain servlet. It sickes soo much back then, that a lot of web frameworks evolved. There is a sh*tload of them, but good ones will utilize dependency injection techniques like spring
( for example , struts 2 ) and there are distinct scopes - application / session / request - containing plain java beans, which can in turn have authentication data.
J2EE also provides own authentication semantics with servlet container and JAAS - it also uses session tracking and useful when you need to access some backend resources like datasources or queues or EJBs - but most web application do not bother wth it.

Related

How to use Spring Websocket with the Spring Session custom HttpSession and without Stomp/SockJS?

In an server application I use bare websockets without the spring messaging layer and sockjs/stomp. I need my own messaging layer on top, but I want to use for example spring session to leverage the servlet HttpSession replacement to keep the http session alive which is beneath the websocket session, to prevent timeouts. The websocket is opened from a static HTML-page using JavaScript.
In the spring-framework documentation there is all the necessary information to setup bare websocket support with e.g. a basic BinaryWebSocketHandler or TextWebSocketHandler as well as how to
provide your own HandshakeInterceptor.
I've added spring session 1.1.0.RC1 with hazelcast for storing sessions and replacing the servlet container HttpSession implementation with the Session/ExpiringSession proivided by spring session. I just followed the given instructions to do this.
So far everything is fine, but as I'm serving a static HTML page from which I open the websocket using JavaScript without using spring security or any other mechanism to trigger a processing by the servlet container, no http session is intialized so far.
So the question is: How do I intitialze the custom HttpSession which is then stored in a the SessionRepository provided by spring session?
Note: I will provide an answer myself as I think I solved the issue for my case and it may be helpful for others facing a similar problem.
As can be seen from the spring-framework documentation, it is possible to add a custom HandshakeInterceptor. Spring session offers the
// example for reference:
org.springframework.session.web.socket.server.SessionRepositoryMessageInterceptor
which targets the spring messaging layer. It shows how to reset the timer of the HttpSession prior to sending a message within the method preSend(...) as well as how to optain the HttpSession from the request in the method beforeHandshake(...).
I implemented my own HandshakeInterceptor based on this with an almost identical beforeHandshake(...) method, but with one minor difference and of course leaving out the ChannelInterceptorAdapter stuff. The reset of the HttpSession time has to be done somewhere else, but that is out-of-scope.
Because in my case no HttpSession has been created so far, I changed the line obtaining the session from the request to look like this:
HttpSession session = servletRequest.getServletRequest().getSession(true);
Changing the boolean parameter from false to true in the method getSession(...). Now this call will trigger the creation of a new HttpSession (provided by spring session) if none is available so far.
This solution seems to do what is required in my case. Please correct me if I'm missing something or using anything the wrong way.

How to create, manage, associate a session in REST Jersey Web Application

A HTML5 UI is connected to the backend (REST Jersey to business logic to Hibernate and DB).
I need to create and maintain a session for each user login until the user logs out.
Can you please guide me on what technologies/ APIs can be used.
Does something need to be handled at the REST Client end also..
Using JAX-RS for RESTful web services is fairly straightforward. Here are the basics. You usually define one or more service classes/interfaces that define your REST operations via JAX-RS annotations, like this one:
#Path("/user")
public class UserService {
// ...
}
You can have your objects automagically injected in your methods via these annotations:
// Note: you could even inject this as a method parameter
#Context private HttpServletRequest request;
#POST
#Path("/authenticate")
public String authenticate(#FormParam("username") String username,
#FormParam("password") String password) {
// Implementation of your authentication logic
if (authenticate(username, password)) {
request.getSession(true);
// Set the session attributes as you wish
}
}
HTTP Sessions are accessible from the HTTP Request object via getSession() and getSession(boolean) as usual. Other useful annotations are #RequestParam, #CookieParam or even #MatrixParam among many others.
For further info you may want to read the RESTEasy User Guide or the Jersey User Guide since both are excellent resources.

what method is used by httpSession for session management in Java

I read lot of articles which says that there are different ways to manage the session like cookies, hidden form fields, url rewriting and jsessionId.
But when I do
HttpSession session = request.getSession();
Which method is actually used internally?
According to the servlet 2.4 specification:
Session tracking through HTTP cookies is the most used session
tracking mechanism and is required to be supported by all servlet
containers... To fulfill this requirement, Web containers commonly
support the URL rewriting mechanism.
Basically the session tracking (i.e. to keep the user interaction and sending the data ) can be maintained by 4 ways like HttpSession,cookies,hidden field and URL rewriting.
It depends on your requirement , which it needs to use.
If you are using HttpSession then you need to go for
HttpSession session = request.getSession(true);
As Cookies are client side.
Hidden fields are the form data you need to send to by request to servlet.
URL rewriting is used for sending the data using href or any link (usally GET method).
Session is used for secure and state full transaction.
Which method is actually used internally?
Its recommended to use HttpSession , if you want to track the request data over the application, until unless you invalidate that session. Jsessionid is a part of HttpSession. Internally Session is using unique Jsessionid for each session you are creating.
Hope it will help you.
The answer is that it doesn't depend on Java. It depends on the specific servlet container you are using and possibly the browser as well. If the brower won't accept cookies for example the container may be forced back to using URL rewriting.

How can I manage users' sessions when I use web services?

In case if user works with web application via web browser, the user's session is managed by application server. It takes care of sessions creation, validation, timeouts, disposings, etc.
And as far as I know there is no such mechanisms in the other case, if user works with app via remote client and uses SOAP web services.
So the question is, how can we manage users' sessions in case of web services and implement the same mechanisms of session management such as invalidation, prolongation, disposing?
Assuming you use JAX-WS and SOAP/HTTP it is possible to work with container managed security (and e.g. session cookies) as well. You just have to inject WebServiceContext in your service. It allows access to all HTTP environment variables:
#Resource
WebServiceContext wsContext;
A detailed example is available here. Of course, your clients must support this as well (if they are JAX-WS based it works). Nevertheless, a rule of thumb is that web services should not maintain any state at all, they should behave stateless. See this on SO.
Edit: You can access the ServletRequest by:
#WebMethod
public void foo() {
final MessageContext mc = this.wsContext.getMessageContext();
final ServletRequest sr = mc.get(MessageContext.SERVLET_REQUEST);
/* works if this is a HTTP(s) request */
if (sr != null && sr instanceof HttpServletRequest) {
final HttpServletRequest hsr = (HttpServletRequest) sr;
hsr.getSession(true);
/* ... */
} else {
/* do some exceptional stuff */
}
}
The session created above should behave in exactly the same way as a 'standard' web session. You must make sure that your clients understand that as well. They have to submit the session identifier (cookie) on each subsequent call.
I think you are talking about how to maintain web-services session(state-full web-services).
In this case following link can help you:
https://blogs.oracle.com/sujit/entry/ws_addressing_and_stateful_webservice
Web Service does not support session state for achieving high scalability, web service is designed stateless.
Session state handling is not a part of SOAP specification. The cookie stores a token which acts as session identifier. There are a number of ways to pass the session identifier: as an HTTP cookie, as a SOAP header, or as an element in the SOAP message body.
A SOAP header is transport independent, but it requires the SOAP client and service to agree on the format of the SOAP header, and it required that both the SOAP client and SOAP server implementations support SOAP headers. If you use the SOAP body to pass the session id, then it's up to the service (i.e., your application code) to re-establish the state on each call. Stateful processing can make cross-SOAP interoperability a bit more challenging, but it does work. Check into the capabilities of your SOAP implementation. source

Spring Session Management

I'm using Spring for my web app. I have used several SimpleFormControllers. I've created a session in the first SimpleFormController for the login page using:
HttpSession session = request.getSession(true);
How can I protect other SimpleFormControllers using Sessions, i.e. so that other controllers won't load if the user is not loged in.
Thank you
You probably want to use Spring Security.
It's flexible and allows restrictions based on roles.
Without it, you will need to manually check in every controller whether the user logged in or not. Or you'll have to "reinvent" a security framework by adding filter to the webapp.
If you only want to protect the operation of getting the session, you need to write a filter that wraps the original request and overrides the getSession methods. There you can check for login data using the original request's getSession().
BTW, getSession() is equivalent to getSession(true)
To protect the Controller from access outside of the intended Session, you may want to compare the Scoping rules you need with this clearly written Guide.
How to get Session Object In Spring MVC
The author gives an example of creating a Controller annotated with #Scope("session")

Categories