Shiro-官方文档及使用
普通web應用官方文檔:
shiro.ini
Once you choose at least one user store to connect to for Shiro’s needs, we’ll need to configure a Realm that represents that data store and then tell the ShiroSecurityManager about it.
If you’ve checked out the step2 branch, you’ll notice the src/main/webapp/WEB-INF/shiro.ini file’s [main] section now has the following additions:
中文翻譯:一旦您為Shiro的需要選擇了至少一個要連接到的用戶商店,我們將需要配置一個Realm,它表示數據存儲,然后告訴ShiroSecurityManager關于這件事。
如果您已經檢查了step2布蘭奇,你會注意到src/main/webapp/WEB-INF/shiro.ini檔案[main]一節現在增加了以下內容
web.xml
這個聲明定義了ServletContextListener啟動Shiro環境(包括Shiro環境)。SecurityManager在web應用程序啟動時。默認情況下,此偵聽器自動知道如何查找WEB-INF/shiro.ini用于Shiro配置的文件。
這個聲明定義了主ShiroFilter。這個過濾器需要過濾。全請求進入Web應用程序,這樣Shiro可以在允許請求到達應用程序之前執行必要的標識和訪問控制操作。
這個聲明確保全請求類型由ShiroFilter。經常filter-mapping聲明沒有指定元素,但是Shiro需要定義它們,這樣它就可以過濾可能為Web應用程序執行的所有不同的請求類型。
spring整合shiro官方文檔
web.xml:
<!-- The filter-name matches name of a 'shiroFilter' bean inside applicationContext.xml --> <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><!-- Make sure any request you want accessible to Shiro is filtered. /* catches all --> <!-- requests. Usually this filter mapping is defined first (before all others) to --> <!-- ensure that Shiro works in subsequent filters in the filter chain: --> <filter-mapping><filter-name>shiroFilter</filter-name><url-pattern>/*</url-pattern> </filter-mapping>applicationContext.xml
bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean"><!--配置引用安全管理器--><property name="securityManager" ref="securityManager"/><!-- override these for application-specific URLs if you like:<!--配置登錄頁面--><property name="loginUrl" value="/login.jsp"/><!--配置成功登錄后跳轉的頁面--><property name="successUrl" value="/home.jsp"/><!--配置攔截后跳轉的頁面--><property name="unauthorizedUrl" value="/unauthorized.jsp"/> --><!-- The 'filters' property is not necessary since any declared javax.servlet.Filter bean --><!-- defined will be automatically acquired and available via its beanName in chain --><!-- definitions, but you can perform instance overrides or name aliases here if you like: --><!-- <property name="filters"><util:map><entry key="anAlias" value-ref="someFilter"/></util:map></property> --><!--配置過濾器規則常用的規則:anno:任何人可以訪問authc:必須登錄后才能訪問,不包括remember meuser:登錄用戶才可以訪問,包含remember meperms:指定過濾規則,這個一般是擴展使用,不會使用原生的--><property name="filterChainDefinitions"><value># some example chain definitions:/admin/** = authc, roles[admin]/docs/** = authc, perms[document:read]/** = authc# more URL-to-FilterChain definitions here</value></property> </bean><!-- Define any javax.servlet.Filter beans you want anywhere in this application context. --> <!-- They will automatically be acquired by the 'shiroFilter' bean above and made available --> <!-- to the 'filterChainDefinitions' property. Or you can manually/explicitly add them --> <!-- to the shiroFilter's 'filters' Map if desired. See its JavaDoc for more details. --> <bean id="someFilter" class="..."/> <bean id="anotherFilter" class="..."> ... </bean> ... <!--配置安全管理器--> <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager"><!-- Single realm app. If you have multiple realms, use the 'realms' property instead. --><property name="realm" ref="myRealm"/><!-- By default the servlet container sessions will be used. Uncomment this lineto use shiro's native sessions (see the JavaDoc for more): --><!-- <property name="sessionMode" value="native"/> --> </bean> <!--生命周期管理--> <bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor"/><!-- Define the Shiro Realm implementation you want to use to connect to your back-end --> <!-- security datasource: --> <!--配置realm--> <bean id="myRealm" class="...">... </bean>啟用Shiro注釋
<!-- Enable Shiro Annotations for Spring-configured beans. Only run after --> <!-- the lifecycleBeanProcessor has run: --> <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>在spring整合shiro過程中,不需要添加EnvironmentLoaderListener這個監聽器,是因為spring的ContentLoadListener 已經代替EnvironmentLoaderListener初始化容器并加載配置shiro的配置文件,所以spring整合shiro以后不需要配置EnvironmentLoaderListener。
使用
依賴:
<dependency><groupId>org.apache.shiro</groupId><artifactId>shiro-spring</artifactId><version>1.3.2</version> </dependency> <!--shiro核心包--> <dependency><groupId>org.apache.shiro</groupId><artifactId>shiro-core</artifactId><version>1.3.2</version> </dependency>web.xml:
<!--4. Shiro權限校驗過濾器,這里的filter-name固定,對應spring容器中的過濾器工廠的bean的id--> <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>自定義realm類
package com.zhijin.web.shiro;import org.apache.shiro.authc.AuthenticationException; import org.apache.shiro.authc.AuthenticationInfo; import org.apache.shiro.authc.AuthenticationToken; import org.apache.shiro.authz.AuthorizationInfo; import org.apache.shiro.realm.AuthorizingRealm; import org.apache.shiro.subject.PrincipalCollection;/*** 自定義reamlm*/ public class AuthRealm extends AuthorizingRealm {//登陸認證 protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {//強轉為用戶名密碼tokenUsernamePasswordToken upToken = (UsernamePasswordToken)token;//得頁面傳的登錄名String email = upToken.getUsername();//從數據庫中查詢登錄名User user = userService.findUserByEmail(email);if (user != null){//封裝到認證對象中//第一個參數:安全數據(user對象)//第二個參數:密碼(數據庫密碼)//第三個參數:當前調用realm域的名稱(類名即可)return new SimpleAuthenticationInfo(user,user.getPassword(),this.getName());}return null;}// 授權訪問校驗protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {User user = (User) principals.getPrimaryPrincipal();if (user !=null) {//根據用戶的ID從數據庫中查詢出權限模塊List<Module> moduleList = moduleService.findModuleByUserId(user.getId());Set<String> permissions = new HashSet<>();for (Module module : moduleList) {//將查詢出的模塊名稱添加到set集合中permissions.add(module.getName());}SimpleAuthorizationInfo sia = new SimpleAuthorizationInfo();//將帶有模塊名稱的set結合添加到SimpleAuthorizationInfo(封裝授權對象) sia.addStringPermissions(permissions);return sia;}return null;} }配置applicationContext-shiro
<?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:jdbc="http://www.springframework.org/schema/jdbc" xmlns:tx="http://www.springframework.org/schema/tx"xmlns:task="http://www.springframework.org/schema/task"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsdhttp://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsdhttp://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc.xsdhttp://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd"><!-- 1. 配置shiro過濾器工廠 --><bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean"><!--配置引用安全管理器--><property name="securityManager" ref="securityManager"/><!--登錄頁面--><property name="loginUrl" value="/login.jsp"/><!--沒有權限默認跳轉的頁面,登錄的用戶訪問了沒有被授權的資源自動跳轉到的頁面--><property name="unauthorizedUrl" value="/unauthorized.jsp"/><!--配置過濾規則--><property name="filterChainDefinitions"><value><!--anno:任何人可以訪問authc:必須登錄后才能訪問,不包括remember meuser:登錄用戶才可以訪問,包含remember meperms:指定過濾規則,這個一般是擴展使用,不會使用原生的-->/index.jsp* = anon/login.jsp* = anon/login* = anon/logout* = anon/css/** = anon/img/** = anon/plugins/** = anon/make/** = anon/** = authc</value></property></bean><!--2. 配置安全管理器--><bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager"><property name="realm" ref="myRealm"/></bean><!--3. 配置自定義Realm域 --><bean id="myRealm" class="com.zhijin.web.shiro.AuthRealm"><property name="credentialsMatcher" ref="credentialsMatcher"/></bean><!--4. 創建shiro提供的憑證匹配器,自動對用戶輸入的密碼按照指定的算法加密--><bean id="credentialsMatcher" class="org.apache.shiro.authc.credential.HashedCredentialsMatcher"><property name="hashAlgorithmName" value="md5"/></bean> </beans>自定義憑證匹配器
package com.zhijin.web.shiro;import org.apache.shiro.authc.AuthenticationInfo; import org.apache.shiro.authc.AuthenticationToken; import org.apache.shiro.authc.credential.HashedCredentialsMatcher; import org.apache.shiro.crypto.hash.Md5Hash;public class CustomCredentialsMatcher extends HashedCredentialsMatcher {@Overridepublic boolean doCredentialsMatch(AuthenticationToken token, AuthenticationInfo info) {//獲取用戶輸入的登錄名String username = (String) token.getPrincipal();//獲取用戶輸入的登錄密碼String password = new String((char[])token.getCredentials());//獲取數據庫查出來的密碼String md5Password = new Md5Hash(password,username).toString();String dbPassword = (String) info.getCredentials();return md5Password.equals(dbPassword);} }登錄
//1.獲取subjectSubject subject = SecurityUtils.getSubject();//2.構造用戶名和密碼UsernamePasswordToken upToken = new UsernamePasswordToken(email, password);//3.借助subject完成用戶登錄subject.login(upToken);總結
以上是生活随笔為你收集整理的Shiro-官方文档及使用的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: android开发地图找房,androi
- 下一篇: html grid插件,grid.htm