When using homegrown authentication with manually putting the logged-in user in the HTTP session, you'd really have to pass it along yourself as a method argument as the service layer is supposed to be unaware of any frontend specifics such as the HTTP session (i.e., it's forbidden to import/use anything from javax.faces.*
, javax.servlet.*
, javax.ws.*
, etc in the service layer).
When using container managed authentication via j_security_check
or request.login()
, it's available by EJBContext#getCallerPrincipal()
. The EJBContext
is in turn just injectable via @Resource
. Here's an usage example in a logging interceptor.
@Resource
private EJBContext ejbContext; // You can also inject SessionContext.
@AroundInvoke
public Object log(InvocationContext invocationContext) {
String username = ejbContext.getCallerPrincipal().getName();
// ...
}
Note that it's never null
and defaults to "anonymous"
when non-logged-in.
Additional advantage of container managed authentication is that you can put security restriction annotations like @RolesAllowed
on service methods. How to use container managed authentication is in turn however a story apart. Start here: How to handle authentication/authorization with users in a database?