Write a Custom Authorisation Filter

In some cases, you might want to apply custom business logic for authorization after a user has been authenticated in Appkit. For example, you might want to load group and role information from an external database or directory, in those cases where the authentication provider does not provide this information.

This is relatively easy to do in Appkit, if you follow these steps.

1. Implement your own authorisation filter

MyAuthorisationFilter.java

import com.google.inject.Singleton;
import twigkit.model.auth.AnonymousUser;
import twigkit.model.auth.Role;
import twigkit.model.auth.User;
import twigkit.security.SecurityContext;
import twigkit.security.filter.AuthorisationFilter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

@Singleton
public class MyAuthorisationFilter implements AuthorisationFilter {

    @Override
    public void init() {
    }

    @Override
    public boolean filter(HttpServletRequest servletRequest, HttpServletResponse servletResponse) throws Exception {

        if (SecurityContext.getUser() != null && !(SecurityContext.getUser() instanceof AnonymousUser)) {
            User user = SecurityContext.getUser();

            List<Role> roles = null; // implement your own business logic here
            for (Role role : roles) {
                user.addRole(role);
            }
        }

        return true;
    }

    @Override
    public void destroy() {
    }
}

2. Bind your authorisation filter in Guice

Assuming you already have a Guice application module, add your authorisation filter to the authorisation bindings like so:

MyAppModule.java

import com.google.inject.multibindings.Multibinder;
import twigkit.AbstractTwigKitModule;
import twigkit.security.filter.AuthorisationFilter;

public class MyAppModule extends AbstractTwigKitModule {

    @Override
    protected void configure() {

        Multibinder<AuthorisationFilter> authorisationBinder = Multibinder.newSetBinder(binder(), AuthorisationFilter.class);
        authorisationBinder.addBinding().to(MyAuthorisationFilter.class);
    }
}

If you do not already have a Guice app module, simply create one like above, and add an entry to src/main/resources/META-INF/services/twigkit.TwigKitModule (note the capitalisation of TwigKitModule) containing the Fully-Qualified Class Name of the module. That is, in src/main/resources/META-INF/services/twigkit.TwigKitModule add the entry:

your.package.MyAppModule