您应该将用户主体与 Restlet 一起使用。事实上,Restlet 有自己的基于挑战响应的安全机制。这允许对请求的用户进行身份验证,获取其角色并在ClientInfo#user 中设置。 servlet 扩展必须被视为在 servlet 容器中嵌入 Restlet 引擎的适配器,但您不应依赖 servlet API。
这是使用 Restlet 安全性的方法:
public class MyApplication extends Application {
public Restlet createInboundRoot() {
Router router = new Router(getContext());
(...)
ChallengeAuthenticator ca = new ChallengeAuthenticator(getContext(),
ChallengeScheme.HTTP_BASIC, "admin");
Verifier verifier = (...)
Enroler enroler = new MyEnroler(this);
ca.setNext(router);
return ca;
}
}
这是Verifier的示例实现:
public class MyVerifier extends SecretVerifier {
@Override
public boolean verify(String identifier, char[] secret) {
System.out.println(identifier);
System.out.println(secret);
//TODO compare with the Database
return true;
}
}
这是Enroler的示例实现:
public class MyEnroler implements Enroler {
private Application application;
public MyEnroler(Application application) {
this.application = application;
}
public void enrole(ClientInfo clientInfo) {
Role role = new Role(application, "roleId",
"Role name");
clientInfo.getRoles().add(role);
}
}
然后,您可以从过滤器、服务器资源等中的请求访问安全/身份验证提示,如下所述:
User user = getRequest().getClientInfo().getUser();
List<Role> roles = getRequest().getClientInfo().getRoles();
你可以注意到这个机制是在 Restlet 中打开的,并且可以支持多种身份验证(oauth2,...)。在 REST 中使用基于 cookie 的身份验证并不是真正的好方法。也就是说,即使与 Restlet 一起使用,您也可以使用它。
希望对你有帮助
蒂埃里