前提:准备SSM项目,废话不多言,直接上代码。
一、添加依赖
<!--shiro依赖-->
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-core</artifactId>
<version>1.3.2</version>
</dependency>
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-web</artifactId>
<version>1.3.2</version>
</dependency>
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-ehcache</artifactId>
<version>1.3.2</version>
</dependency>
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-quartz</artifactId>
<version>1.3.2</version>
</dependency>
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-spring</artifactId>
<version>1.3.2</version>
</dependency>
二、配置web.xml
<!-- 以过滤器的方式整合进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>
<!-- targetBeanName值和spring的shiro的配置文件中bean的id值一致 -->
<init-param>
<param-name>targetBeanName</param-name>
<param-value>shiroFilter</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>shiroFilter</filter-name>
<!-- 访问任何url都会被shiro的过滤器过滤 -->
<url-pattern>*.do</url-pattern>
</filter-mapping>
三、添加spring-shiro.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" xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
<!-- 配置自定义Realm -->
<bean id="myRealm" class="com.xxf.shiro.UserRealm"/>
<!-- 安全管理器 -->
<bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
<property name="realm" ref="myRealm"/>
<!-- 注入缓存管理器 -->
<property name="cacheManager" ref="cacheManager"/>
<!-- 注入session管理器 -->
<property name="sessionManager" ref="sessionManager"/>
</bean>
<!-- 缓存管理器 -->
<bean id="cacheManager" class="org.apache.shiro.cache.ehcache.EhCacheManager">
<property name="cacheManagerConfigFile" value="classpath:shiro-ehcache.xml"/>
</bean>
<!-- 会话管理器 -->
<bean id="sessionManager" class="org.apache.shiro.web.session.mgt.DefaultWebSessionManager">
<!-- session的失效时长,单位毫秒 -->
<property name="globalSessionTimeout" value="600000"/>
<!-- 删除失效的session -->
<property name="deleteInvalidSessions" value="true"/>
</bean>
<!-- Shiro过滤器 核心-->
<bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
<!-- Shiro的核心安全接口,这个属性是必须的 -->
<property name="securityManager" ref="securityManager"/>
<!-- 身份认证失败,则跳转到登录页面的配置 -->
<property name="loginUrl" value="/login.do"/>
<!-- 权限认证失败,则跳转到指定页面 -->
<property name="unauthorizedUrl" value="/nopower.jsp"/>
<!-- Shiro连接约束配置,即过滤链的定义 -->
<property name="filterChainDefinitions">
<value>
<!--anon 表示匿名访问,不需要认证以及授权-->
/login.do=anon
/dologin.do=anon
/loginOut=logout
<!--authc表示需要认证 没有进行身份认证是不能进行访问的-->
/**=authc
</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>
</beans>
四、添加spring-shiro.xml
<ehcache>
<!--diskStore:缓存数据持久化的目录 地址 -->
<diskStore path="./ehcache" />
<defaultCache
maxElementsInMemory="1000"
maxElementsOnDisk="10000000"
eternal="false"
overflowToDisk="false"
diskPersistent="false"
timeToIdleSeconds="120"
timeToLiveSeconds="120"
diskExpiryThreadIntervalSeconds="120"
memoryStoreEvictionPolicy="LRU">
</defaultCache>
</ehcache>
五、自定义的Realm
package com.xxf.shiro;
import com.xxf.model.AdminInfo;
import com.xxf.service.AdminResouceService;
import com.xxf.service.AdminService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
public class UserRealm extends AuthorizingRealm {
@Autowired
private AdminService adminService;
@Autowired
private AdminResouceService adminResouceService;
/**
* 功能描述: 授权
* @Param: [principalCollection]
* @Return: org.apache.shiro.authz.AuthorizationInfo
* @Author: Administrator
*/
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
String userName = principalCollection.getPrimaryPrincipal().toString();
SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
//用户
AdminInfo info = this.adminService.findByName(userName);
if(info!=null){
//根据用户获取用户的角色
Set<String> sroles = new HashSet<>();
sroles.add(String.valueOf(info.getRoleId()));
//赋值角色给simpleAuthorizationInfo
simpleAuthorizationInfo.setRoles(sroles);
}
//根据用户查询用户的权限
Set<String> spermit = this.adminResouceService.selpremission(Integer.parseInt(info.getRoleId()));
//授权
simpleAuthorizationInfo.setStringPermissions(spermit);
return simpleAuthorizationInfo;
}
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
System.out.println("身份校验--执行了goGetAuthenticationInfo...");
//拿到用户名
String username = (String) token.getPrincipal();
//根据用户名数据库中找到admin
AdminInfo user = adminService.findByName(username);
if (user == null) {
throw new UnknownAccountException(); //没有找到账号
}
//交给AuthenticationRealm使用CredentialsMatcher进行密码匹配
SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(
user, //这里要传user,否则后面想拿到登录的用户信息,拿不到而报错
user.getPassword(), //密码
getName() //realm name
);
return authenticationInfo;
}
}
六、Controller代码(登录)
/**
* 功能描述: 执行登陆验证
* @Param: [adminInfo]
* @Return: java.lang.String
* @Author: Administrator
*/
@RequestMapping("/dologin")
@ResponseBody
public String login(@RequestBody AdminInfo adminInfo, HttpSession session){
/*AdminInfo admin = this.adminService.checkPwdAndUserName(adminInfo);
if(admin!=null){
session.setAttribute("admin",admin);
return "success";
}
return "error";*/
String resuleMesage = "error";
if (adminInfo != null ) {
//初始化
Subject subject = SecurityUtils.getSubject();
UsernamePasswordToken token = new UsernamePasswordToken(adminInfo.getUserName(), adminInfo.getPassword());
try {
//登录,即身份校验,由通过Spring注入的UserRealm会自动校验输入的用户名和密码在数据库中是否有对应的值
subject.login(token);
resuleMesage = "success";
return resuleMesage;
//return "redirect:index.do";
}catch (Exception e){
e.printStackTrace();
resuleMesage = "未知错误,错误信息:" + e.getMessage();
}
} else {
resuleMesage = "请输入用户名和密码";
}
return resuleMesage;
}