Marcelo Oliveira Marcelo Oliveira - 2 months ago 34
Java Question

Role-based access control using Dropwizard

We're spiking Dropwizard for our next project and one of the things that we'll need to implement is a role based access control mechanism.

Is there a standard easy way to do it using Dropwizard or examples I can follow?


Have you taken a look at dropwizard-auth? It makes it very easy to plug in whatever authentication method you want (Shiro, Spring, etc). It also supports OAuth2 if you want to go that far...

You can implement a Shiro authenticator like this:

public class BasicAuthenticator implements Authenticator<BasicCredentials, Subject> {

  public Optional<Subject> authenticate(BasicCredentials credentials) throws AuthenticationException {
    Subject subject = SecurityUtils.getSubject();
    try {
      subject.login(new UsernamePasswordToken(credentials.getUsername(), credentials.getPassword(), false));
      return Optional.of(subject);
    } catch (UnknownAccountException | IncorrectCredentialsException | LockedAccountException e) {
    } catch (AuthenticationException ae) {
    return Optional.absent();


And you can register Shiro with the environment like this (called from your run method):

void configureAuthentication(Environment environment) {
  JdbcRealm realm = getJdbcRealm(); // However your Shiro realm is configured

  DefaultSecurityManager securityManager = new DefaultSecurityManager(realm);

  environment.jersey().register(new BasicAuthProvider<Subject>(new BasicAuthenticator(), "Shiro"));

And then check for a role like this:

public SecretPlan getSecretPlan(@Auth Subject subject) {
  if (user.hasRole("secretPlanner")) {
    return new SecretPlan();
  } else {
    return new NonSecretPlan();