1.创建一个类继承PermissionsAuthorizationFilter
public class AiSellPermissionsAuthorizationFilter extends PermissionsAuthorizationFilter {
@Override
protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws IOException {
Subject subject = this.getSubject(request, response);
if (subject.getPrincipal() == null) {
this.saveRequestAndRedirectToLogin(request, response);
} else {
// 强转为HTTP
HttpServletRequest req = (HttpServletRequest) request;
HttpServletResponse resp = (HttpServletResponse)response;
// 获取响应头中ajax
String header = req.getHeader("X-Requested-With");
// 如果是ajax请求
if ("XMLHttpRequest".equals(header)){
// 设置响应头
resp.setContentType("application/json;charset=UTF-8");
resp.getWriter().print(false);
}
String unauthorizedUrl = this.getUnauthorizedUrl();
if (StringUtils.hasText(unauthorizedUrl)) {
WebUtils.issueRedirect(request, response, unauthorizedUrl);
} else {
WebUtils.toHttp(response).sendError(401);
}
}
return false;
}
}
2.配置applicationContext-shiro.xml
<!-- 真正实现权限的过滤器 它的id名称和web.xml中的过滤器名称一样 -->
<bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
<!--shiro核心对象-->
<property name="securityManager" ref="securityManager"/>
<!--如果没有登录进入 value 页面-->
<property name="loginUrl" value="/login"/>
<!--如果登录成功进入 value 页面-->
<property name="successUrl" value="/aisell"/>
<!--如果没有权限进入 value 页面-->
<property name="unauthorizedUrl" value="/s/unauthorized"/>
<!--配置拦截路径-->
<property name="filterChainDefinitionMap" ref="map" />
<!--shiro自定义过滤器-->
<property name="filters">
<map>
<!--自定义过滤器名字aiPerms-->
<entry key="aiPerms" value-ref="aiSellPermissionsAuthorizationFilter"/>
</map>
</property>
</bean>
<!--调用permsMap中的方法获取Map-->
<bean id="map" factory-bean="permsMap" factory-method="perms" />
<!--配置bean-->
<bean id="permsMap" class="cn.meco.aisell.shiro.PermsMap" />
<!--shiro自定义过滤器-->
<bean id="aiSellPermissionsAuthorizationFilter" class="cn.meco.aisell.shiro.AiSellPermissionsAuthorizationFilter"/>
3.修改过滤器配置
修改为第二步中自定义的过滤器名字(aiPerms)
public class PermsMap {
@Autowired
private IPermissionService permissionService;
public Map<String, String> perms() {
// LinkedHashMap有序Map
LinkedHashMap<String, String> permsMap = new LinkedHashMap<>();
// 登录放行
permsMap.put("/login", "anon");
permsMap.put("/WEB-INF/views/login/**", "anon");
// 静态资源放行
permsMap.put("*.js", "anon");
permsMap.put("*.css", "anon");
permsMap.put("/css/**", "anon");
permsMap.put("/js/**", "anon");
permsMap.put("/easyui/**", "anon");
permsMap.put("/images/**", "anon");
permissionService.findAll().forEach(permission -> {
permsMap.put(permission.getUrl(), "aiPerms[" + permission.getSn() + "]");
});
// 需要登录后才能访问
permsMap.put("/**", "authc");
return permsMap;
}
}