用于保护 Java EE 应用程序的注释

您可以在在源代码中使用注释来直接为 Java™ EE 企业应用程序提供安全性。

公共安全性注释:JSR 250 定义了一些公共安全性注释。定义了 5 种安全性注释:
  • javax.annotation.security.PermitAll:
    • 可在类型级别或方法级别使用。
    • 指示任何人均可访问给定的方法或给定 EJB 的所有业务方法。
  • javax.annotation.security.DenyAll:
    • 可在方法级别使用。
    • 指示任何人均无法访问 EJB 中的给定方法。
  • javax.annotation.security.RolesAllowed:
    • 可在类型级别或方法级别使用。
    • 指示与角色列表相关联的用户可以访问给定的方法或 EJB 中的所有业务方法。
  • javax.annotation.security.DeclareRoles:
    • 可在类型级别使用。
    • 定义用于安全性检查的角色。将由 EJBContext.isCallerInRole、HttpServletRequest.isUserInRole 和 WebServiceContext.isUserInRole 使用。
  • javax.annotation.security.RunAs:
    • 可在类型级别使用。
    • 指定给定组件的运行身份角色。

使用安全性注释

  • 对于 @PermitAll、@DenyAll 和 @RolesAllowed 注释,类级别的注释应用于某个类,方法级别的注释应用于某个方法。方法级别注释会覆盖类级别注释的行为。
    	@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;
    		}
    	}
     

    在本示例中,hello() 方法可供任何人访问,而 goodbye() 方法则供角色小组的用户访问。

  • @DeclareRoles 注释定义给定组件使用的角色列表。在 Java EE 5 或 6 环境中,您可以使用 @javax.annotation.Resource 来查找资源,并通过调用下列 API 来验证该用户是否分配有给定的角色:
    表 1. . 由 Java EE 组件使用的 API
    组件 用于检查角色的 API
    EJB javax.ejb.EJBContext.isCallerInRole(role)
    servlet javax.servlet.http.HttpServletRequest.isUserInRole(role)
    Web Service javax.xml.ws.WebServiceContext.isUserInRole(role)
  • @PermitAll、@DenyAll 和 @RolesAllowed 注释使您能够实现大部分权限决策。但是,要完成更多复杂逻辑,请使用 @DeclareRoles 注释。例如,假定 hello 方法可供位于角色 A 但同时不位于角色 B 中的某个用户访问。以下代码样本将实现此目标:
    	@Stateless
    		@DeclaresRoles({"A", "B"})
    		public class TestEJB implements Test {
    				@Resource private SessionContext sc;
    				public String hello(String msg) {
    						if (sc.isCallerInRole("A") && !sc.isCallerInRole("B")) {
    				...
    						} else {
    				...
    			}
    		}
    	}
     

安全性注释的无效使用

  • 不能将多个 @DenyAll、@PermitAll 和 @RolesAllowed 应用于同一种方法。例如,以下使用情况无效:
    	@PermitAll
    	@DenyAll
    		public String test()
     
  • 不能将两个 @RolesAllowed 注释应用于同一种方法。 例如,以下使用情况无效并将在编译时失败:
    		@RolesAllowed("team")
    		@RolesAllowed("otherteam")
    		public String hello()
    请改用此结构:
    		@RolesAllowed({"team", "otherteam"})
    		public String hello()
Icon that indicates the type of topic Concept topic
Timestamp icon Last updated: last_date

File name: csecuringejee.html