JAAS - Java programmatic Security in Java EE 6 (without @DeclareRoles)
Asked Answered
H

2

9

Java Security is my main topic for the last couple of weeks and I archive the following:

  • Custom Valve Authentificator (extends AuthenticatorBase)
  • Custom Login Module for jBoss (extends UsernamePasswordLoginModule)
  • Secured Endpoint (JAX-RS)

My major problem is, that my endpoint works only with the annotation @DeclareRoles, if I don't use it I cant get through authentication. In detail the method AuthenticatorBase.invoke (from org.apache.catalina.authenticator) calls the method RealmBase.hasResourcePermission and there the roles will be checked.

Since I don't use any predefined roles the check will fail.

My question: Is there any way to use code like that:

@Path("/secure")
@Stateless
public class SecuredRestEndpoint {  

    @Resource
    SessionContext ctx;

    @GET
    public Response performLogging() {

        // Receive user information
        Principal callerPrincipal = ctx.getCallerPrincipal();
        String userId = callerPrincipal.getName();

        if (ctx.isCallerInRole("ADMIN")) {
            // return 200 if ok
            return Response.status(Status.OK).entity(userId).build();
        }
    ...
    }
}

Some additional background: There is the requirement to use a reverse proxy for authentication just the username gets forwarded (X-FORWARD-USER). Thats why I use my own Authenticator class and the custom Login module (I dont have any password credentials). But I think the problem also occurs with standard authentication methods from application server itself

Horsecar answered 26/10, 2012 at 9:43 Comment(0)
G
8

Since your code is static (meaning you have a static set of resources that can be secured), I do not understand your requirement for adding security roles aside from increasing access granularity. I could see this requirement in a modular environment, where the code is not static, in which case you would need to support the additional security roles declared by later deployments.

That said, I had to implement something similar, a security system that supports:

  • adding (declaring) / removing roles without redeployment;
  • associating users to those roles.

I'll describe on a high level of abstraction what I did and hopefully it will give you some useful ideas.

First off, implement an @EJB, something like this:

@Singleton
@LocalBean
public class MySecurityDataManager {

    public void declareRole(String roleName) {
        ...
    }

    public void removeRole(String roleName) {
        ...
    }

    /**
     * Here, I do not know what your incoming user data looks like such as:
     * do they have groups, attributes? In my case I could determine user's groups
     * and then assign them to roles based on those. You may have some sort of
     * other attribute or just plain username to security role association.
     */
    public void associate(Object userAttribute, String roleName) {
        ...
    }

    public void disassociate(Object userAttribute, String roleName) {
        ...
    }

    /**
     * Here basically you inspect whatever persistence method you chose and examine
     * your existing associations to build a set of assigned security roles for a
     * user based on the given attribute(s).
     */
    public Set<String> determineSecurityRoles(Object userAttribute) {
        ...
    }
}

Then you implement a custom javax.security.auth.spi.LoginModule. I'd recommend implementing it from scratch, unless you know the container provided abstract implementation will work for you, it didn't for me. Also, I suggest you get familiar with the following, if you aren't, to better understand what I'm getting to:


public class MyLoginModule implements LoginModule {

    private MySecurityDataManager srm;

    @Override
    public void initialize(Subject subject, CallbackHandler callbackHandler,
            Map<String, ?> sharedState, Map<String, ?> options) {
        // make sure to save subject, callbackHandler, etc.
        try {
            InitialContext ctx = new InitialContext();
            this.srm = (MySecurityDataManager) ctx.lookup("java:global/${your specific module names go here}/MySecurityDataManager");
        } catch (NamingException e) {
            // error logic
        }
    }

    @Override
    public boolean login() throws LoginException {
        // authenticate your user, see links above
    }

    @Override
    public boolean commit() throws LoginException {
        // here is where user roles get assigned to the subject
        Object userAttribute = yourLogicMethod();
        Set<String> roles = srm.determineSecurityRoles(userAttribute);
        // implement this, it's easy, just make sure to include proper equals() and hashCode(), or just use the Jboss provided implementation.
        Group rolesGroup = new SimpleGroup("Roles", roles);
        // assuming you saved the subject
        this.subject.getPrincipals().add(rolesGroup);
    }

    @Override
    public boolean abort() throws LoginException {
        // see links above
    }

