Search code examples
javajbossjaas

Client application to get the roles of a logged in user (JAAS)


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?


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.