前言:实现账户登录、以及index不能匿名登录
效果演示:
登录账户不存在或者密码错误
登录成功可以访问index界面
当点击退出、在页面中请求http://127.0.0.1:8080/SpringShiroDemo/pages/index.jsp会被跳回到登录界面
一、首先搭建Spring和mybatis先实现基础的查找用户功能。(Spring和mybatis的搭建在这里就不说了)
dao层
通过账号名查找账户,写这一个就够了。(这个大家都会写)
二、配置自定义的Realm,需要继承AuthorizingRealm
public class UserRealm extends AuthorizingRealm {
@Autowired
private UserService userService;
/**
* 授权验证
*/
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection arg0) {
return null;
}
/**
* 登录验证
*/
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
// 账户名
String username = (String) authenticationToken.getPrincipal();
User user = userService.findUser(username);
if(user != null){
return new SimpleAuthenticationInfo(username,user.getPassword(),getName());
}else{
return null;
}
}
}
userService就是上面获取账户的实现类。此处的核心代码就是通过名字查找账户,之后通过SimpleAuthenticationInfo去验证密码。
三、配置shiro.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd
">
<!-- 定义验证规则 -->
<bean id="userRealm" class="com.waysoft.common.shiro.UserRealm"/>
<!-- securityManager -->
<bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
<property name="realm" ref="userRealm"/>
</bean>
<bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
<property name="securityManager" ref="securityManager"/>
<property name="loginUrl" value="/pages/login.jsp"/>
<property name="unauthorizedUrl" value="/err.jsp"/>
<property name="filterChainDefinitions">
<value>
/pages/index.jsp = authc
/pages/** = anon
/user/login.action = anon
</value>
</property>
</bean>
</beans>
filterChainDefinitions是最重要的验证规则,因为index.jsp是菜单页,所以必须登录才能访问。
filterChainDefinitions的配置顺序为自上而下,以最上面的为准 。
通常可将这些过滤器分为两组
anon,authc,authcBasic,user是第一组认证过滤器
perms,port,rest,roles,ssl是第二组授权过滤器
注意user和authc不同:当应用开启了rememberMe时,用户下次访问时可以是一个user,但绝不会是authc,因为authc是需要重新认证的
user表示用户不一定已通过认证,只要曾被Shiro记住过登录状态的用户就可以正常发起请求,比如rememberMe
说白了,以前的一个用户登录时开启了rememberMe,然后他关闭浏览器,下次再访问时他就是一个user,而不会authc
四、配置web.xml
通过org.springframework.web.filter.DelegatingFilterProxy设置过滤,必须注意的是,filter-name的name必须与第三步shiro.xml中配置的名字一致,否则项目启动会找不到filter
五、实现登录、退出功能