0
無論何時在filter/servlet中,我們用request.getSession(false)
檢索會話,這意味着什麼?會話null,它是什麼意思?
我知道當會話爲空時,它可以表示任何這兩種情況。
- 沒有與請求相關聯的JSESSION Id cookie,請求是新請求。
- 與JSESSION id關聯的會話已過期?
我在我的應用程序中使用Spring-Security。我創建了一個攔截所有請求的過濾器,檢查是否有會話和與請求關聯的身份驗證對象,如果沒有,我假設請求是全新的,並創建一個新會話並創建一個空白身份驗證對象與NULL
主體和空白權限列表,並將驗證設置爲true。
HttpSession session = httpRequest.getSession(false);
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
if(session == null && auth == null) {
LOGGER.debug("In AuthenticationFilter | In doFilter | Session and Authentication are both null.");
session = httpRequest.getSession(true);
auth = CookieAuthentication.createBlankAuthentication();
auth.setAuthenticated(true);
SecurityContextHolder.getContext().setAuthentication(auth);
chain.doFilter(req, res);
}
else if(session == null && auth != null) {
LOGGER.debug("In AuthenticationFilter | In doFilter | Session is null but authentication is not.");
LOGGER.info("In AuthenticationFilter | Returning Response.");
Response response = new Response();
response = new Response();
response.setMessage("Session Has Expired.");
response.setFlag("SE");
httpResponse.setStatus(401);
try {
httpResponse.getWriter().write(response.toJSON());
httpResponse.getWriter().flush();
}
catch (IOException e) {
LOGGER.error(e.getMessage());
}
} else if (session != null && auth != null) {
LOGGER.debug("In AuthenticatorFilter | In doFilter | Session and Authentication are not null. ");
chain.doFilter(req, res);
} else {
/**
* Some Fatal error.
* We shouldn't be here.
*/
Response response = new Response();
response = new Response();
response.setMessage("Un Authenticated");
response.setFlag("UA");
httpResponse.setStatus(401);
try {
httpResponse.getWriter().write(response.toJSON());
httpResponse.getWriter().flush();
}
catch (IOException e) {
LOGGER.error(e.getMessage());
}
}
什麼是各種情況下,當我可以接收會話空和認證對象null和非空。
我的假設如下。
Session : null, authenticatin : null -> Fresh Request.
Session : null, authentication : not-null -> Expired Session.
Session : not-null, authentication : null -> Shouldn't happen normally.
Session : not-null, authentication : not-null -> Previously authenticated request.
請讓我知道我對這個概念的誤解。 以及其他這些,我想知道如何區分會話不存在,並且當我接收會話爲空時已經過期。