所谓的Shiro认证,其实就是用户登录。控制某些页面登录可见,不登录则自动重定向到登录页面。
一、导入项目所需要的jar
二、配置web.xml
在web.xml中需要配置spring和springmvc以及shiro。
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>shiro-2</display-name>
<!-- 配置spring环境 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- 配置springmvc -->
<servlet>
<servlet-name>spring</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-mvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<!-- Shiro Filter is defined in the spring application context: -->
<!--
1、配置Shiro 的 ShiroFilter
2、DelegatingFilterProxy 实际上是一Filter的一个代理对象,默认情况下,Spring会到IOC容器中查找
和filter-name 对应的filter bean,也可以通过targetBeanName的初始化参数来配置Filter Bean的Id
-->
<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>
三、配置springmvc.xml
主要配置了URL前后缀和注解扫描。
<?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:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
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
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">
<context:component-scan base-package="com.mfc"></context:component-scan>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
<mvc:annotation-driven></mvc:annotation-driven>
<mvc:default-servlet-handler/>
</beans>
四、配置applicationContext.xml
配置shiro,在这里直接模拟了两个用户,并没有连接数据库进行取值验证。
<?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:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
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
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">
<!--
1、配置securityManager
-->
<bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
<property name="cacheManager" ref="cacheManager"/>
<property name="authenticator" ref="authenticator"/>
</bean>
<!--
2、配置cacheManager
2.1、需要加入ehcache的jar包及配置文件
-->
<bean id="cacheManager" class="org.apache.shiro.cache.ehcache.EhCacheManager">
<property name="cacheManagerConfigFile" value="classpath:ehcache.xml"/>
</bean>
<!--
3、配置Realm
3.1、直接配置实现了org.apache.shiro.realm.Realm接口的bean
-->
<bean id="authenticator" class="org.apache.shiro.authc.pam.ModularRealmAuthenticator">
<property name="realms">
<list>
<ref bean="jdbcRealm"/>
<ref bean="secondRealm"/>
</list>
</property>
<!--
配置认证策略 :
"FirstSuccessfulStrategy":只要有一个Realm验证成功即可,其他Realm忽略,只返回第一个验证陈宫的Realm身份验证成功的认证信息
"AtLeastOneSuccessfulStrategy":只要有一个Realm验证成功即可,返回所有Realm身份验证成功的认证信息
"AllSuccessfulStrategy":所有的Realm验证成功才算成功,且返回所有Realm身份验证成功的认证信息,如果有一个失败了就算是失败了
-->
<property name="authenticationStrategy">
<bean class="org.apache.shiro.authc.pam.AllSuccessfulStrategy"></bean>
</property>
</bean>
<bean id="jdbcRealm" class="com.mfc.realm.ShiroRealm">
<property name="credentialsMatcher">
<bean class="org.apache.shiro.authc.credential.HashedCredentialsMatcher">
<property name="hashAlgorithmName" value="MD5"></property>
<property name="hashIterations" value="1024"></property>
</bean>
</property>
</bean>
<bean id="secondRealm" class="com.mfc.realm.SecondRealm">
<property name="credentialsMatcher">
<bean class="org.apache.shiro.authc.credential.HashedCredentialsMatcher">
<property name="hashAlgorithmName" value="SHA1"></property>
<property name="hashIterations" value="1024"></property>
</bean>
</property>
</bean>
<!--
4、配置lifecycleBeanPostProcessor,可以自动的来调用配置在Spring IOC 容器中的shiro bean的生命周期方法
-->
<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>
<!--
6、配置shiroFilter
6.1、id必须和web.xml中的配置的DelegatingFilterProxy的<filter-name>的值一致
若不一致会抛出异常NoSuchBeanDefinitionException。因为shiro会来IOC容器中查找和<filter-name>名字对应的filter bean
-->
<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匹配模式:
?:匹配一个字符。如/admin将匹配/admin1,但不匹配/admin或/admin/
*:匹配0个或多个字符串。如/admin*将匹配/admin、/admin123,但不匹配/admin/1
**:匹配路径中的零个或多个路径。如/admin/**将匹配/admin/a或admin/a/b
配置哪些页面需要受保护,以及访问这些页面需要的权限,这里的URL权限采取第一次匹配优先的方式
1、anon 可以被匿名访问
2、authc 必须认证(即登录)后才可以访问的页面
3、logout 注销
-->
<property name="filterChainDefinitions">
<value>
/login.jsp = anon
/shiroCtrl/login = anon
/shiroCtrl/logout = logout
# everything else requires authentication:
/** = authc
</value>
</property>
</bean>
</beans>
五、Realm:
Realm:域,Shiro 从从Realm获取安全数据(如用户、角色、权限),就是说SecurityManager要验证用户身份,那么它需要从Realm获取相应的用户进行比较以确定用户身份是否合法;
也需要从Realm得到用户相应的角色/权限进行验证用户是否能进行操作;可以把Realm看成DataSource , 即安全数据源。
ShiroRealm.java:
package com.mfc.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.crypto.hash.SimpleHash;
import org.apache.shiro.realm.AuthenticatingRealm;
import org.apache.shiro.util.ByteSource;
public class ShiroRealm extends AuthenticatingRealm {
@Override
protected AuthenticationInfo doGetAuthenticationInfo(
AuthenticationToken token) throws AuthenticationException {
System.out.println("[FirstRealm] doGetAuthenticationInfo");
//1、把AuthenticationToken 转换为UsernamePasswordToken
UsernamePasswordToken upToken = (UsernamePasswordToken) token;
//2、从UsernamePasswordToken 中获取username
String username = upToken.getUsername();
//3、调用数据库方法,从数据库中查询username 对应的用户记录
System.out.println("从数据库中获取username:" + username + " 所对应的用户信息");
//4、若用户不存在,则可以抛出UnknowAccountException异常
if("unknow".equals(username)){
throw new UnknownAccountException("影虎不存在");
}
//5、根据用户的信息情况,决定是否需要抛出其他的AuthenticationException异常
if("monster".equals(username)){
throw new LockedAccountException("用户被锁定");
}
//6、根据用户的情况,来构建AuthenticationInfo对象并返回,通常使用实现类是SimpleAuthenticationInfo
//以下信息是从数据库中获取的
//1、principal:认证的实体信息,可以使username,也可以是数据表对应的用户的实体类对象
Object principal = username;
//2、credentials:密码
Object credentials = null; //fc1709d0a95a6be30bc5926fdb7f22f4
if("admin".equals(username)){
credentials = "038bdaf98f2037b31f1e75b5b4c9b26e";
}else if("user".equals(username)){
credentials = "098d2c478e9c11555ce2823231e02ec1";
}
//3、realmName:当前realm对象的name,调用父类的getName()即可
String realmName = getName();
//4、盐值
ByteSource credentialsSalt = ByteSource.Util.bytes(username);
SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(principal, credentials, credentialsSalt, realmName);
return info;
}
public static void main(String[] args) {
String algorithmName = "MD5";
Object source = "123456";
Object salt = ByteSource.Util.bytes("user");
int hashIterations = 1024;
Object result = new SimpleHash(algorithmName, source, salt, hashIterations);
System.out.println(result);
}
}
SecondRealm.java:
package com.mfc.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.crypto.hash.SimpleHash;
import org.apache.shiro.realm.AuthenticatingRealm;
import org.apache.shiro.util.ByteSource;
public class SecondRealm extends AuthenticatingRealm {
@Override
protected AuthenticationInfo doGetAuthenticationInfo(
AuthenticationToken token) throws AuthenticationException {
System.out.println("[SecondReaml] doGetAuthenticationInfo");
//1、把AuthenticationToken 转换为UsernamePasswordToken
UsernamePasswordToken upToken = (UsernamePasswordToken) token;
//2、从UsernamePasswordToken 中获取username
String username = upToken.getUsername();
//3、调用数据库方法,从数据库中查询username 对应的用户记录
System.out.println("从数据库中获取username:" + username + " 所对应的用户信息");
//4、若用户不存在,则可以抛出UnknowAccountException异常
if("unknow".equals(username)){
throw new UnknownAccountException("影虎不存在");
}
//5、根据用户的信息情况,决定是否需要抛出其他的AuthenticationException异常
if("monster".equals(username)){
throw new LockedAccountException("用户被锁定");
}
//6、根据用户的情况,来构建AuthenticationInfo对象并返回,通常使用实现类是SimpleAuthenticationInfo
//以下信息是从数据库中获取的
//1、principal:认证的实体信息,可以使username,也可以是数据表对应的用户的实体类对象
Object principal = username;
//2、credentials:密码
Object credentials = null; //fc1709d0a95a6be30bc5926fdb7f22f4
if("admin".equals(username)){
credentials = "ce2f6417c7e1d32c1d81a797ee0b499f87c5de06";
}else if("user".equals(username)){
credentials = "073d4c3ae812935f23cb3f2a71943f49e082a718";
}
//3、realmName:当前realm对象的name,调用父类的getName()即可
String realmName = getName();
//4、盐值
ByteSource credentialsSalt = ByteSource.Util.bytes(username);
SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(principal, credentials, credentialsSalt, realmName);
return info;
}
public static void main(String[] args) {
String algorithmName = "SHA1";
Object source = "123456";
Object salt = ByteSource.Util.bytes("admin");
int hashIterations = 1024;
Object result = new SimpleHash(algorithmName, source, salt, hashIterations);
System.out.println(result);
}
}