0

I'd like my application layer to be aware of which user is logged in to simplify method signatures - for instance method(owner, object) would be simply method(object). I use Spring Security for security though I'd like to keep Spring out of my application layer so there is a separate layer just for that purpose (and DTO conversion) - like a facade (adapter for application services).

How to make the application layer aware of the user context its operating on without using spring?

kboom
  • 2,279
  • 3
  • 28
  • 43

1 Answers1

1

You would need to register a Filter or HandlerInterceptor that would have a look at the HttpSession and, if the user is logged in, store some kind of User representation in some static ThreadLocal context. Any class could then have access to this static ThreadLocal containing your User object.

You would have to remove this object when the user logs out or session expires. Hint: HttpSessionListener.

Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
  • Do you mean something like [this](https://wiki.openclinica.com/doku.php?id=developerwiki:interceptor)? – kboom Aug 27 '13 at 18:50
  • @Kboom Similar. However with that solution, you would have to pass around the `HttpServletRequest` or `HttpSession` objects. Instead you should register them in a `static ThreadLocal` which you can then access from any class if you are in the same `Thread`. [This might help](http://stackoverflow.com/questions/2784009/why-should-java-threadlocal-variables-be-static). – Sotirios Delimanolis Aug 27 '13 at 18:52
  • Or maybe it would be much easier to just bind SecurityContextHolder.getContext() to that thread local? If I'm wrong correct me please. I'm looking for simplest solution :). – kboom Aug 27 '13 at 19:46
  • @Kboom See, I don't know Spring Security, but it seems that `SecurityContextHolder` is exactly what I was describing. If it already offers that, there is no need for you to add anything. Just call that method anywhere you need to check your user. – Sotirios Delimanolis Aug 27 '13 at 19:48
  • One more thing - you said you don't know Spring security. But is it that simple that I could register a listener on session creation / destruction event and bind those to functions from my application layer (for instance logout when session is destroyed) and have security mechanism with no spring security? I could just check what the state of that ThreadLocal variable is to ensure security? – kboom Aug 27 '13 at 20:10
  • @kboom Of course you could. That is probably how Spring security is implemented. Careful, a listener is created by the servlet container. You'll need some workarounds if you want to inject Spring beans. But that is a whole other topic. – Sotirios Delimanolis Aug 27 '13 at 20:11