Question

I have the following code working to run a Java (SE) application (not on server), where the login should be done using an existing JBoss server (I am tied to 4.2.3) running with JAAS authentication. I started with a simple console application to perform the login and later integrate this functionality to the application.

I use a snippet - found here - to perform the login:

JaasJbossConfiguration.activateConfiguration();
UsernamePasswordHandler handler =
  new UsernamePasswordHandler("userName", "passWord");
LoginContext lc = new LoginContext("myrealm", handler);
try {
     lc.login();
} catch (LoginException e) {
 // Authentication failed.
}

This works like a charm. Now I want to extend my application and permit access only for users in special role. Is there any way to get the roles of the user from the Java application side or permit authentication only for those users?

Was it helpful?

Solution

  • You could prevent authentication based on a (non-existing) role, if the (custom) login module checks for it.
  • But normally, if there is a user with a matching password, the user is authenticated (possibly with no roles at all). So normally authentication (user/password) is not linked with authorization (roles).

  • In EJBs you can use declarative authorization based on roles (see @RolesAllowed)
  • As for EJBs: You can call EJBContext.getCallerPrincipal() and EJBContext.isUserInRole() in an EJB
  • As for a servlet/JSP: you can call HttpServletRequest.getRemoteUser() and HttpServletRequest.isUserInRole()
  • As for stand-alone applications, I am not aware of an API.
  • So the standard API only allows to check against a role. If you want to get the list of roles, there is no official API.

Anyway, look into the source of a login module (for example: DatabaseServerLoginModule). Then write an EJB which does the same (regarding roles lookup), and which returns the list of roles to your stand-alone application.

OTHER TIPS

Follow below steps to make use of JEE security provided by containers (mostly JAAS). The advantage is, you can change the authentication and authorization to any new technology with just configuration, without impacting other part of application. I give an example using JBoss AS

  1. Add security constraints in web.xml

    Web Resources /* ROLE_ADDUPDATE ROLE_SEARCH ROLE_ADMIN ROLE_ADMIN ROLE_ADDUPDATE ROLE_SEARCH

  2. Add Jboss Security domain name in jboss-web.xml

    java:/jaas/other true

    • Add users and roles in application-users.properties and applications-roles.properties (see documentatin of Jboss for Command Line Interface)
    • You can even authorize at granular level like EJB method level using @RolesAllowed, @PermitAll, @DenyAll etc if you are using EJBs
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top