12.07.2015 Views

Beginning Java EE 6 with GlassFish 3, Second Edition

Beginning Java EE 6 with GlassFish 3, Second Edition

Beginning Java EE 6 with GlassFish 3, Second Edition

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

CHAPTER 9 ■ TRANSACTIONS AND SECURITY}@RolesAllowed("admin")public void deleteBook(Book book) {em.remove(em.merge(book));}The last annotation, @RunAs, is handy if you need to temporarily assign a new role to the existingprincipal. You might need to do this, for example, if you’re invoking another EJB <strong>with</strong>in your method,but the other EJB requires a different role.For example, the ItemEJB in Listing 9-10 authorizes access to the user, employee, and admin role.When one of these roles accesses a method, the method is run <strong>with</strong> the temporary inventoryDpt role(@RunAs("inventoryDpt")). This means that, when the createBook() method is executed, theInventoryEJB.addItem() method will be invoked <strong>with</strong> an inventoryDpt role.Listing 9-10. A Stateless Bean Running as a Different Role@Stateless@RolesAllowed({"user", "employee", "admin"})@RunAs("inventoryDpt")public class ItemEJB {@PersistenceContext(unitName = "chapter09PU")private EntityManager em;@EJBprivate InventoryEJB inventory;public List findBooks() {Query query = em.createNamedQuery("findAllBooks");return query.getResultList();}}public Book createBook(Book book) {em.persist(book);inventory.addItem(book);return book;}As you can see, declarative security gives you easy access to a powerful authentication policy. Butwhat if you need to provide security settings to an individual, or apply some business logic based on thecurrent principal’s role? This is where programmatic security comes into play.Programmatic SecurityDeclarative security covers most security cases needed by an application. But sometimes you needmeans of a finer grain for authorizing access (allowing a block of code instead of the entire method,permitting or denying access to an individual, etc.). You can use programmatic authorization toselectively permit or block access to a role or a principal. That’s because you have direct access to the273

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!