版本:
- Spring Boot 1.5.4.RELEASE
- Shiro 1.4.0
問(wèn)題
當(dāng)session超時(shí)后巍举,發(fā)起Ajax請(qǐng)求(查詢更新表格內(nèi)容)逸绎,頁(yè)面沒(méi)有跳轉(zhuǎn)到登陸畫面判导。
原因
因?yàn)槭褂昧薙hiro稽亏,默認(rèn)的“authc”是FormAuthenticationFilter
過(guò)濾器,該類中的onAccessDenied方法如下富俄,從中可以看出:當(dāng)訪問(wèn)被拒检号,并且不是登錄請(qǐng)求時(shí),會(huì)重定向(302)到登錄URL蛙酪。
protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
if (isLoginRequest(request, response)) {
if (isLoginSubmission(request, response)) {
if (log.isTraceEnabled()) {
log.trace("Login submission detected. Attempting to execute login.");
}
return executeLogin(request, response);
} else {
if (log.isTraceEnabled()) {
log.trace("Login page view.");
}
//allow them to see the login page ;)
return true;
}
} else {
if (log.isTraceEnabled()) {
log.trace("Attempting to access a path which requires authentication. Forwarding to the " +
"Authentication url [" + getLoginUrl() + "]");
}
// 這里重定向到登錄畫面
saveRequestAndRedirectToLogin(request, response);
return false;
}
}
如果不是Ajax請(qǐng)求齐苛,是沒(méi)有問(wèn)題的,瀏覽器可以正常跳轉(zhuǎn)到登陸畫面桂塞。如果是jQuery Ajax請(qǐng)示凹蜂,則ajaxComplete事件最終拿到的response status是redirect之后的status,即訪問(wèn)登陸畫面后的響應(yīng)狀態(tài)200阁危。
解決方法
重寫FormAuthenticationFilter
類的onAccessDenied方法玛痊,并判斷如果請(qǐng)求是ajax請(qǐng)求,就在header中添加一個(gè)需要登錄的標(biāo)識(shí)狂打,并且設(shè)置response status為401擂煞,避免還是200而繼續(xù)走ajax的成功回調(diào)。然后Ajax添加全局事件趴乡,當(dāng)有需要登錄的標(biāo)識(shí)時(shí)对省,將頁(yè)面定位到登錄畫面蝗拿。
重寫FormAuthenticationFilter
public class MyShiroAuthcFilter extends FormAuthenticationFilter {
public MyShiroAuthcFilter() {
super();
}
@Override
protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
if (isLoginRequest(request, response)) {
return super.onAccessDenied(request, response);
} else {
if (isAjax((HttpServletRequest) request)) {
HttpServletResponse httpServletResponse = WebUtils.toHttp(response);
httpServletResponse.addHeader("REQUIRE_AUTH", "true");
httpServletResponse.setStatus(HttpStatus.UNAUTHORIZED.value());
} else {
saveRequestAndRedirectToLogin(request, response);
}
return false;
}
}
private boolean isAjax(HttpServletRequest request) {
String requestedWithHeader = request.getHeader("X-Requested-With");
return "XMLHttpRequest".equals(requestedWithHeader);
}
}
配置重寫后的filter
@Configuration
public class ShiroConfig {
@Bean
public SpringTemplateEngine templateEngine(ITemplateResolver templateResolver) {
SpringTemplateEngine engine = new SpringTemplateEngine();
engine.setTemplateResolver(templateResolver);
final ShiroDialect dialect = new ShiroDialect();
engine.addDialect(dialect);
return engine;
}
// @Bean
// public HashedCredentialsMatcher hashedCredentialsMatcher(){
// HashedCredentialsMatcher credentialsMatcher = new HashedCredentialsMatcher();
// credentialsMatcher.setHashAlgorithmName("SHA1");
// credentialsMatcher.setHashIterations(5);
// credentialsMatcher.setStoredCredentialsHexEncoded(true);
// return credentialsMatcher;
// }
@Bean
public MyShiroRealm myShiroRealm() {
MyShiroRealm myShiroRealm = new MyShiroRealm();
// myShiroRealm.setCredentialsMatcher(hashedCredentialsMatcher);
return myShiroRealm;
}
@Bean
public EhCacheManager ehCacheManager() {
EhCacheManager cacheManager = new EhCacheManager();
return cacheManager;
}
@Bean
public SecurityManager securityManager(MyShiroRealm myShiroRealm) {
DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager(myShiroRealm);
securityManager.setCacheManager(ehCacheManager());
securityManager.getSessionManager();
return securityManager;
}
// @Bean
// public MyShiroAuthcFilter myShiroAuthcFilter() {
// MyShiroAuthcFilter myShiroAuthcFilter = new MyShiroAuthcFilter();
// return myShiroAuthcFilter;
// }
@Bean
public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(SecurityManager securityManager) {
AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor = new AuthorizationAttributeSourceAdvisor();
authorizationAttributeSourceAdvisor.setSecurityManager(securityManager);
return authorizationAttributeSourceAdvisor;
}
@Bean
public ShiroFilterFactoryBean shirFilter(SecurityManager securityManager) {
ShiroFilterFactoryBean filter = new ShiroFilterFactoryBean();
filter.setSecurityManager(securityManager);
filter.setLoginUrl("/login");
filter.setSuccessUrl("/index");
filter.setUnauthorizedUrl("/403");
filter.setUnauthorizedUrl("/404");
filter.setUnauthorizedUrl("/500");
Map<String, Filter> filters = filter.getFilters();
// filters.put("authd", myShiroAuthcFilter());
// 注意這里不要用Bean的方式,否則會(huì)報(bào)錯(cuò)
filters.put("authd", new MyShiroAuthcFilter());
filters.put("anon", new AnonymousFilter());
filters.put("logout", new LogoutFilter());
filter.setFilters(filters);
Map<String, String> filterChainDefinitionMap = new LinkedHashMap<>();
filterChainDefinitionMap.put("/resources/**", "anon");
filterChainDefinitionMap.put("/loginSubmit", "anon");
filterChainDefinitionMap.put("/logout", "logout");
filterChainDefinitionMap.put("/**", "authd");
filter.setFilterChainDefinitionMap(filterChainDefinitionMap);
return filter;
}
@Bean
public LifecycleBeanPostProcessor lifecycleBeanPostProcessor() {
return new LifecycleBeanPostProcessor();
}
}
Ajax全局事件
$(document).ready(function() {
// 解決session超時(shí)蒿涎,Ajax請(qǐng)求頁(yè)面不跳轉(zhuǎn)的問(wèn)題
$(document).ajaxComplete(function(event, xhr, settings) {
if (xhr.getResponseHeader('REQUIRE_AUTH') === 'true') {
window.location.href = ctx + "/index";
}
});
});
參考:
https://stackoverflow.com/questions/30461823/spring-mvc-detect-ajax-request
https://stackoverflow.com/questions/199099/how-to-manage-a-redirect-request-after-a-jquery-ajax-call
http://shiro-user.582556.n2.nabble.com/redirect-302-Found-td5769710.html
https://blog.csdn.net/callmesong/article/details/78826696
http://shiro-user.582556.n2.nabble.com/Session-Timeout-doesn-t-redirect-to-login-page-td7577730.html
http://shiro-user.582556.n2.nabble.com/Web-Filter-to-return-HTTP-status-code-td7577672.html