一、添加依賴
<!--shiro版本號-->
<shiro.version>1.4.0</shiro.version>
<!-- shiro -->
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-core</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-web</artifactId>
<version>${shiro.version}</version>
</dependency>
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-ehcache</artifactId>
<version>${shiro.version}</version>
</dependency>
二、創建shiro配置文件,配置shiro
<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-4.0.xsd ">
<!-- web.xml中shiro的filter對應的bean -->
<!-- Shiro 的Web過濾器 -->
<bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
<property name="securityManager" ref="securityManager" />
<!-- loginUrl認證提交地址,如果沒有認證將會請求此地址進行認證,請求此地址將由formAuthenticationFilter進行表單認證 -->
<property name="loginUrl" value="/static/html/login.html" />
<!-- 認證成功統一跳轉到first.action,建議不配置,shiro認證成功自動到上一個請求路徑 -->
<property name="successUrl" value="/static/html/mainPage/admin.html"/>
<!-- 通過unauthorizedUrl指定沒有權限操作時跳轉頁面-->
<property name="unauthorizedUrl" value="/refuse.jsp" />
<!-- 自定義filter配置 -->
<property name="filters">
<map>
<!-- 將自定義 的FormAuthenticationFilter注入shiroFilter中-->
<entry key="authc" value-ref="formAuthenticationFilter" />
</map>
</property>
<!-- 過慮器鏈定義,從上向下順序執行,一般將/**放在最下邊 -->
<property name="filterChainDefinitions">
<value>
<!-- 對靜態資源設置匿名訪問 -->
/images/** = anon
/js/** = anon
/styles/** = anon
/html/** = anon
/WEB-INF/static/** = anon
/user/login.do = anon
<!-- 驗證碼,可匿名訪問 -->
/validatecode.jsp = anon
<!-- 請求 logout.action地址,shiro去清除session-->
/logout.do = logout
<!--商品查詢需要商品查詢權限 ,取消url攔截配置,使用註解授權方式 -->
<!-- /items/queryItems.action = perms[item:query]
/items/editItems.action = perms[item:edit] -->
<!-- 配置記住我或認證通過可以訪問的地址 -->
/index.jsp = user
/first.action = user
/welcome.jsp = user
<!-- /** = authc 所有url都必須認證通過纔可以訪問-->
/** = authc
<!-- /** = anon所有url都可以匿名訪問 -->
</value>
</property>
</bean>
<!-- securityManager安全管理器 -->
<bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
<property name="realm" ref="customRealm" />
<!-- 注入緩存管理器 -->
<!--<property name="cacheManager" ref="cacheManager"/>-->
<!-- 注入session管理器 -->
<property name="sessionManager" ref="sessionManager" />
<!-- 記住我 -->
<property name="rememberMeManager" ref="rememberMeManager"/>
</bean>
<!-- realm -->
<bean id="customRealm" class="cn.coolservice.oa.common.ShiroRealm">
<!-- 將憑證匹配器設置到realm中,realm按照憑證匹配器的要求進行散列 -->
<property name="credentialsMatcher" ref="credentialsMatcher"/>
</bean>
<!-- 憑證匹配器 -->
<bean id="credentialsMatcher" class="org.apache.shiro.authc.credential.HashedCredentialsMatcher">
<property name="hashAlgorithmName" value="MD5" />
<property name="hashIterations" value="5" />
</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">
<!-- 定時清理失效會話, 清理用戶直接關閉瀏覽器造成的孤立會話 -->
<property name="sessionValidationInterval" value="60000"/>
<!-- <property name="sessionValidationSchedulerEnabled" value="false"/> -->
<property name="sessionValidationSchedulerEnabled" value="true"/>
<!-- 這一句是關鍵-->
<property name="sessionIdCookie" ref="sessionIdCookie"/>
</bean>
<!-- 指定本系統SESSIONID, 默認爲: JSESSIONID 問題: 與SERVLET容器名衝突, 如JETTY, TOMCAT 等默認JSESSIONID,
當跳出SHIRO SERVLET時如ERROR-PAGE容器會爲JSESSIONID重新分配值導致登錄會話丟失! -->
<bean id="sessionIdCookie" class="org.apache.shiro.web.servlet.SimpleCookie">
<constructor-arg name="name" value="jeesite.session.id"/>
<property name="path" value="/"/>
</bean>
<!-- 自定義form認證過慮器 -->
<!-- 基於Form表單的身份驗證過濾器,不配置將也會註冊此過慮器,表單中的用戶賬號、密碼及loginurl將採用默認值,建議配置 -->
<bean id="formAuthenticationFilter"
class="cn.coolservice.oa.common.MyFormAuthenticationFilter ">
<!-- 表單中賬號的input名稱 -->
<property name="usernameParam" value="username" />
<!-- 表單中密碼的input名稱 -->
<property name="passwordParam" value="password" />
<!-- 記住我input的名稱 -->
<property name="rememberMeParam" value="rememberMe"/>
</bean>
<!-- rememberMeManager管理器,寫cookie,取出cookie生成用戶信息 -->
<bean id="rememberMeManager" class="org.apache.shiro.web.mgt.CookieRememberMeManager">
<property name="cookie" ref="rememberMeCookie" />
</bean>
<!-- 記住我cookie -->
<bean id="rememberMeCookie" class="org.apache.shiro.web.servlet.SimpleCookie">
<!-- rememberMe是cookie的名字 -->
<constructor-arg value="rememberMe" />
<!-- 記住我cookie生效時間30天 -->
<property name="maxAge" value="2592000" />
</bean>
</beans>
三、自定義shiroRealm
package cn.coolservice.oa.common;
import cn.coolservice.oa.entity.User;
import cn.coolservice.oa.service.systemService.PermissionService;
import cn.coolservice.oa.service.systemService.SroleService;
import cn.coolservice.oa.service.systemService.UserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.*;
/**
* @Author: 樊小銘
* Date: 2020/2/12 10:12
* @Version:
* @Description:
*/
public class ShiroRealm extends AuthorizingRealm {
@Autowired
private UserService userService;
@Autowired
private SroleService sroleService;
@Autowired
private PermissionService permissionService;
/*
* 授權
*
* */
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
// 獲取身份信息
String username = (String) principals.getPrimaryPrincipal();
// 根據身份信息從數據庫中查詢權限數據
//....這裏使用靜態數據模擬
List<String> permissions = new ArrayList<String>();
permissions.add("user:create");
permissions.add("user.delete");
//將權限信息封閉爲AuthorizationInfo
SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
for(String permission:permissions){
simpleAuthorizationInfo.addStringPermission(permission);
}
return simpleAuthorizationInfo;
}
/*
* 認證
* */
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
UsernamePasswordToken uptoken = (UsernamePasswordToken)token;
String username = uptoken.getUsername();
char[] passwords = uptoken.getPassword();
StringBuffer password = new StringBuffer();
for(char i : passwords){
password.append(i);
}
User user = userService.getUserByUserName(username);
if( user == null || !user.getUsername().equals(username)) {
throw new UnknownAccountException(); //如果用戶名錯誤
}
String algo = "MD5";
Object testSalt = ByteSource.Util.bytes(username); // 把用戶名當作鹽值
int hashi = 5 ; // 加密5次
SimpleHash md5Pwd = new SimpleHash(algo,password.toString(),testSalt,hashi);
if(!md5Pwd.toString().equals(user.getPassword())){
throw new IncorrectCredentialsException();
}
ByteSource salt = ByteSource.Util.bytes(username);
//如果身份認證驗證成功,返回一個AuthenticationInfo實現;
return new SimpleAuthenticationInfo(user.getUsername(), user.getPassword(), salt, getName());
}
public static void main(String[] args) {
String algo = "MD5";
Object sour = "666666";
Object salt = ByteSource.Util.bytes("admin");
int hashi = 5 ;
// String md5 = new Md5Hash("666666").toString();
SimpleHash md5 = new SimpleHash(algo,sour,salt,hashi);
System.out.println(md5);
}
}
四、在web.xml中註冊shiro filter
<!-- spring整合安全框架 -->
<filter>
<filter-name>DelegatingFilterProxy</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
<!-- 初始化參數 -->
<init-param>
<param-name>targetBeanName</param-name>
<param-value>shiroFilter</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>DelegatingFilterProxy</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>