Servlet Session - switch from URL Rewriting to Cookie - java

Situation: I have a "dumb" Javascript frontend that can contact some kind of SSO middleware (MW). The MW can obtain sessions by issuing requests that contain authentication credentials (username, password). I.e. the session will be created for a certain user.
My frontend needs to "restart" the session to gain the user's permissions to the target system. For that i need a valid session cookie.
The target system is not under my control (could be a more or less public WFS, WMS, etc.), so i cannot add any SSO mechanism to it.
Question: Is it possible to "steal" a Session forging a request which URL contains a valid session ID in the jsessionid parameter?
Goal : Issue such a request to a Servlet and make it respond with a Set-Cookie header that contains the same id. That way the frontend joins the session and may do whatever the user, which was used to create the session, is able to do.

Your best bet is a shared datasource (RDBMS?) where the shared information is stored with some long, auto-generated, unique identifier as key (java.util.UUID maybe?) and then pass this key around.

Related

Spring Security returning the same token each time

We're using spring security (Authorisation and Resource server ) in our project.
client sends a token request (/oauth/token) with the oauth2 parameters.
spring security app creates a token for the user and respond to the client with the access_token, refresh_token, custom user object (name, organisation, email etc) and authorities (Roles).
Client adds additional roles (say ROLE_CLIENT, ROLE_USER).
spring application will store the above roles for the given user.
Next time when client sends a token request, spring security returns the previously created token (not expired yet) along with the user and authority information. This authority information is not having the latest roles (added in step4).
Here spring security always using the existing token (as it is not expired) and returning the valid token. Is this the expected behaviour even though the user object is being modified?
It sounds like you need to revoke the access token when the users roles change if you want the next request to get a new access token with the new roles and not return an existing token with existing roles if it's still valid.
At the point where you update the users roles you'd likely want to revoke the token.
I haven't personally tested this but I found a guide for it here https://www.baeldung.com/spring-security-oauth-revoke-tokens so your milage may vary.
I want to add that this does not sound like the normal OAuth2 process and you may be breaking a few conventions here which might bite you later. That said, you don't have to follow a standard if you're confident in your proposed solution.
Edit: To clarify the users roles and access is normally part of a resource and not part of the token exchange. For example you have a normal OAuth2 request which generates a token which you can exchange for an access token, as you've laid out in steps 1 and 2. Then you'd normally take that access token and request user access information from a resource such as "userinfo" service or something similar.
Your security service can also be a resource server but the two steps should be seen as different. Then when you want to modify the users roles you do this again through a resource. This means the next time you invoke the resource it'll have the up to date information without needing to authenticate the user again.

Passing parameter form jsp to servlet to jsp and then to another servlet

Is there a way to pass a parameter to a servlet going through another jsp and then to another servlet
like
jsp---parameter--->servlet(using getParameter())---parameter--->jsp---parameter--->servlet(is there a way to get the parameter here)
The program that am working on is to pass the username.
Looks like you want to use HTTPsession.
Provides a way to identify a user across more than one page request or visit to a Web site and to store information about that user.
The servlet container uses this interface to create a session between an HTTP client and an HTTP server. The session persists for a specified time period, across more than one connection or page request from the user. A session usually corresponds to one user, who may visit a site many times. The server can maintain a session in many ways such as using cookies or rewriting URLs.
Setting
Session session = request.getSession();
session.setAttribute("username", username);
getting it back
String username = (String)session.getAttribute("username");

Confusion about how java web session handeling works. Demystifying Cookies and Header differences using servlet api and HttpSession object

