Securing EJBs
You can provide security for your EJB application using annotations or using deployment descriptors.
Before Java™ EE 5, if you wanted to use authorization for a given application, you needed to specify authorization information in the application deployment descriptors ejb-jar.xml or web.xml. You can set up security in your application directly using annotations.
Common security annotations
JSR 250 defines a number of common security annotations. Five security annotations are defined:- javax.annotation.security.PermitAll:
- Can be used at type or method level.
- Indicates that the given method or all business methods of the given EJB are accessible by everyone.
- javax.annotation.security.DenyAll:
- Can be used at method level.
- Indicates that the given method in the EJB cannot be accessed by anyone.
- javax.annotation.security.RolesAllowed:
- Can be used at type or method level.
- Indicates that the given method or all business methods in the EJB can be accessed by users associated with the list of roles.
- javax.annotation.security.DeclareRoles:
- Can be used at type level.
- Defines roles for security checking. To be used by EJBContext.isCallerInRole, HttpServletRequest.isUserInRole, and WebServiceContext.isUserInRole.
- javax.annotation.security.RunAs:
- Can be used at type level.
- Specifies the run-as role for the given components.
Example:
@Stateless
@RolesAllowed("team")
public class TestEJB implements Test {
@PermitAll
public String hello(String msg) {
return "Hello, " + msg;
}
public String goodbye(String msg) {
return "Goodbye, " + msg;
}
}
In this example, the hello() method is accessible by everyone, and the goodbye() method is accessible by users of role team.