spring.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"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<!-- 1.配置 securityManager管理器-->
<bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
<!-- 缓存管理器 -->
<property name="cacheManager" ref="cacheManager"/>
<!-- 配置session的管理方式 -->
<!-- <property name="sessionMode" value="native"/> -->
<!-- <property name="realm" ref="shiroRealm"/> -->
<property name="authenticator" ref="modularRealmAuthenticator" />
<!-- 配置多个realms,必须放在authenticator属性后面 -->
<property name="realms">
<list>
<ref bean="shiroRealm" />
</list>
</property>
</bean>
<bean id="modularRealmAuthenticator" class="org.apache.shiro.authc.pam.ModularRealmAuthenticator">
<!-- 设置多个Realm的策略 -->
<property name="authenticationStrategy">
<bean class="org.apache.shiro.authc.pam.AtLeastOneSuccessfulStrategy"></bean>
</property>
</bean>
<!-- 2.配置缓存管理器,可以设置缓存 -->
<!-- 2.1 添加ehcache的jar包和配置文件 -->
<bean id="cacheManager" class="org.apache.shiro.cache.ehcache.EhCacheManager">
<!-- <property name="cacheManager" ref="ehCacheManager"/> -->
<property name="cacheManagerConfigFile" value="classpath:ehcache.xml"/>
</bean>
<!-- 3.配置实现了realm接口的bean -->
<!-- <bean id="demoshiro" class="com.znsd.shiro.demo.DemoShiro"></bean> -->
<!-- 4.配置lifecycleBeanPostProcessor,可以自动调用配置在spring中的shrio对象生命周期方法。 -->
<bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor"/>
<!-- 5.启用IOC容器中的shiro注解,但必须在配置 lifecycleBeanPostProcessor 后才会生效。-->
<bean class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator"
depends-on="lifecycleBeanPostProcessor"/>
<bean class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor">
<property name="securityManager" ref="securityManager"/>
</bean>
<!-- 添加自定义的Relm规则 -->
<bean id="shiroRealm" class="com.znsd.shiro.demo.DemoShiro">
<property name="credentialsMatcher">
<bean class="org.apache.shiro.authc.credential.HashedCredentialsMatcher">
<!-- 指定使用MD5加密方式加密前台密码 -->
<property name="hashAlgorithmName" value="MD5" />
<!-- 指定使用MD5加密的次数 -->
<property name="hashIterations" value="10" />
</bean>
</property>
</bean>
<!--
6.配置shiroFilter过滤器相关的属性。
6.1 id必须 和web.xml中配置的filter-name一致。
-->
<bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
<property name="securityManager" ref="securityManager"/>
<property name="loginUrl" value="/login"/>
<property name="successUrl" value="/admin/index"/>
<property name="unauthorizedUrl" value="/unauthorized"/>
<!--
配置哪些页面需要被保护,以及访问该页面所需要的权限。
anon: 表示可以匿名访问。
authc:表示需要登录之后才可以访问。
-->
<property name="filterChainDefinitions">
<value>
/loginpost=anon
/index=roles[admin]
/login = anon
/index.jsp = anon
/loginout=logout
/** = authc
</value>
</property>
</bean>
</beans>
实现了realm接口
public class DemoShiro extends AuthorizingRealm{
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
//①、把AuthenticationToken转换为UsernamePasswordToken。
UsernamePasswordToken upToken = (UsernamePasswordToken) token;
//②、从UsernamePasswordToken中获取username
String username = upToken.getUsername();
//③、调用数据库的方法,从数据库中查询username对应的记录。
UserService userService = new UserService();
User user = userService.login(username);
//④、若用户不存在,则可以跑出UnknownAccountException异常。
if(user == null) {
throw new UnknownAccountException("用户不存在.");
}
//⑤、根据用户信息的情况,决定是否需要抛出其它AuthenticationException异常。
if(user.isIslock()) {
throw new LockedAccountException("用户被锁定");
}
//⑥、根据用户的情况,来构建AuthenticationInfo对象并返回。
AuthenticationInfo info = new SimpleAuthenticationInfo(user.getName(), user.getPass(), this.getName());
return info;
}
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
System.out.println(123321+"__________");
// 授权方法的步骤:
// 1、从PrincipalCollection中来获取登录用户的信息。
String username = (String) principals.getPrimaryPrincipal();
System.out.println(username);
// 2、利用登录用户的信息来验证当前用户的角色或者权限。
Set<String> roles = new HashSet<>();
roles.add("user");
if ("admin".equals(username)) {
roles.add("admin");
System.out.println("admin权限");
}
// 3、创建SimpleAuthorizationInfo,并设置其roles属性。
SimpleAuthorizationInfo info = new SimpleAuthorizationInfo(roles);
// 4、返回SimpleAuthorizationInfo对象
return info;
}
/*@Test
public void test() {
SimpleHash sh=new SimpleHash("MD5","123123",null,10);
System.out.println(sh);
}*/
}
doGetAuthenticationInfo()方法是用来判定权限是否足够
doGetAuthorizationInfo()方法是添加权限的
在控制层判定密码是否正确
@RequestMapping(value = "/loginpost" , method = RequestMethod.POST)
public String loginpost(User user) {
//获取当前的Subject
Subject currentUser = SecurityUtils.getSubject();
// 测试当前用户是否已经被认证,即是否已经登录。
if (!currentUser.isAuthenticated()) {
// 把用户名和密码封装为UsernamePasswordToken对象
UsernamePasswordToken token
= new UsernamePasswordToken(user.getName(), user.getPass());
// 记住密码
token.setRememberMe(true);
try {
// 执行登录
currentUser.login(token); //实际上调用Realm中的doGetAuthenticationInfo方法
System.out.println("login");
return "redirect:/index";
} catch (UnknownAccountException e) { // 其他异常,是其他异常的父类
System.err.println("用户不存在");
}catch(LockedAccountException e) {
System.err.println("账户锁定");
}catch(IncorrectCredentialsException e) {
System.err.println("密码不正确");
}catch (AuthenticationException ae) {
System.out.println("权限不组");
}
}
return "login";
}
web.xml配置
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
id="WebApp_ID" version="3.1">
<display-name>shiro</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<!-- spring配置文件 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- SpringMVC的配置文件 -->
<servlet>
<servlet-name>springDispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springmvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springDispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<!-- 添加shiro过滤器,用来拦截shiro请求 -->
<filter>
<filter-name>shiroFilter</filter-name>
<filter-class>
org.springframework.web.filter.DelegatingFilterProxy
</filter-class>
<init-param>
<param-name>targetFilterLifecycle</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>shiroFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>