how to programmatically invalidate a session using spring security - session

Some users of my application can use it for a fixed maximum amount of time. At the first request happening past the expiration time, after checking the user is part of the target group, I want to invalidate the session, update the user and return a 401.
In theory a servlet filter invoked post-session-validation could be used for this. I am looking for pointers on how to do this using spring security.
Thanks!

While you could most certainly just add a normal servlet filter that executes at the very end of the chain (or at least after the Spring Security filter stack) where you get the SecurityContext and inspect the user (potentially logging out the user like this or this), I would suggest you instead simply change the session duration on per-user basis. After a successful login (AuthenticationSuccessHandler is a good place) you could simply call setMaxInactiveInterval on the session and give it a different value depending on the user's role. This seems a lot cleaner to me as you don't have to separately handle otherwise semantically equal actual and forced session expiration/logout cases.

Related

Spring Boot - How to associate a request with a particular user?

I have a spring boot application and now i need to return specific information for each user that makes an http request. How can i achieve this? I have to scale this up so multiple instances of the application must be consider.
For example..
In the fornt end an user is logged in, for each request this user makes, i have to return his proper information.
If another user is logged, and makes a request at the same time, he also gets his own information.
I was thinking that i can achive this by including user id in each request but donĀ“t know if this is the proper way.

What is difference between disabled and stateless session management?

What is difference between the following options:
http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
and
http.sessionManagement().disable()
?
Seems like in the first case SessionManagementFilter will be added and do nothing. While in the second case it will not be added at all. So, seems like it is better to always use the second option if you don't need sessions. But I'm not sure.
Behaviour-wise I've noticed that, as you say, setting it as STATELESS adds a SessionManagementConfigurer to the SecurityBuilder and disabling it just adds null as the configurer.
This affects the SessionAuthenticationStrategyies added when configuring security. For example, enabling CSRF protection will add a CsrfAuthenticationStrategy even for statless case but will not for disabled session management.
To sum up: disabling it will not execute session authentication strategies at all but enabling it will execute it on each authenticated request for a stateless scenario.
Hope it helps, this is based on personal experience (configuring, trial-error, debugging).

How to invalidate a JCR session based on user inactivity in AEM?

I am designing a solution for the use case where I am logging into my website in AEM 6.3 and would like to logout the user from the website after a definite time of inactivity.
However, I did not find any such method in the javax.jcr.session API which allows the same. For reference, I am looking something similar to the setMaxInactiveInterval(int interval) method of HttpSession.
Also, if it is not possible in JCR Sessions, is it a conscious choice of design? If yes, what is the reason for the same?
You don't have to worry about the jcr Session, sling creates a new session for every request, and closes it when the request is done. There is no jcr Session associated with a user session as such.
Sling delegates the user session to the underlying servlet container Jetty; which, with default config never clears the sessionid cache on the server. But the login-token cookie is not set any expiration date and is cleared when the browser session is closed.

Does custom security HTTP headers violate separation of concerns

Does custom application specific, security related HTTP headers violate separation of concerns, is it considered a bad practice? I realize using custom header to control the service would tightly couple the client with the service implementation. Or in this case, to control the security framework behavior. The context where I planned using the custom header is the following:
We are using token based authentication, where token has a fixed lifetime, and new token is issued each time authenticated client calls the web API. SPA client may call the server with AJAX in two contexts
User action (navigation and submit)
Automatic refresh (current view re-fetches data at fixed intervals)
Now, if user leaves the page open, the session never expires, as new token is generated for each automatic fetch. Somehow, we need to differentiate user action from automatic refresh in the server side, and issue new token only for user actions.
I realize Websocket based refresh would be one solution, but we have decided to stick with timed AJAX call due specific matters. Another solution would be to provide token refresh as a separate endpoint, but this would violate the DRY principle from client's perspective, and would be more cumbersome to setup with Spring Security.
Only remaining option is to embed the user/automated information in the request itself, and using a header seems a viable option here. A presence of certain header would prevent the token refresh. Easy to implement with a few lines of code.
I'm only concerned, if this couples the client too much with the service implementation. Technically, it doesn't couple client with the service, but the preceding security filter, thus leaking security concerns in the user interface. Ideally security stuff should be transparent to user interface, so new client could be coded without knowing anything about security (especially when cookies are used).
In the other hand, this solution isn't destructive or mutative. It's an optional feature. By client utilizing it, security is enhanced, but in either case never reduced (from the perspective of server, as it is). Now the question is, what principles using a optional header to enhance security is violating, and is it a valid solution in this context?
In my option the security should be maximized transparently, but I don't see how to not leak security concerns in the client in this situation.
It sounds like you're using your own home-built custom Token Authentication solution here. This is not a good idea.
I'll take a moment to explain WHY you don't want to do what you're proposing, and then what the better option is.
First off -- the problem that you're trying to solve here is that you don't want a user to remain logged into your site forever if they leave a tab open. The reason you need to fix this is because right now, you're assigning a new Access Token on EVERY REQUEST from the user.
The correct solution to handling the above problem is to have two types of token.
An Access Token that has a very short lifetime (let's say: 1 hour), and a Refresh Token that has a longer lifetime (let's say: 24 hours).
The way this should work is that:
When the user first authenticates to your service, the Access and Refresh tokens are generated with their respective timeouts.
These tokens are both set in HTTP cookies that the client-side JS cannot access.
From this point on, every time your user's browser makes a request to your service, you'll parse out the Access token from the cookie, check to see if it's valid, then allow the request.
If the Access token is no longer valid (if it has expired), you'll then parse out the Refresh token from the cookie, and see if that is valid.
If the Refresh token is valid, you'll generate a NEW Access token with another 1 hour lifetime, and override the old Access token cookie with the new on.
If the Refresh token is invalid, you'll simply return a 301 redirect to the login page of your app, forcing the user to manually re-authenticate again.
This flow has a number of benefits:
There is a maximum session length, which is technical (duration of Refresh token + duration of Access token) -- aka: 25 hours in this example.
Access tokens are short lived, which means that if a token is somehow compromised, attackers can't use it for very long to impersonate the user.
What's nice about the above flow is that it is a web authorization standard: OAuth2.
The OAuth2 Password Grant flow does EXACTLY what you're describing. It generates both types of tokens, handles 'refreshing' tokens, handles the entire thing from start to finish in a safe, standards-compliant way.
What I'd highly recommend you do is implement an OAuth2 library on both your server and client, which will take care of these needs for you.
Now -- regarding the tokens, most OAuth2 implementations now-a-days will generate tokens as JSON Web Tokens. These are cryptographically signed tokens that provide a number of security benefits.
Anyhow: I hope this was helpful! I author several popular authentication libraries in Python, Node, and Go -- so this comes from my direct experience working with these protocols over the last several years.

Spring do not update session for ajax polling

We are currently running into a problem with session time outs on one of our Spring web applications. The session never times out because we have a continuous ajax request polling the server. Is there a way to tell spring to ignore this request and not update the session so that time out works as expected?
You could run a timer, equal to your session timeout, along side the continuous ajax request that would log the user out if the page never refreshes. Another idea would be to host the URL that you are hitting in a separate web application on the same domain. I'm not sure if Spring has something built in for what you are doing.
I thought about this some more. You could implement your own session registry that ignores the Ajax URLs. Basically you wouldn't set the last accessed time for a user in the session registry if the URL matched one that you defined in your ignore list or filter defined in the Spring Security filter chain.
See SessionRegistry

Resources