这篇教程将从ssm整合shiro的方式出发,以实战的角度快速的搭建起整个工程的框架,因此重点在与怎么整合shiro,至于逻辑代码不是这篇教程的重点。
- 工程架构
- 相关依赖
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.7</maven.compiler.source>
<maven.compiler.target>1.7</maven.compiler.target>
<spring.version>4.0.2.RELEASE</spring.version>
<shiro.version>1.3.2</shiro.version>
</properties>
<dependencies>
<!--日志相关依赖-->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.25</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.25</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-nop</artifactId>
<version>1.7.2</version>
</dependency>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.1.1</version>
</dependency>
<!--shiro相关依赖-->
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-core</artifactId>
<version>${shiro.version}</version>
</dependency>
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-web</artifactId>
<version>${shiro.version}</version>
</dependency>
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-spring</artifactId>
<version>${shiro.version}</version>
</dependency>
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-ehcache</artifactId>
<version>${shiro.version}</version>
</dependency>
<!-- spring相关依赖-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.version}</version>
</dependency>
</dependencies>
- 主要代码
首先配置web.xml
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-*.xml</param-value>
</context-param>
<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>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>spring</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
配置spring-servlet.xml(同web.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">
<!--这里主要配置securityManager中的缓存管理、认证策略、加密方式-->
<bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
<!--缓存管理-->
<property name="cacheManager" ref="cacheManager"/>
<!--认证管理-->
<property name="authenticator" ref="authenticator"></property>
<!--加密管理-->
<property name="realms">
<list>
<ref bean="shiroRealm"/>
<ref bean="secondRealm"/>
</list>
</property>
<!--配置记住我相关的功能-->
<property name="rememberMeManager.cookie.maxAge" value="10"></property>
</bean>
<!--缓存管理-->
<bean id="cacheManager" class="org.apache.shiro.cache.ehcache.EhCacheManager">
<property name="cacheManagerConfigFile" value="classpath:ehcache.xml"/>
</bean>
<!--认证相关的设置-->
<bean id="authenticator"
class="org.apache.shiro.authc.pam.ModularRealmAuthenticator">
<!--认证策略的配置-->
<property name="authenticationStrategy">
<bean class="org.apache.shiro.authc.pam.AtLeastOneSuccessfulStrategy"></bean>
</property>
</bean>
<!--加密方式的配置-->
<bean id="shiroRealm" class="com.kkcl.shiro.realm.ShiroRealm">
<property name="credentialsMatcher">
<bean class="org.apache.shiro.authc.credential.HashedCredentialsMatcher">
<!--加密的方式-->
<property name="hashAlgorithmName" value="MD5"/>
<!--加密的次数-->
<property name="hashIterations" value="1024"/>
</bean>
</property>
</bean>
<bean id="secondRealm" class="com.kkcl.shiro.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>
<!--配置bean的生命周期,可以自定义的来调用配置在Spring IOC容器中的shiro bean的生民工周期方法-->
<bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor"/>
<!--启用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>
<!--id必须和web.xml中的DelegatingFilterProxy的name一致-->
<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"/>
<!--设置相关页面的权限
anon表示任意都可以访问
authc表示需要认证
->
<property name="filterChainDefinitions">
<value>
/login.jsp = anon
/shiro/login = anon
/shiro/logout = logout
/user.jsp = roles[user]
/list.jsp = roles[admin]
/** = authc
</value>
</property>
</bean>
<bean id="filterChainDefinitionMap"
factory-bean="filterChainDefinitionMapBuilder" factory-method="buildFilterChainDefintionMap"/>
<!--通过配置bean的方法来增加相关的权限-->
<bean id="filterChainDefinitionMapBuilder"
class="com.kkcl.shiro.factory.FilterChainDefinitionMapBuilder"/>
<bean id="shiroService" class="com.kkcl.shiro.service.ShiroService"/>
</bean>
- 项目部署
启动项目后默认加载到登陆页面在登陆页面中输入用户名和密码
进入LoginController.java的/shiro/login方法
@RequestMapping("/login")
public String login(@RequestParam("username") String username, @RequestParam("password") String password){
Subject subject = SecurityUtils.getSubject();
if(!subject.isAuthenticated()){
UsernamePasswordToken token = new UsernamePasswordToken(username,password);
token.setRememberMe(true);
try {
System.out.println("====================");
System.out.println("1."+token.hashCode());
subject.login(token);
} catch (AuthenticationException e) {
System.out.println("登陆失败:"+ e.getMessage());
}
}
return "redirect:/list.jsp";
}
程序运行到subject.login(token);进入编写好的ShiroRealm.java和SecondRealm.java
由于ShiroRealm和SecondRealm的代码相识,故这里之战是SecondRealm中打主要代码
public class SecondRealm extends AuthenticatingRealm {
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
/**
System.out.println("====================");
System.out.println("doGetAuthenticationInfo:"+token.hashCode());
System.out.println("====================");
return null;
**/
System.out.println("[SecondRealm] doGetAuthenticationInfo:"+token.hashCode());
UsernamePasswordToken upToken = (UsernamePasswordToken)token;
String username = upToken.getUsername();
//调用数据库的方法,从数据中查询username对应的用户记录
System.out.println("从数据库中共获取到username:"+username +"所对应的用户信息");
if("unknow".equals(username)){
throw new UnknownAccountException("用户不存在!");
}
if("monster".equals(username)){
throw new LockedAccountException("该用户已被锁定!");
}
//principal认证的实体的相关的信息,可以是username,也可以是数据库表对应的用户的实体类的对象
Object principal = username;
//凭证(密码)
Object credentials = "123456";
if("admin".equals(username)){
credentials = "0d414ed7ade260fc506cbf4628041b4c17fe8f32";
}else if("user".equals(username)){
credentials = "073d4c3ae812935f23cb3f2a71943f49e082a718";
}
//当前realm的名称
String realmName = getName();
//盐值加密
ByteSource byteSourceSalt = ByteSource.Util.bytes(username);
SimpleAuthenticationInfo info = null;
info = new SimpleAuthenticationInfo(principal,credentials,byteSourceSalt,realmName);
return info;
}
}
如何符合相关的认证的规则,将成功的跳转到list.jsp页面,认证不通过时将跳转回login.jsp页面。
- 源码地址
https://github.com/kkcl/kkcl-learning-example/tree/master/shiro