Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 436
Marcelo Oliveira Avatar asked Jun 03 '14 16:06

Marcelo Oliveira


Video Answer


1 Answers

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();
  }
}
like image 196
condit Avatar answered Sep 18 '22 13:09

condit