创建一个类,继承自UserFilter,实现OnAccessDenied函数即可。
package io.tenglu.modules.sys.shiro;
import org.apache.shiro.web.filter.authc.UserFilter;
import org.apache.shiro.web.servlet.ShiroHttpServletRequest;
import org.springframework.stereotype.Component;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpSession;
@Component
public class SessionCheckFilter extends UserFilter {
@Override
protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
ShiroHttpServletRequest rrr = (ShiroHttpServletRequest)request;
String s = rrr.getRequestURI();
HttpSession session = rrr.getSession();
Long t1 = session.getCreationTime();
String userAgent = rrr.getHeader("User-Agent");
String sid = session.getId();
String a = rrr.getRequestedSessionId();
String b = rrr.getQueryString();
String c = rrr.getPathInfo();
Cookie d[] = rrr.getCookies();
//是APP访问
if (userAgent.indexOf("Android-APP") >= 0 || userAgent.indexOf("IOS-APP") >= 0) {
response.getWriter().write("{\"code\":\"101\",\"message\":\"token已失效,请重新登录\"}");
response.getWriter().flush();
response.getWriter().close();
}
else {//是Web访问
super.redirectToLogin (request, response);
//super.isLoginRequest(request,response)
}
return false;
}
}
添加过滤器到 setFilterChainDefinitionMap 中,系统访问时,如果session失效,访问被拒绝,则会被自定义的过滤器进行拦截。
@Bean("shiroFilter")
public ShiroFilterFactoryBean shiroFilter(SecurityManager securityManager) {
ShiroFilterFactoryBean shiroFilter = new ShiroFilterFactoryBean();
shiroFilter.setSecurityManager(securityManager);
SessionCheckFilter sessionCheckFilter = new SessionCheckFilter();
Map<String, Filter> cumstomfilterMap = new HashMap<>();
//map里面key值要为authc才能使用自定义的过滤器
cumstomfilterMap.put("user", sessionCheckFilter);
shiroFilter.setLoginUrl("/login.html");
shiroFilter.setUnauthorizedUrl("/login.html");
Map<String, String> filterMap = new LinkedHashMap<>();
filterMap.put("/swagger/**", "anon");
filterMap.put("/v2/api-docs", "anon");
filterMap.put("/swagger-ui.html", "anon");
filterMap.put("/webjars/**", "anon");
filterMap.put("/swagger-resources/**", "anon");
filterMap.put("/statics/**", "anon");
filterMap.put("/login.html", "anon");
filterMap.put("/sys/login", "anon");
filterMap.put("/sys/logoinfo","anon");
filterMap.put("/app/login", "anon");
filterMap.put("/app/logout", "anon");
filterMap.put("/app/getCaptcha", "anon");
filterMap.put("/favicon.ico", "anon");
filterMap.put("/captcha.jpg", "anon");
filterMap.put("/**", "user");
shiroFilter.setFilterChainDefinitionMap(filterMap);
shiroFilter.setFilters(cumstomfilterMap);
return shiroFilter;
}