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> {
@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();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With