    @Override
    public boolean logout() throws LoginException {
        // see links above
    }

}

In order to allow dynamic configuration (i.e. declaring roles, associating users), build a UI that uses that same @EJB MySecurityDataManager to CRUD your security settings that the login module will use to determine security roles.

Now, you can package these the way you want, just make sure that the MyLoginModule can look up the MySecurityDataManager and that you deploy them to the container. I worked on JBoss, and you mentioned JBoss, so this should work for you as well. A more robust implementation would include the lookup string in the LoginModule's configuration, which you then can read at runtime from the options map in the initialize() method. Here's an example configuration for JBoss:

<security-domain name="mydomain" cache-type="default">
    <authentication>
        <login-module flag="required"
                      code="my.package.MyLoginModule"
                      module="deployment.${your deployment specific info goes here}">
            <module-option name="my.package.MySecurityDataManager"
                           value="java:global/${your deployment specific info goes here}/MySecurityDataManager"/>
        </login-module>
    </authentication>
</security-domain>

At this point you can use this security domain mydomain to manage the security of any other deployments in the container.

Here are a couple usage scenarios:

  1. Deploy a new .war and assign it to the mydomain security domain. The .war comes with predefined security annotations throughout its code. Your security realm doesn't have them initially, so no user can log in. But after deployment, since the security roles are well documented, you open the mydomains configuration interface you wrote and declare those roles, then assign users to them. Now they can log in.
  2. After a few months of deployment, you no longer want users to have access to specific par of the war. Remove the security roles pertinent to that portion of the .war from your mydomain and no one will be able to use it.

The best part, especially about #2 is no redeployment. Also, no editing XML to override the default security settings declared with annotations (That is assuming your interface is better than that).

Cheers! I'll be happy to provide more specifics, but for now, this should at least tell you if you would need them.

Gaby answered 1/11, 2012 at 4:4 Comment(3)
Thank your for your answer, unfortunately I'm going on vacation so I can not respond now properly. In two weeks I will try and read your answer. CheersHorsecar
Thank you, it's an excellent source of inspiration even though I use Jetty instead of JBoss.Demy
@Demy I'm happy to hear you found it useful :)Gaby
T
2

If I'm getting you right, there are two problems.

  1. You don't want @DeclareRoles appear in your code. If you don't mind to use web.xml, take a look at this: http://docs.oracle.com/cd/E19159-01/819-3669/bncbg/index.html

  2. You want to solely use username to access your rest resource, because the rest resources don't have security threat, but at the same time the rest resource needs to know whom is calling.

    1. There is more than one way to do this. For identifying the user, you only need to provide user's id in your http request, JAAS security is overkill. For example, provide userid by URI:/user/bob, or by URI parameters like: /user?id=bob.

    2. If security is mandatory (if I don't get it wrong, you are using javaee's standard security component), you'll need to deal with roles, because java6's specification have role-based authentication/authorization written in.

Terpsichore answered 29/10, 2012 at 16:5 Comment(4)
Thank you for your answer: 1. The reason why I don't want to have @DeclareRoles in my code is because it's static and roles can change over time (maintenance). 2.1 I don't want to have just the user name within the REST code. Think about deeper context where I don't have the name present and I can't always provide him. I could easily read the parameter from the reqeust header, but thats not my aim. 2.2 I like to have JEE security with SesseionContext and user roles, but why it has to be static and not just programmatic?Horsecar
Just for the question "why it has to be static and not just programmatic?" Roles are static because applications, generally speaking, should not dynamically increase its securable features without redeployment. Though you can decide whether to specify roles in web.xml or your beans to make code maintenance easier, but better not avoid code redeployment.Terpsichore
Thats a good point and change it within the web.xml is not a big deal (no redeployment is necessary). I'll definitely consider it. From my project it is important not to redeploy if somthing changes, because it is a custom code for a client who don't want to touch the code nor ask the vendor to do it all the time. Thats why I was looking for a easy configurable solution. But apart from that, I thought there is a way to do my approach and I'll keep the bounty open to get as much response as possible :DHorsecar
Yeah, there should be some way I guess. There are lots of questions about JAXRS and security, oracle should really look into this, or at least provide some kind of guide about this.Terpsichore

© 2022 - 2024 — McMap. All rights reserved.