springboog + shiro 自定义权限拦截处理
2018-07-04 本文已影响0人
咪雅先森
shiro 的自定义 filter 进行拦截先于 controller。可以实现一些常用功能,比如,验证用户是否已登陆,如果未登陆就做处理,返回json 或 重定向。
使用时发现,如果用户没有权限,不会调用 isAccessAllowed 方法。请求进来以后直接进到 preHandle 方法,可以在 preHandle 方法中做处理。
package com.reapal.openapi.web.filter;
import java.io.IOException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.alibaba.fastjson.JSONObject;
import com.reapal.openapi.common.constant.StatusEnum;
import com.reapal.openapi.web.vo.ResultVo;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.StringUtils;
import org.apache.shiro.web.filter.authz.AuthorizationFilter;
import org.apache.shiro.web.util.WebUtils;
/**
* @Type LoginFilter.java
* @Desc 用于自定义过滤器,过滤用户请求时是否是登录状态 loginFilter主要是覆盖了自带的authc过滤器,让未登录的请求统一返回401
*/
public class LoginFilter extends AuthorizationFilter {
@Override
protected boolean isAccessAllowed(ServletRequest req, ServletResponse resp, Object arg2) throws Exception {
Subject subject = getSubject(req, resp);
if (null != subject.getPrincipals()) {
return true;
}
return false;
}
/**
* 会话超时或权限校验未通过的,统一返回401,由前端页面弹窗提示
*/
@Override
protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws IOException {
if (isAjax((HttpServletRequest) request)) {
WebUtils.toHttp(response).sendError(401);
} else {
String unauthorizedUrl = getUnauthorizedUrl();
if (StringUtils.hasText(unauthorizedUrl)) {
WebUtils.issueRedirect(request, response, unauthorizedUrl);
} else {
WebUtils.toHttp(response).sendError(401);
}
}
return false;
}
private boolean isAjax(HttpServletRequest request) {
String header = request.getHeader("x-requested-with");
if (null != header && "XMLHttpRequest".endsWith(header)) {
return true;
}
return false;
}
/**
* Method: ajax 请求拦截
* Description:
* Author: liu kai
* Date: 2018/7/3 14:50
*
* @param request
* @param response
* @return boolean
*/
@Override
protected boolean preHandle(ServletRequest request, ServletResponse response) throws Exception {
HttpServletRequest httpServletRequest = (HttpServletRequest) request;
HttpServletResponse httpServletResponse = (HttpServletResponse) response;
Subject subject = SecurityUtils.getSubject();
if (isAjax(httpServletRequest)) {
if (org.apache.commons.lang3.StringUtils.contains(httpServletRequest.getRequestURI(), "/portal/admin/login")) {
return true;
}
if (subject.isAuthenticated()) {
return true;
} else {
ResultVo resultVo = new ResultVo();
//未登陆返 2033
httpServletResponse.setCharacterEncoding("UTF-8");
httpServletResponse.setContentType("application/json");
resultVo.setCode(StatusEnum.UserStatus.NO_LOGIN.getCode());
resultVo.setMsg(StatusEnum.UserStatus.NO_LOGIN.getMsg());
httpServletResponse.getWriter().write(JSONObject.toJSONString(resultVo));
return false;
}
} else {
//不是ajax进行重定向处理
// httpServletResponse.sendRedirect("/login/local");
return true;
}
}
}