[英]Difference between request.getSession() and request.getSession(true)
[英]Is calling request.getSession(true) explicitly required to persist programmatic authentication via request.login(username,password)?
在使用Java Servlet Filter
与内部SSO集成时,我努力寻找使用编程安全功能创建持久登录的正确方法。 具体来说,读很多教程,如后这个我打电话request.login(username,password)
和用户Principal
是创建了方法返回正确的值request.isUserInRole(role)
等当前请求。
我希望这对于用户来说将是持久的,但是后续请求将为request.getUserPrincipal()
返回null
,因此在每个请求上都输入了我的身份验证代码。 经过大量搜索后,我在这里发现的是,在调用request.login(username,password)
之前调用request.getSession(true)
request.login(username,password)
会使Principal
在用户会话中保持不变。
在登录用户以保留会话的Principal
之前是否需要显式创建会话? 这种行为对我来说似乎很奇怪,所以我想知道我做错了什么。 我感谢开发人员比我自己更了解此事的任何见解。 使用JDK 7和Tomcat8。Realm是RealmBase的扩展,它覆盖了authenticate(username,password),getName(),getPassword(username)和getPrincipal(username)。
public void doFilter(ServletRequest req, ServletResponse res, FilterChain fc) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest)req;
HttpServletResponse response = (HttpServletResponse)res;
if(request.getUserPrincipal() == null) {
try {
String userName = request.getParameter(userNameField);
String password = request.getParameter(passwordField);
request.getSession(true); // <-- block always entered without this
request.login(username,password);
}
catch(ServletException e) {
// Handle failed login...
return;
}
}
fc.doFilter(req,res);
}
答案是在AuthenticatorBase.java
的Tomcat源代码中, login(username,password)
链调用配置的Realm's
authenticate(username,password)
方法,然后调用register(...)
传递返回的Principal
并将其存储在会话中如果存在。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.