如果有人可以帮助我解决以下问题,我将不胜感激:
最佳答案
What are the differences between @RolesAllowed and @DeclareRoles annotations?
@RolesAllowed
批注用于指定实际上允许访问业务方法的角色列表。此注释的存在会影响EJB在运行时的行为,因为EJB容器会主动验证调用者是否处于允许的角色中。同样,可以在TYPE
和METHOD
上定义此批注,从而使您可以定义在类或方法级别上允许的角色列表。您可以在单个方法的级别覆盖类的所有方法所允许的角色列表。另一方面,
@DeclareRoles
注释仅用于声明角色列表。它等效于security-role-ref
文件中的ejb-jar.xml
元素。 EJB容器不需要了解这些角色即可对EJB的业务方法执行访问控制检查。相反,bean提供者/开发人员可以在isCallerInRole
测试中使用这些角色,以确保程序安全性。EJB 3.1规范声明了有关
@DeclareRoles
注释的以下内容:17.2.5.3 Declaration of Security Roles Referenced from the Bean’s Code
The Bean Provider is responsible for using the DeclareRoles annotation or the security-role-ref elements of the deployment descriptor to declare all the security role names used in the enterprise bean code. The DeclareRoles annotation is specified on a bean class, where it serves to declare roles that may be tested by calling isCallerInRole from within the methods of the annotated class. Declaring the security roles allows the Bean Provider, Application Assembler, or Deployer to link these security role names used in the code to the security roles defined for an assembled application. In the absence of this linking step, any security role name as used in the code will be assumed to correspond to a security role of the same name.
问题的第二部分指出:
I developed a login function to check username and password against information in the database. However, I'd like to ask how I can assign a role to an authenticated user to use with the above annotations.
在这种情况下,需要指出的一般要点是,我的首选方法是不使用组合安全性,除非您的用例实际需要它。在大多数情况下,如果可以使用声明性安全性满足要求,则最好使用它,因为程序安全性要求您跟踪
isCallerInRole
方法调用,而没有这样的调用可能会导致安全漏洞。无论哪种情况,您都需要容器首先识别数据库中的组和主体,作为可能用于访问控制检查的角色。用简单的话来说,EJB客户端(一个Java SE应用程序,一个servlet或另一个EJB)必须首先根据容器的安全性机制对自己进行身份验证,以建立调用者的
Principal
。因此,成功使用声明性或程序性安全性取决于成功的身份验证过程。在您的情况下,您将需要配置容器以识别数据库中的组和用户,并将其转换为Principal
对象,这些对象可用于以声明性或编程方式实现访问控制。为此,大多数容器都支持一种或多种JAAS登录模块。例如,Glassfish 3.1允许使用JDBCRealm进行此操作,而JBoss 6.0支持使用DatabaseServerLoginModule进行此操作。因此,您将需要确定您的容器是否支持这种登录模块,并将其配置为使用数据库。请注意,在某些情况下,容器提供的登录模块可能不足以满足您的需求。在这种情况下,您需要编写自己的登录模块(如果需要,请针对容器的接口(interface))。
另外,您还需要将应用程序使用的角色映射到JAAS领域中的用户和组。例如,如果您的数据库由JAAS领域使用:
U1
,U2
,U3
,U4
和U5
以及G1
,G2
和G3
,分别包含U1
,U2
,U3
和R1
,R2
和R3
(通过@RolesAllowed
批注定义)的用户访问其方法那么您需要将角色映射到JAAS领域中的主体(用户和组)。即使角色名称与主体名称相同,也必须进行映射。 Glassfish simplifies this by supporting the default principal to role mapping将名称相似的主体(用户或组)直接映射到角色。另外,映射的过程是特定于容器的,并且您已经猜到了,该映射是在特定于容器的部署描述符中而不是在EJB部署描述符(
ejb-jar.xml
)中执行的。要完成答案,您需要为创建的每个用户分配一个角色。为了简单起见,您可以创建一个所有用户都可能属于的单个用户组。当用户针对JAAS领域对自己进行身份验证时,Principal对象将包含该组。然后,可以将JAAS领域中的组映射到EJB角色,并且可以在
@RolesAllowed
批注中指定角色名称。 EJB容器将阻止数据库中不在该组中的任何用户访问带注释的方法。
关于java - ejb有关角色和身份验证的安全性问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7219312/