只需要认证,直接继承AuthenticatingRealm 类就可以了
package com.atguigu.shiro.realms;import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.realm.AuthenticatingRealm;/*** * @author Lee**/
public class ShiroRealm extends AuthenticatingRealm {private static final String MONSTER = "monster";private static final String UNKNOW = "unknow";@Overrideprotected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {// 1、将AuthenticationToken转换为UsernamePasswordTokenUsernamePasswordToken upToken = (UsernamePasswordToken) token;// 2、从UsernamePasswordToken中获取usernameString username = upToken.getUsername();
// char[] password = upToken.getPassword();// 3、从数据库中获取username对应的记录System.out.println("从数据库中查找" + username + "对应的记录");// 4、若用户不存在抛出UnknownAccountException异常if (UNKNOW.equals(username)) {throw new UnknownAccountException("用户不存在");}// 5、根据用户的信息决定是否抛出AuthenticationException异常if (MONSTER.equals(username)) {throw new LockedAccountException("用户被锁定");}// 6、根据用户情况,构建 AuthenticationInfo 对象并返回// 一下信息是从数据库中获取// 1)principal:认证的实体信息,可以是username,也可以是数据表对应的用户的实体类对象。Object principal = username;// 2) credentials:密码Object credentials = "123456";// 3) realmName:当前realm对象的name,调用父类的getName()方法获取String realmName = getName();SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(principal, credentials, realmName);return info;}}
如果登陆成功后,之后在进行认证会从缓冲中直接获取,不会经过Realm,所以若需要重新登陆,需要先登出,再进行登陆。
登出有登出的过滤器,直接配置登出的URL使用即可
<bean id="shiroFilter"class="org.apache.shiro.spring.web.ShiroFilterFactoryBean"><property name="securityManager" ref="securityManager" /><property name="loginUrl" value="/login.jsp" /><property name="successUrl" value="/list.jsp" /><property name="unauthorizedUrl" value="/unauthorized.jsp" /><!-- 配置哪些页面需要保护以及访问页面的权限拦截器:(这里的url支持Ant风格模式)1).anon 可以被匿名访问2) .authc 需要认证才能访问3) .logout 登出过滤器这里的url优先匹配--><property name="filterChainDefinitions"><value>/login.jsp = anon/shiro/login = anon/shiro/logout = logout# everything else requires authentication:/** = authc/list.jsp = anon</value></property></bean>