Role Based Access Control with Dropwizard

We are dropping Dropwizard for our next project, and one of the things we need to implement is a role-based access control mechanism.

Is there a standard easy way to do this with Dropwizard or examples that I can follow?

+6
source share
2 answers

Have you looked at dropwizard-auth ? This allows you to easily connect any authentication method (Shiro, Spring, etc.). It also supports OAuth2 if you want to go this far ...

You can implement the Shiro authenticator as follows:

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 Syro with this environment (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 out a role like this:

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

You can very well use the dropwizard provided by the 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); } 
+1
source

Source: https://habr.com/ru/post/970254/


All Articles