第一步:引入Maven
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-core</artifactId>
<version>1.4.0</version>
</dependency>
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-web</artifactId>
<version>1.4.0</version>
</dependency>
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-spring</artifactId>
<version>1.2.4</version>
</dependency>
<!-- shiro需要依赖servlet api -->
第二步: 配置 shiro的配置文件
<?xml version="1.0" encoding="UTF-8"?><bean
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="systemPropertiesModeName" value="SYSTEM_PROPERTIES_MODE_OVERRIDE" />
<property name="ignoreResourceNotFound" value="true" />
<property name="locations">
<list>
<value>classpath:jdbc.properties</value>
<value>classpath:redis.properties</value>
<value>classpath:env.properties</value>
</list>
</property>
</bean>
<context:component-scan base-package="com.gzs" />
<!-- <bean id="dataSource" class="com.jolbox.bonecp.BoneCPDataSource"
destroy-method="close">
<property name="driverClass" value="${jdbc.driver}" />
<property name="jdbcUrl" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
<property name="idleConnectionTestPeriod" value="60" />
<property name="idleMaxAge" value="30" />
<property name="maxConnectionsPerPartition" value="150" />
<property name="minConnectionsPerPartition" value="5" />
</bean>
-->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"
init-method="init" destroy-method="close">
<property name="driverClassName" value="${jdbc.driver}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
<property name="filters" value="stat" />
<property name="maxActive" value="20" />
<property name="initialSize" value="1" />
<property name="maxWait" value="60000" />
<property name="minIdle" value="1" />
<property name="timeBetweenEvictionRunsMillis" value="60000" />
<property name="minEvictableIdleTimeMillis" value="300000" />
<property name="validationQuery" value="SELECT 'x'" />
<property name="testWhileIdle" value="true" />
<property name="testOnBorrow" value="false" />
<property name="testOnReturn" value="false" />
<property name="poolPreparedStatements" value="true" />
<property name="maxPoolPreparedStatementPerConnectionSize"
value="50" />
<!-- <property name="filters" value="stat" /> -->
</bean>
<!-- 自定义Realm -->
<bean id="myRealm" class="com.gzs.manage.pojo.DatabaseRealm"/>
<!-- 安全管理器 -->
<bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
<property name="realm" ref="myRealm"/>
</bean>
<!-- Shiro过滤器 -->
<bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
<!-- Shiro的核心安全接口,这个属性是必须的 -->
<property name="securityManager" ref="securityManager"/>
<!-- 身份认证失败,则跳转到登录页面的配置 -->
<property name="loginUrl" value="/login.jsp"/>
<!-- 权限认证失败,则跳转到指定页面 -->
<property name="unauthorizedUrl" value="/error.jsp"/>
<!-- Shiro连接约束配置,即过滤链的定义 -->
<property name="filterChainDefinitions">
<value>
/login=anon
/admin*=authc
/student=roles[teacher]
/teacher=perms["user:create"]
</value>
</property>
</bean>
<!-- 保证实现了Shiro内部lifecycle函数的bean执行 -->
<bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor"/>
<!-- 开启Shiro注解 -->
<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>
第三步:web.xml 配置 过滤器
<filter>
<filter-name>shiroFilter</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
<init-param>
<!-- 该值缺省为false,表示生命周期由SpringApplicationContext管理,设置为true则表示由ServletContainer管理 -->
<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>
第四步: 编写一个验证账号密码的类
public class DatabaseRealm extends AuthorizingRealm{
@Autowired
private NewLoginService newloginService;
/**
* 为当限前登录的用户授予角色和权
*/
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
System.out.println(2);
String username=(String)principals.getPrimaryPrincipal();
SimpleAuthorizationInfo authorizationInfo=new SimpleAuthorizationInfo();
// authorizationInfo.setRoles(userService.getRoles(Integer.parseInt(userid)));
// authorizationInfo.setRoles(userService.getRoles(username));
// authorizationInfo.setStringPermissions(userService.getPermissions(Integer.parseInt(userid)));
return authorizationInfo;
}
/**
* 验证当前登录的用户
*/
@Override
@Lazy
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
//获取账号密码
UsernamePasswordToken t = (UsernamePasswordToken) token;
String userName= token.getPrincipal().toString();
String password= new String( t.getPassword());
//获取数据库中的密码
Member user=newloginService.selectuseridFany(Integer.valueOf(userName));
String md5 = "";
try {
md5 = MD5.getMD5("guojianbing" + password);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(user.getPassword().equals(md5)){
SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(userName,password,getName());
return authenticationInfo;
}else{
return null;
}
}
}
第五步:测试
Subject currentUser=SecurityUtils.getSubject();
UsernamePasswordToken token = new UsernamePasswordToken(userid,password);
//用户是否验证
try {
//当前用户登录
currentUser.login(token);
}catch(org.apache.shiro.authc.AuthenticationException e){
e.printStackTrace();
}
Session session=currentUser.getSession();
System.out.println("用户ID:"+session.getId());
System.out.println("sessionId:"+session.getId());
System.out.println("sessionHost:"+session.getHost());
System.out.println("sessionTimeout:"+session.getTimeout());
session.setAttribute("info", "session的数据");
session.setAttribute("username", token.getUsername());
总结一共五步:
1)MAVEN
2)spring.xml配置文件
3)web.xml
4)需要先写一个 继承AuthorizingRealm的类 ,名为DatabaseRealm
5)测试