I am learning Spring security and Spring MVC, but I realized I needed to learn jsp Servlets first and general web programming in a java environment.
I have confusions surrounding the HttpServletRequest and HttpServletResponse objects and how they can be used to add headers to the request and response objects and how they relate to sessions.
As far as I understand, a cookie is a type of header just like Content-type and Accept.
The java servlet api just makes it easy to work with the header by using methods specific to the context in which the header is being used. For example:
response.setContentType(String mimeType)
response.setContentLength(int lengthInBytes)
My confusion starts here.. Cookie is not a String or int, its a object:
response.addCookie(Cookie cookie)
response.getCookies()
Since a cookie is a type of header, can't I just use something like this:
String cookieVal = response.getHeader("cookie")
I'm having difficulty understanding session management and how it relates to the HttpServletRequest and HttpServletResponse API.. What is the HttpSession object for?
HttpSession.getAttribute() // What is this getting??
HttpSession.setAttribute("Bla Bla", "valuetoset") // What is this setting?
You can read the RFC describing Cookies and the related headers, Set-Cookie and Cookie to understand what they are.
You can go through Chapter 7 of the Servlet Specification if you want to understand in detail how Cookies and Sessions are related.
You first need to understand that HTTP is a stateless protocol. This means that each request that a client makes has no relation to any previous or future requests. However, as users, we very much want some state when interacting with a web application. A bank application, for example, only wants you to be able to see and manage your transactions. A music streaming website might want to recommend some good beats based on what you've already heard.
To achieve this, the Cookie and Session concepts were introduced. Cookies are key-value pairs, but with a specific format (see the links). Sessions are server-side entities that store information (in memory or persisted) that spans multiple requests/responses between the server and the client.
The Servlet HTTP session uses a cookie with the name JSESSIONID and a value that identifies the session.
The Servlet container keeps a map (YMMV) of HttpSession objects and these identifiers. When a client first makes a request, the server creates an HttpSession object with a unique identifier and stores it in its map. It then adds a Set-Cookie header in the response. It sets the cookie's name to JSESSIONID and its value to the identifier it just created.
This is the most basic Cookie that a server uses. You can set any number of them with any information you wish. The Servlet API makes that a little simpler for you with the HttpServletResponse#addCookie(Cookie) method but you could do it yourself with the HttpServletResponse#addHeader(String, String) method.
The client receives these cookies and can store them somewhere, typically in a text file. When sending a new request to the server, it can use that cookie in the request's Cookie header to notify the server that it might have done a previous request.
When the Servlet container receives the request, it extracts the Cookie header value and tries to retrieve an HttpSession object from its map by using the key in the JSESSIONID cookie. This HttpSession object is then attached to the HttpServletRequest object that the Servlet container creates and passes to your Servlet. You can use the setAttribute(String, Object) and getAttribute(String) methods to manage state.
You are correct that cookies are managed using headers. There are TWO cookie management related headers: Cookie and Set-Cookie.
Cookie header is sent by the user agent (browser) and will be available in your HttpServletRequest object and the Set-Cookie header is appended to your HttpServletResponse object when you use methods such as addCookie(Cookie).
In Java an HttpSession is established when the first request reaches your application. The Servlet Spec implementation in your container (Jetty, Tomcat, WebSphere, etc) will create and manage the HttpSession. The browser will receive a JSESSIONID cookie which will identify this particular session in the future.
Agreeing with the answers given above, I would like to conclude that Cookie and Session are two different entities in the world of web.
Cookie
Cookie represents some brief information that's generated by server and stored on client(browser). According to HTTP mechanism, browser have to send all the cookies(that have not expired), that server had sent before to browser.
Session
HTTP is a stateless protocol. Unlike FTP and other protocol, where connection state is preserved between multiple request-response transaction, in HTTP connection is established for one request and it's closed when response for that request is satisfied. This flaw in HTTP is present, because it was designed in early days to serve static web pages only. But as web has expanded, it's now used to serve dynamic full-fledged webapps. Thus, it has become necessary to identify users. Thus, for every request served by web-server, a labeling mechanism is required which can identify user of each request. This identification of user of request(whether the request has came from same user, same machine), sessions are used.
Session can be successfully implemented only if web-server can receive any information about the user in the request. One way of making this information available to user is Cookie. Others are URL rewriting, hidden fields, etc.
session.setAttribute() will store information in current session on server side not on client side(browser).
Hope it may help you.
Ok Looks like you want to see the difference between Cookies and Headers. They have different purpose. Cookies are temporary storage of information on client side. Server set the cookies(data) on the response and once set browser send these cookies(data) with each subsequent requests till the cookie expires. But headers are used as hints to browser and server. For ex
setHeader("Content-Type", "application/json");
will inform client to prepare to see a json response in the payload. Since it is a "one time" information there is not need the browser to send that information back to the server with each new requests like cookies.

Google Cloud Endpoint Backend - Is it possible to retrieve attributes of the HttpSession?

I'm trying to access the HttpSession object (or similar API that let me fetch session attributes) from inside of a Google Cloud Endpoints backend method...
Reading this answer I've learn that I can inject a HttpRequest object as a parameter.
What I'm trying to do is retrieve a facebook access token previously stored by a Servlet.
Within the Development Web Server I can retrieve the HttpSession and get the desired attribute:
#ApiMethod
public MyResponse getResponse(HttpServletRequest req) {
String accessToken = (String) req.getSession().getAttribute("accessToken");
}
But, once I deploy my application to GAE, the retrieved access token is always null.
So is there a way to recover session attributes from inside api methods?
And if there isn't, how can I retrieve my access token from someplace else? Answers and comments in the mentioned question suggests the use of the data store, but I really can't think of a good natural candidate for a key... As far as GAE authentication mechanism is concerned my users aren't even logged in, I don't know how to retrieve the access_token of the current user from the Datastore / memcached or any other mechanism.
I've filed a feature request to support sessions in production, as I can confirm it's not working right now.
For now, I recommend you continue passing the access token on subsequent requests in a header. Header information is similarly available through the injected HttpServletRequest.

GWT authenticated user session

My web application consists of 2 parts:
GWT app that does all the work.
Handmade servlet aimed to handle OpenID authentication facility.
I need to wire p.2 to p.1. I'm reading LoginSecurityFAQ, so I'd like to confirm whether my understanding is correct here.
Once OpenID provider confirms that user is OK and gives me its identity, I should register the session.
To "register" the session, I should store somewhere in my DB a mapping between OpenID identity and a session id (identity="https://www.google.com/accounts/o8/id?id=wwyruiwncuyrwieruyfakefakefake" and session id is a large random string like "HiuhoiuhIUHOIUY87Y*&Ttgi6yUYGIuygUHGugyg^G6g").
That session id should be stored on client side in a cookie.
Every time any request is sent from client side, on server side I should check whether client's session id is still fresh enough (alive) and I should also use it to resolve client's identity in case I need it.
Is it right? Is it secure enough in case session ID is really large?
Your thinking is right, I do it more or less like that too.
Just a few notes:
1) In case you want to persist the identity, do not forget to set the realm right. Depending on OpenID provider you may end up with a different identity for the same user on next login otherwise. I think Google's OpenID requires you to use your server name plus port:
openIdManager.setRealm("http://" + req.getServerName() + ":" + req.getServerPort());
2) Why create your own session management? It is quite a lot of extra work and you might end up writing up something insecure. Use common http servlet sessions.
3) You won't need to manage session timeouts if you use http sessions, but if you need to intercept all GWT RPC calls, the right place might be overriding service method in your RemoteServiceServlet implementation.

Categories

Resources