FormAuthenticationFilter无效的解决方案

我们在登录的时候,如果用户名为username,密码为password,那么我们可以不用自己写登录的代码,FormAuthenticationFilter这个过滤器会自动帮我们进行登陆验证。在测试shiro框架的时候,也都没问题。

但是后来在实际项目开发中,突然发现FormAuthenticationFilter不起作用了,后来才发现原因:在测试的时候,filterChainDefinitions中配置了/** = authc ,表示所有访问地址都有经过FormAuthenticationFilter过滤,但是在实际项目的时候,并没有这么配置,因此失效了。

解决方案:filterChainDefinitions下配置加上/login = authc,此处的/login就是你登录的时候表单提交的路径。

提示:authc表示使用FormAuthenticationFilter来过滤

抱歉,我之前的回答有误。在SSM + Shiro框架中,你可以继承`FormAuthenticationFilter`,并重写`onAccessDenied()`方法来实现免登录功能。以下是修改后的示例代码: ```java public class CustomAuthenticationFilter extends FormAuthenticationFilter { @Override protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception { HttpServletRequest httpServletRequest = (HttpServletRequest) request; HttpServletResponse httpServletResponse = (HttpServletResponse) response; // 从Cookie中获取sessionId String sessionId = null; Cookie[] cookies = httpServletRequest.getCookies(); if (cookies != null) { for (Cookie cookie : cookies) { if ("sessionId".equals(cookie.getName())) { sessionId = cookie.getValue(); break; } } } // 从Redis中获取账号密码 Jedis jedis = new Jedis("redis_host", redis_port); String password = jedis.get(sessionId); // 调用Shiro的登录方法进行认证 UsernamePasswordToken token = new UsernamePasswordToken(sessionId, password); Subject subject = SecurityUtils.getSubject(); try { subject.login(token); return true; // 认证成功,继续访问原请求页面 } catch (AuthenticationException e) { return false; // 认证失败,重定向到登录页面 } } } ``` 然后,在Shiro配置文件中将自定义过滤器添加到过滤器链中,如下所示: ```xml <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean"> <!-- ...其他配置... --> <property name="filters"> <map> <!-- ...其他过滤器配置... --> <entry key="authc"> <bean class="com.example.CustomAuthenticationFilter"> <!-- 设置登录页的URL --> <property name="loginUrl" value="/login"/> </bean> </entry> <entry key="user"> <bean class="org.apache.shiro.web.filter.authc.UserFilter"/> </entry> </map> </property> <property name="filterChainDefinitions"> <value> /login = anon /logout = logout /** = user </value> </property> </bean> ``` 通过以上步骤,在拦截器中重写`onAccessDenied()`方法,实现从Cookie中获取sessionId并从Redis中获取账号密码进行Shiro认证。如果认证成功,用户将继续访问原请求页面,否则将重定向到登录页面。 请注意,在实际生产环境中,你需要根据具体情况对Cookie和Redis进行适当的安全性加固和保护。同时,以上代码仅为示例,你可以根据实际需求进行适当调整和扩展。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值