我在用着play framework 2.4.2
使用Java,我想通过拦截所有请求并检查是否设置了会话值来验证用户是否已登录。所以我延长了默认HttpRequestHandler https://www.playframework.com/documentation/2.4.2/api/java/play/http/DefaultHttpRequestHandler.html并覆盖createAction
拦截所有请求的方法。但是,我还没有找到验证会话的好方法。
选项 1 - 失败
当我尝试获取会话值时,出现运行时异常:There is no HTTP Context available from here
以下是我正在使用的课程:
public class RequestHandler extends DefaultHttpRequestHandler {
@Override
public Action createAction(Http.Request request, Method method) {
session("loggedIn"); // Throws runtime Exception: no HTTP Context
}
}
选项 2 - 丑陋
由于会话在技术上是一个 cookie,我可以使用如下代码从标头检索值:
for(String cookie : request.headers().get("Cookie")){
System.out.println("cookie: "+cookie);
}
但随后我必须解析类似于以下行的 cookie 字符串才能获取loggedIn 值。对我来说太脏了。
_ga=GA1.1.1508004144.1421266376; ki_r=; ki_t=1438789543788%378129908%3B1438789543788%3B1%3B1; PLAY_SESSION=0570411c3eb55ad230681539ddcfaa4220583fd-loggedIn=1
选项 3 - 太容易忘记注释
我注意到一些网站记录了不同的方法,而是创建了一个
动作组合 https://www.playframework.com/documentation/2.4.2/JavaActionsComposition并向每个控制器类或方法添加适当的注释。
这种方法的问题是它要求开发人员记住添加注释。我更愿意将其反转以默认阻止每个路由,然后向不需要验证的路由添加注释。
几个记录动作组合的网站:
- http://alexgaribay.com/2014/06/16/authentication-in-play-framework-using-java/ http://alexgaribay.com/2014/06/16/authentication-in-play-framework-using-java/
- https://www.playframework.com/documentation/2.2.1/JavaGuide4 https://www.playframework.com/documentation/2.2.1/JavaGuide4
Question
有没有办法全局验证用户是否应该有权访问页面以及如何获取会话变量?
*请注意,我对使用第三方插件进行身份验证不感兴趣。