推薦shiro教程:https://www.w3cschool.cn/shiro/
Spring整合shiro步驟解讀:
一:導入shiro相關依賴
二:web.xml中配置shiro過濾器
三:編寫自定義的DbRealm,進行認證和授權
四:spring整合shiro配置檔案:applicationContext-shiro.xml
五:shiro緩存檔案:ehcache-shiro.xml
六:spring容器配置加載applicationContext-shiro.xml檔案
一:導入shiro相關依賴
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-core</artifactId>
<version>1.4.0</version>
</dependency>
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-ehcache</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.4.0</version>
</dependency>
二:web.xml中配置shiroFilter
<!-- 注意這個過濾器的name,在配置allicationContext-shiro.xml中需要使用 -->
<filter>
<filter-name>shiroFilter</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
<filter-name>shiroFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
三:編寫自定義的DbRealm,實作使用者的認證和授權
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
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 com.mote.pojo.Role;
import com.mote.pojo.User;
import com.mote.service.RoleService;
import com.mote.service.UserService;
public class ShiroDbRealm extends AuthorizingRealm {
@Autowired
private UserService userService;
@Autowired
private RoleService roleService;
/**
* 認證
*/
protected AuthenticationInfo doGetAuthenticationInfo(
AuthenticationToken authcToken) throws AuthenticationException {
UsernamePasswordToken token = (UsernamePasswordToken) authcToken;//轉為UsernamePasswordToken
String userName = token.getUsername();//擷取使用者名
String password = new String(token.getPassword());//擷取密碼
User user = userService.getUserByNamePwd(userName, password);//通過使用者名和密碼擷取使用者
if (user == null)
return null;
// 身份認證驗證成功,傳回一個AuthenticationInfo實作
return new SimpleAuthenticationInfo(user.getUserName(),
password, getName());
}
/**
* 授權
*/
protected AuthorizationInfo doGetAuthorizationInfo(
PrincipalCollection principals) {
SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
String userName = (String) getAvailablePrincipal(principals); // 擷取使用者名
Role role = roleService.getRolesByUserName(userName);// 擷取使用者角色
if (role == null)
return null;
info.addRole(role.getRoleName()); // 添加角色
List<String> perms = roleService.getPerm(role.getId());// 擷取角色對應的權限
info.addStringPermissions(perms); // 添權重限
return info;
}
}
對應的sql語句:
<select id="getUserByNamePwd" resultType="com.mote.pojo.User">
SELECT * FROM user WHERE user_name = #{userName} AND password = #{password}
</select>
<select id="getRolesByUserName" resultType="com.mote.pojo.Role">
SELECT r.id,r.role_name FROM `user` u JOIN role r
ON u.role_id = r.id AND u.user_name = #{userName}
</select>
<select id="getPerm" resultType="String">
SELECT perm_token FROM permission WHERE id IN
(SELECT p.perm_id FROM role_permission p
WHERE p.role_id = #{id})
</select>
四:建立spring整合shiro的配置檔案:applicationContext-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: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.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<!-- 配置Realm -->
<bean id="shiroDbRealm" class="com.mote.interceptor.ShiroDbRealm" />
<!-- 配置緩存 -->
<bean id="shiroEhcacheManager" class="org.apache.shiro.cache.ehcache.EhCacheManager">
<property name="cacheManagerConfigFile" value="classpath:ehcache-shiro.xml" />
</bean>
<!-- 使用者退出系統後,清空緩存,解決更新權限後不起作用的問題 -->
<bean id="logoutFilter" class="org.apache.shiro.web.filter.authc.LogoutFilter">
<!-- 跳轉登入頁面 -->
<property name="redirectUrl" value="/login" />
</bean>
<!-- 配置shiro安全管理器 -->
<bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
<property name="realm" ref="shiroDbRealm" />
<property name="cacheManager" ref="shiroEhcacheManager" />
</bean>
<!-- Shiro Filter -->
<bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
<property name="securityManager" ref="securityManager" />
<!-- 登入頁面 ,使用者 登入不成功自動 傳回該頁面 -->
<property name="loginUrl" value="/login" />
<!-- 登入成功頁面,登入成功後跳轉到該頁面 -->
<property name="successUrl" value="/idnex" />
<!-- 無權通路跳轉頁面 -->
<property name="unauthorizedUrl" value="/noAuthor" />
<property name="filters">
<map>
<!--使用者退出系統時,觸發logoutFilter -->
<entry key="logout" value-ref="logoutFilter" />
</map>
</property>
<property name="filterChainDefinitions">
<!-- anon任何使用者都可以通路,authc,登入才可以通路,user需要shiro進行認證之後才可以通路, -->
<value>
/css/** = anon
/img/** = anon
/js/** = anon
/login = anon
/loginOut = logout <!-- 攔截到/loginOut時,觸發shiro退出過濾器 -->
/**/**=user
</value>
</property>
</bean>
<!-- 保證實作了Shiro内部lifecycle函數的bean執行 -->
<bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor" />
<!-- 支援 Shiro對Controller的方法級AOP安全控制 -->
<bean
class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator"
depends-on="lifecycleBeanPostProcessor">
<property name="proxyTargetClass" value="true" />
</bean>
<!-- 開啟shiro注解支援 -->
<bean
class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor">
<property name="securityManager" ref="securityManager" />
</bean>
</beans>
關于權限管理filterChainDefinitions過濾器配置可以參考:filterChainDefinitions配置
五:建立ehcache緩存檔案:shiro-ehcache.xml
<ehcache updateCheck="false" name="shiroCache">
<defaultCache
maxElementsInMemory="10000"
eternal="false"
timeToIdleSeconds="120"
timeToLiveSeconds="120"
overflowToDisk="false"
diskPersistent="false"
diskExpiryThreadIntervalSeconds="120"
/>
</ehcache>
六:spring容器加載applicationContext-shiro.xml檔案
<context-param>
<param-name>contextConfigLocation</param-name >
<param-value>classpath:applicationContext*.xml</param-value >
</context-param>
上一篇:系統的角色管理AND使用者管理
下一篇:系統登入邏輯AND授權