我想使用带有细粒度身份验证的 RESTlet 公开资源。我的ServerResource
应该可以通过访问GET
仅适用于经过身份验证的会员(使用基本身份验证)。但是,请求使用POST
无需任何身份验证的呼叫者也应该可以使用。
为了澄清:http://路径/myapp/用户应该允许任何人注册使用POST
,但只有注册会员才能GET
所有用户的列表。
不幸的是,我对 RESTlet 不太感兴趣,我只找到了使用更粗略的身份验证的示例Restlet
s or Router
s.
那么如何启用资源的可选身份验证并在每个方法级别检查它们?
提前致谢!
在 RESTlet 2.0 中进行基本身份验证(我假设您正在使用 2.0,因为您提到了ServerResource
),你需要使用ChallengeAuthenticator
。如果配置为optional = true
那么只有当您调用时才会请求身份验证ChallengeAuthenticator.challenge()
.
您可以使用以下内容创建您的应用程序authenticate()
方法,并在需要访问要保护的资源时调用此方法:
应用:
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;
}
}
资源:
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
// ...
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)