解决shiro自定义filter后,ajax登录无法登录,并且无法显示静态资源的问题
这个问题困扰了我一天,看了下面两个文章,豁然开朗:
https://www.cnblogs.com/gj1990/p/8057348.html
https://412887952-qq-com.iteye.com/blog/2392741
按照如下方法即可解决无法显示静态资源问题:
一、让springboot拦截器来接管静态资源,同时在shiroconfig中通过new方式注册过滤器
1、代码一
import java.util.Arrays; import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; /**
* SpringBoot管理器
*/
@Configuration
public class WebMvcConfiguration implements WebMvcConfigurer { private final Logger logger = LoggerFactory.getLogger(WebMvcConfiguration.class); @Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new LoginRequiredInterceptor()).excludePathPatterns(Arrays.asList("/css/**", "/js/**","/img/**","/fonts/**"));
}
}
2、代码二
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter; /**
* 登录拦截器
*
*
*/
public class LoginRequiredInterceptor extends HandlerInterceptorAdapter { private final Logger logger = LoggerFactory.getLogger(LoginRequiredInterceptor.class); @Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
logger.info(request.getRequestURI());
return super.preHandle(request, response, handler);
} @Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
throws Exception {
logger.info(request.getRequestURI());
super.afterCompletion(request, response, handler, ex);
}
}
三、shiro配置中使用new方式生成filter
filters.put("authc", new ExtendFormAuthenticationFilter());
filterChainDefinitionMap.put("/**", "user,authc");
四、自定义filter
import com.simon.common.util.R;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter; public class ExtendFormAuthenticationFilter extends FormAuthenticationFilter { private static final Logger log = LoggerFactory.getLogger(FormAuthenticationFilter.class); /**
* 表示当访问拒绝时是否已经处理了;如果返回true表示需要继续处理;如果返回false表示该拦截器实例已经处理了,将直接返回即可。
* onAccessDenied是否执行取决于isAccessAllowed的值,如果返回true则onAccessDenied不会执行;如果返回false,执行onAccessDenied
* 如果onAccessDenied也返回false,则直接返回,不会进入请求的方法(只有isAccessAllowed和onAccessDenied的情况下)
* */ @Override
protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception { if(this.isLoginRequest(request, response)) {
if(this.isLoginSubmission(request, response)) {
if(log.isTraceEnabled()) {
log.trace("Login submission detected. Attempting to execute login.");
} return this.executeLogin(request, response);
} else {
if(log.isTraceEnabled()) {
log.trace("Login page view.");
} return true;
}
} else {
if(log.isTraceEnabled()) {
log.trace("Attempting to access a path which requires authentication. Forwarding to the Authentication url [" + this.getLoginUrl() + "]");
} this.saveRequestAndRedirectToLogin(request, response);
return false;
}
} /** * 当登录成功 * @param token * @param subject * @param request * @param response * @return * @throws Exception */
@Override
protected boolean onLoginSuccess(AuthenticationToken token, Subject subject, ServletRequest request, ServletResponse response) throws Exception { HttpServletRequest httpServletRequest = (HttpServletRequest) request;
HttpServletResponse httpServletResponse = (HttpServletResponse) response; if (!"XMLHttpRequest".equalsIgnoreCase(httpServletRequest
.getHeader("X-Requested-With"))) {// 不是ajax请求
issueSuccessRedirect(request, response);
} else {
httpServletResponse.setCharacterEncoding("UTF-8");
PrintWriter out = httpServletResponse.getWriter(); //out.println("{\"success\":true,\"message\":\"登入成功\"}");
out.println(R.ok());
out.flush();
out.close();
}
return false;
} /** * 当登录失败 * @param token * @param e * @param request * @param response * @return */
@Override
protected boolean onLoginFailure(AuthenticationToken token, AuthenticationException e, ServletRequest request, ServletResponse response) {
if (!"XMLHttpRequest".equalsIgnoreCase(((HttpServletRequest) request)
.getHeader("X-Requested-With"))) {// 不是ajax请求
setFailureAttribute(request, e);
return true;
}
try {
response.setCharacterEncoding("UTF-8");
PrintWriter out = response.getWriter();
String message = e.getClass().getSimpleName();
if ("IncorrectCredentialsException".equals(message)) {
out.println("{\"success\":false,\"message\":\"密码错误\"}");
} else if ("UnknownAccountException".equals(message)) {
out.println("{\"success\":false,\"message\":\"账号不存在\"}");
} else if ("LockedAccountException".equals(message)) {
out.println("{\"success\":false,\"message\":\"账号被锁定\"}");
} else {
out.println("{\"success\":false,\"message\":\"未知错误\"}");
}
out.flush();
out.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
return false;
}
} 第二种方式就是“取消Filter自动注册,不会添加到FilterChain中“,方法如下:
一、定义过滤器,如上第四步
二、在shiroconfig中声明自定义FormAuthenticationFilter
@Bean
public ExtendFormAuthenticationFilter getLoginAdviceFilter(){
ExtendFormAuthenticationFilter filter=new ExtendFormAuthenticationFilter();
filter.setRememberMeParam("username");
filter.setPasswordParam("password");
//对应前端的checkbox的name = rememberMe
filter.setRememberMeParam("rememberMe");
filter.setLoginUrl(loginUrl);
return filter;
}
三、取消注册
@Bean
public FilterRegistrationBean registrationBean(ExtendFormAuthenticationFilter customFormAuthenticationFilter){
FilterRegistrationBean registration = new FilterRegistrationBean(customFormAuthenticationFilter);
registration.setEnabled(false);//怎么取消 Filter自动注册,不会添加到FilterChain中.
return registration;
}
通过以上步骤就实现了解决shiro自定义filter后,ajax登录无法登录,并且无法显示静态资源的问题
解决shiro自定义filter后,ajax登录无法登录,并且无法显示静态资源的问题的更多相关文章
- shiro 自定义filter
1.自定义登录filter package com.creatunion.callcenter.filter; import com.alibaba.fastjson.JSONObject; impo ...
- Shiro自定义realm实现密码验证及登录、密码加密注册、修改密码的验证
一:先从登录开始,直接看代码 @RequestMapping(value="dologin",method = {RequestMethod.GET, RequestMethod. ...
- shiro session过期后ajax请求跳转(转)
配置了 Shrio框架,session也集成进去了 ,发现问题session会话过期,点击页面,一直请求失败.本来想集成拦截器,过滤器,但是已经用了shiro框架,sessionDestroyed 方 ...
- 解决validaform先验证后 ajax提交
$(".myfroms").Validform({//form class btnSubmit:".submitLayer", 绑定提交按钮 tiptype:4 ...
- web项目中url-pattern改成'/'后,js、css、图片等静态资源(404)无法访问问题解决办法
感谢http://blog.csdn.net/this_super/article/details/7884383的文章 1.增加静态资源url映射 如Tomcat, Jetty, JBoss, Gl ...
- web项目中url-pattern改成'/'后,js、css、图片等静态资源(404)无法访问问题解决办法
感谢http://blog.csdn.net/this_super/article/details/7884383的文章 1.增加静态资源url映射 如Tomcat, Jetty, JBoss, Gl ...
- 解决Shiro+SpringBoot自定义Filter不生效问题
在SpringBoot+Shiro实现安全框架的时候,自定义扩展了一些Filter,并注册到ShiroFilter,但是运行的时候发现总是在ShiroFilter之前就进入了自定义Filter,结果当 ...
- shiro 返回json字符串 + 自定义filter
前言: 在前后端分离的项目中, 在使用shiro的时候, 我们绝大部分时候, 并不想让浏览器跳转到那个页面去, 而是告诉前端, 你没有登录, 或者没有访问权限. 那这时候, 我们就需要返回json字符 ...
- Shiro权限管理框架(五):自定义Filter实现及其问题排查记录
明确需求 在使用Shiro的时候,鉴权失败一般都是返回一个错误页或者登录页给前端,特别是后台系统,这种模式用的特别多.但是现在的项目越来越多的趋向于使用前后端分离的方式开发,这时候就需要响应Json数 ...
随机推荐
- go微服务框架kratos学习笔记四(kratos warden-quickstart warden-direct方式client调用)
目录 go微服务框架kratos学习笔记四(kratos warden-quickstart warden-direct方式client调用) warden direct demo-server gr ...
- Gitlab安装配置管理
◆安装Gitlab前系统预配置准备工作1.关闭firewalld防火墙# systemctl stop firewalld# systemctl disable firewalld 2.关闭SELIN ...
- stormzhangB站直播之总结
此文转自个人微信公众号,原链接为:https://mp.weixin.qq.com/s?__biz=MzUxODk0ODQ3Ng==&mid=2247484313&idx=1& ...
- crawler碎碎念5 豆瓣爬取操作之登录练习
import requests import html5lib import re from bs4 import BeautifulSoup s = requests.Session() #这里要提 ...
- 2019CSP初赛游记
Day 0 作为一个初三的小蒟蒻…… 对于J+S两场比赛超级紧张的…… 教练发的神奇的模拟卷…… 我基本不会…… 就这样吧…… Day 1 Morning 不知道怎么就进了考场…… 周围坐的全是同学( ...
- 关于MySQL5.6配置文件my-default.ini不生效问题
一.问题描述 首先,由于工作要求,需使用MySQL5.6版本(绿色版),从解压到修改root密码,一切都很顺利,但是在我要修改mysql的最大连接数的时候,出现问题了,配置不生效.完蛋.还好有万能的百 ...
- laravel 学习笔记 — 神奇的服务容器
2015-05-05 14:24 来自于分类 笔记 Laravel PHP开发 竟然有人认为我是抄 Laravel 学院的,心塞.世界观已崩塌. 容器,字面上理解就是装东西的东西.常见的变量.对象属 ...
- SpringBoot+MyBatis项目Dao层最简单写法
前言 DAO(Data Access Object) 是数据访问层,说白了就是跟数据库打交道的,而数据库都有哪几种操作呢?没错,就是增删改查.这就意味着Dao层要提供增删改查操作. 不知道大家是怎么写 ...
- vue项目使用keep-alive
作用: 在vue项目中,难免会有列表页面或者搜索结果列表页面,点击某个结果之后,返回回来时,如果不对结果页面进行缓存,那么返回列表页面的时候会回到初始状态,但是我们想要的结果是返回时这个页面还是之前搜 ...
- 浏览器无法进入GitHub(已解决)
时间:2020/1/22 今天突然chrome登不上GitHub,一直出现响应时间过长的问题,如下: 开始还以为是GitHub服务器出问题了(虽然概率很小.....),但这种情况一直持续了几个小时,我 ...