1

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. :)

Community
  • 1
  • 1
bell
  • 63
  • 11

2 Answers2

2

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.

Gas
  • 17,601
  • 4
  • 46
  • 93
  • thank you for your response, I will read articles about the session context. Do you have suggested tutorial site for beginners in this field ? – bell Apr 03 '15 at 13:30
  • @bell Take a look at link to Java EE Tutorial that [endriu_l](http://stackoverflow.com/a/29427706/3701228) posted in his answer it shows all that. – Gas Apr 03 '15 at 15:43
1

About securing beans - You should use javax.ejb.SessionContext to get principal information or check specific role and go from there.

There are some nice examples regarding security in Oracle's Java EE 6 tutorial

endriu_l
  • 1,649
  • 16
  • 20