springBoot使用过滤器进行权限认证和静态资源放行
import java.io.IOException; import java.util.HashSet; import java.util.Set; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.annotation.WebFilter; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.stereotype.Component; import com.alibaba.druid.util.StringUtils; @WebFilter(filterName = "loginFilter", value = "/*") @Component public class LoginFilter implements Filter { private static final String NAME = "x'x'x"; //header名称 private static final String ERROR = "x'x'x x'x'x"; //错误返回 private static final String VALUE = "x'x'x"; //header值 @Override public void init(FilterConfig filterConfig) throws ServletException { } @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest) servletRequest; HttpServletResponse response = (HttpServletResponse) servletResponse; String uri = request.getRequestURI();//取到你访问的资源 String loginToken = request.getHeader(NAME); //获取到对应名称header 的值
//获取请求参数attr
String attr1 = request.getParameter("attr");
if (uri.equals("/")) { //静态资源默认访问路径在/下,所以放过 filterChain.doFilter(servletRequest, servletResponse); } if (isStaticResource(uri)) { //判断是否是静态资源 filterChain.doFilter(servletRequest, servletResponse); } if (StringUtils.isEmpty(loginToken)) { //验证token有没有 response.sendError(404, ERROR); return; } if (!VALUE.equals(loginToken)) { //验证token是否正确 response.sendError(404, ERROR); return; } filterChain.doFilter(servletRequest, servletResponse); //放过 } @Override public void destroy() { } private Set<String> staticResourceTypes = new HashSet<String>(); { staticResourceTypes.add(".html"); staticResourceTypes.add(".css"); staticResourceTypes.add(".js"); staticResourceTypes.add(".png"); staticResourceTypes.add(".jpg"); staticResourceTypes.add(".otf"); staticResourceTypes.add(".eot"); staticResourceTypes.add(".svg"); staticResourceTypes.add(".ttf"); staticResourceTypes.add(".woff"); staticResourceTypes.add(".gif"); staticResourceTypes.add(".ico"); staticResourceTypes.add(".txt"); staticResourceTypes.add(".gzip"); staticResourceTypes.add(".xz"); staticResourceTypes.add(".tar.gz"); staticResourceTypes.add(".tar.bz2"); staticResourceTypes.add(".jar"); staticResourceTypes.add(".war"); staticResourceTypes.add(".7z"); staticResourceTypes.add(".tgz"); staticResourceTypes.add(".gz"); staticResourceTypes.add(".map"); } public final boolean isStaticResource(String url) { boolean result = false; if (org.apache.commons.lang3.StringUtils.isBlank(url)) { return result; } int start = url.lastIndexOf("."); if (start < 0) { return result; } String prex = url.substring(start, url.length()); return staticResourceTypes.contains(prex); } }