Why do I list security roles in web.xml when they&

2019-02-10 00:57发布

问题:

I run JavaEE 6 web application on Glassfish 3. I use JAAS with jdbcRealm and default principal to role mapping. In my database I have table for mapping usernames to their roles:

 username | role
----------+-------
 john     | admin
 mary     | user

Why do I need to list these roles once again in my web.xml?

<security-role>
  <role-name>admin</role-name>
</security-role>
<security-role>
  <role-name>user</role-name>
</security-role>

Without that isUserInRole() always returns false.

回答1:

You don't redefine security roles in web.xml. You list them so an application server knows about their use in your code.

When you deploy a secured application, an application server reads a deployment descriptor to solicit information about security configuration. It knows about roles that are used in your application. The application can then use the roles and expect the application server is able to map them to users and groups (that ultimately resolve to users again as users are the security finest building blocks).

Speaking of mapping roles to users, that's where a realm comes in. It offers the mapping so you know that a role X in a deployment descriptor maps to the role X in a database that in turn map to users A and B.

With that said, the database that's used by jdbcRealm has exactly the same roles because they're the keys to users that the application server needs to map to roles in the application.

What you use in your code and a deployment descriptor is a logical name of a group of users that are resolved to real users via the mapping that's offered by the jdbcRealm.