Veera
Veera

Reputation: 33172

How to get the user roles in Servlet?

I'm using Jbos AS 5 and the DatabaseServerLoginModule for the authorization. I've my application policy defined as (for example only, not the actual code):

<application-policy name = "jbossmq">
  <authentication>
    <login-module code = "org.jboss.security.auth.spi.DatabaseServerLoginModule"
       flag = "required">
       <module-option name = "unauthenticatedIdentity">guest</module-option>
       <module-option name = "dsJndiName">java:/MyDatabaseDS</module-option>
       <module-option name = "principalsQuery">SELECT PASSWD FROM JMS_USERS WHERE USERID=?</module-option>
       <module-option name = "rolesQuery">SELECT ROLEID, 'Roles' FROM JMS_ROLES WHERE USERID=?</module-option>
    </login-module>
  </authentication>
</application-policy>

Once the user is successfully authorized, how can I retrieve the user roles from my servlet? In the above code snippet, the roles are selected from the database, but where are they being stored? In session !? If yes, under which session variables?

Also, is it possible to use Ldap Authentication and Database Authorization combinely in JBoss?

Upvotes: 2

Views: 8960

Answers (3)

thr0wable
thr0wable

Reputation: 502

If the container is JACC compatible the following snippet might work (at least for me on Glassfish 3.1.x)

Subject subject = (Subject) PolicyContext.getContext("javax.security.auth.Subject.container");
for (Principal principal : subject.getPrincipals()) {
    LOG.debug("In subject: " + principal.getName());
}

The first hit is (usually) your user principal and the others tend to be group principals. Please not that if you happen to know the group principals class name you can filter it by calling getPrincipals(Class<T> c) instead.

Upvotes: 2

david a.
david a.

Reputation: 5291

Clinton is basically right, the

boolean HttpServletRequest.isUserInRole(String role)

method can be used to check if a user has a certain roles assigned. However, this method is intended to check for the J2EE roles defined byt the application (in EAR's descriptor, the application.xml).

During deploy, or by packaing an AS-specific descriptor within your EAR file, you need to specify mapping of the application server's user roles (these you set to principals in your login module) to the J2EE app. roles.

Upvotes: 6

Clinton
Clinton

Reputation: 2837

I am aware of the method:

boolean HttpServletRequest.isUserInRole(String role)

I know that doesn't give you a list of all the roles, but would it serve your purpose?

Upvotes: 2

Related Questions