Controllo degli accessi basato sui ruoli utilizzando Dropwizard
-
21-12-2019 - |
Domanda
Stiamo spunendo Dropwizard per il nostro prossimo progetto e una delle cose che dovremo implementare è un meccanismo di controllo degli accessi basato sui ruoli.
C'è un modo standard facile per farlo usando Dropwizard o esempi che posso seguire?
Soluzione
Hai dato un'occhiata a Dropwizard-Auth ?Rende molto facile collegare qualsiasi metodo di autenticazione che desideri (Shiro, Spring, ecc.).Supporta anche OAUTH2 se vuoi andare così lontano ...
È possibile implementare un autenticatore shiro come questo:
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();
}
}
.
E puoi registrare Shiro con l'ambiente come questo (chiamato dal tuo metodo run
):
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"));
}
.
e quindi controlla un ruolo come questo:
@GET
public SecretPlan getSecretPlan(@Auth Subject subject) {
if (user.hasRole("secretPlanner")) {
return new SecretPlan();
} else {
return new NonSecretPlan();
}
}
. Altri suggerimenti
Puoi usare molto bene il dropwizard fornito meccanismi di autenticità http://www.dropwizard.io/0.9.1/docs/manual/auth.html
@RolesAllowed("ADMIN")
@GET
public SecretPlan getSecretPlan(@Auth User user) {
return dao.findPlanForUser(user);
}
.