Search code examples
javavalidationjakarta-eestateless

How to get logged in user stateless bean


I am confused on how I should validate a logged-in user. I was thinking about calling stateful bean from stateless bean but I read this topic access existing instance stateful inside stateless, java ee 6

Here is my idea.

ProductBean.java

@Stateless
@LocalBean
public class ProductBean {
    @EJB private UserBean userBean; // UserBean is SFSB
    public Product addProduct(Product product) {
        if(userBean == null || userBean.getLoggedInUser() == null) {
            // throw an exception
        }
        // persist 
    }
}

ProductController.java

@ManagedBean
@RequestScope
public class ProductController {
    @EJB private ProductBean productBean;
    private Product product;
    public void addProduct() {
        Object result = productBean.addProduct(productBean);
    }
}

Thank you in advance. :)


Solution

  • If you want to protect your beans you should rather use Java EE security mechanisms like@RolesAllowed and sessionContext.getCallerPrincipal() instead of creating your own mechanisms. If you will do proper authentication in the web module, security context will be propagated to the EJBs.

    Stateful beans are not very good idea, and particularly in your design. You cannot use stateful beans in stateless beans, as stateless beans instances are reused among different calls/users.