我正在尝试使用Deadbolt 2在Play Framework 2.4.x中实现一个简单的身份验证系统。
我已经按照Chaloner编写的guide进行了操作,我已经实现了我的死锁处理程序,如您所见:
public class MyDeadboltHandler extends AbstractDeadboltHandler {
public F.Promise<Optional<Result>> beforeAuthCheck(Http.Context context) {
// returning null means that everything is OK. Return a real result if you want a redirect to a login page or
// somewhere else
return F.Promise.promise(Optional::empty);
}
public F.Promise<Optional<Subject>> getSubject(Http.Context context) {
// in a real application, the user name would probably be in the session following a login process
User user = new User("MyUser", "my.email@info.com");
return F.Promise.promise(() -> Optional.ofNullable(user));
}
public F.Promise<Optional<DynamicResourceHandler>> getDynamicResourceHandler(Http.Context context) {
return F.Promise.promise(() -> Optional.of(new MyDynamicResourceHandler()));
}
@Override
public F.Promise<Result> onAuthFailure(final Http.Context context, final String content) {
// you can return any result from here - forbidden, etc
return F.Promise.promise(() -> Controller.redirect(routes.Application.index()));
}
}
我的主控制器是:
public class Application extends Controller {
public Result index() {
return ok(index.render());
}
@SubjectPresent
public Result denyAccess(){
return ok(notAllowed.render());
}
public Result permitAccess(){
return ok(allowed.render());
}
public Result errorPage(){
return ok(errorPage.render());
}
}
当我尝试访问操作denyAccess
呈现的页面时,会出现问题。在这种情况下,我在页面上得到一个NullPointerException而没有我可以读取的堆栈跟踪,如下图所示。
即使我尝试访问控制器denyAccess,似乎也永远不会调用onAuthFailure方法。
你可以在我的github页面上看到完整的项目here,它非常简短,我认为它可以帮助你理解这个问题。
感谢您的帮助。
答案 0 :(得分:1)
问题在于您实施HandlerCache
:
@Singleton
public class MyHandlerCache implements HandlerCache {
private final Map<String, DeadboltHandler> handlers = new HashMap<>();
public MyHandlerCache() {
handlers.put("DEFAULT_KEY", new MyDeadboltHandler());
}
@Override
public DeadboltHandler apply(final String key) {
return handlers.get(key);
}
@Override
public DeadboltHandler get() {
return handlers.get("DEFAULT_KEY");
}
}
默认情况下,默认处理程序键名由be.objectify.deadbolt.java.ConfigKeys.DEFAULT_HANDLER_KEY
定义,但在MyHandlerCache
中使用"DEFAULT_KEY"
。但是,当调用此方法时:
public DeadboltHandler apply(final String key) {
return handlers.get(key);
}
它将接收be.objectify.deadbolt.java.ConfigKeys.DEFAULT_HANDLER_KEY
作为键并返回null。
我确保更好地记录并在文档中明确说明。要修复您的实施,请将"DEFAULT_KEY"
替换为be.objectify.deadbolt.java.ConfigKeys.DEFAULT_HANDLER_KEY
:
@Singleton
public class MyHandlerCache implements HandlerCache {
private final Map<String, DeadboltHandler> handlers = new HashMap<>();
public MyHandlerCache() {
handlers.put(ConfigKeys.DEFAULT_HANDLER_KEY, new MyDeadboltHandler());
}
@Override
public DeadboltHandler apply(final String key) {
return handlers.get(key);
}
@Override
public DeadboltHandler get() {
return handlers.get(ConfigKeys.DEFAULT_HANDLER_KEY);
}
}