Shiro 自己實現登入後重新生成sessionid
阿新 • • 發佈:2019-01-03
Shiro Security是非常不錯的Security框架,我們系統在使用過程中發現Shiro在登入之後不會生成新的Jessionid。這顯然會出現Session_Fixation。Shiro自己說會在下一個版本1.3 fix這個問題,在這之前只能學Spring Security來實現重新生成Session。其實簡單就是在登陸之後把session資料複製一份到新的session。
Shiro中要做到這一點可以通過實現可以通過繼承org.apache.shiro.web.filter.authc.AuthenticatingFilter (一般是繼承AuthenticatingFilter的子類FormAuthenticationFilter),重寫executeLogin方法就可以了。
protected boolean executeLogin(ServletRequest request, ServletResponse response) throws Exception {
AuthenticationToken token = createToken(request, response);
if (token == null) {
String msg = "createToken method implementation returned null. A valid non-null AuthenticationToken " +
"must be created in order to execute a login attempt.";
throw new IllegalStateException(msg);
}
try {
Subject subject = getSubject(request, response);
//獲取session資料
Session session = subject.getSession();
final LinkedHashMap<Object , Object> attributes = new LinkedHashMap<Object, Object>();
final Collection<Object> keys = session.getAttributeKeys();
for (Object key : keys) {
final Object value = session.getAttribute(key);
if (value != null)
{ attributes.put(key, value); }
}
session.stop();
subject.login(token);
// 登入成功後複製session資料
session = subject.getSession();
for (final Object key : attributes.keySet())
{ session.setAttribute(key, attributes.get(key)); }
return onLoginSuccess(token, subject, request, response);
} catch (AuthenticationException e) {
return onLoginFailure(token, e, request, response);
}
}