Para realizar la autenticación básica en RESTlet 2.0 (supongo que está utilizando 2.0 ya que menciona ServerResource
), debe utilizar un ChallengeAuthenticator
. Si esto está configurado con optional = true
, entonces la autenticación solo se solicitará si invoca ChallengeAuthenticator.challenge()
.
Puede crear su aplicación con un método authenticate()
, y llamar a esto cada vez que necesite acceso a un recurso para ser asegurado:
Aplicación:
package example;
import org.restlet.*;
import org.restlet.data.ChallengeScheme;
import org.restlet.routing.Router;
import org.restlet.security.*;
public class ExampleApp extends Application {
private ChallengeAuthenticator authenticatior;
private ChallengeAuthenticator createAuthenticator() {
Context context = getContext();
boolean optional = true;
ChallengeScheme challengeScheme = ChallengeScheme.HTTP_BASIC;
String realm = "Example site";
// MapVerifier isn't very secure; see docs for alternatives
MapVerifier verifier = new MapVerifier();
verifier.getLocalSecrets().put("user", "password".toCharArray());
ChallengeAuthenticator auth = new ChallengeAuthenticator(context, optional, challengeScheme, realm, verifier) {
@Override
protected boolean authenticate(Request request, Response response) {
if (request.getChallengeResponse() == null) {
return false;
} else {
return super.authenticate(request, response);
}
}
};
return auth;
}
@Override
public Restlet createInboundRoot() {
this.authenticatior = createAuthenticator();
Router router = new Router();
router.attach("/user", UserResource.class);
authenticatior.setNext(router);
return authenticatior;
}
public boolean authenticate(Request request, Response response) {
if (!request.getClientInfo().isAuthenticated()) {
authenticatior.challenge(response, false);
return false;
}
return true;
}
}
de recursos:
package example;
import org.restlet.data.MediaType;
import org.restlet.representation.EmptyRepresentation;
import org.restlet.representation.Representation;
import org.restlet.representation.StringRepresentation;
import org.restlet.resource.ServerResource;
public class UserResource extends ServerResource {
@Override
public Representation get() {
ExampleApp app = (ExampleApp) getApplication();
if (!app.authenticate(getRequest(), getResponse())) {
// Not authenticated
return new EmptyRepresentation();
}
// Generate list of users
// ...
}
@Override
public Representation post(Representation entity) {
// Handle post
// ...
}
}
En primer lugar, gracias por su respuesta, esto parece prometedor. Sin embargo, tengo algunos problemas para hacer que tu código funcione. Por ejemplo, no hay un método 'getSubject()' para ClientInfo (estoy usando 2.0m7). Además, no estoy seguro de si su método 'authenticate()' es correcto? –
Estaba usando una instantánea anterior; He actualizado los ejemplos para trabajar con 2.0m7. – Sam
Gracias, una vez más, ahora el código se compila y POST siempre está disponible. Desafortunadamente, GET nunca es. No importa si proporciono credenciales BÁSICAS incorrectas o incorrectas, siempre obtengo un 401. –