Question

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?

Was it helpful?

Solution

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> {

  @Override
  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);
  SecurityUtils.setSecurityManager(securityManager);

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

And then check for a role like this:

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

OTHER TIPS

You can very well use dropwizard provided auth mechanisms http://www.dropwizard.io/0.9.1/docs/manual/auth.html

@RolesAllowed("ADMIN")
@GET
public SecretPlan getSecretPlan(@Auth User user) {
   return dao.findPlanForUser(user);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top