天天看點

authc過濾器 shiro_shiro工具類詳解3Spring整合Shiro

authc過濾器 shiro_shiro工具類詳解3Spring整合Shiro

Spring整合Shiro實作注冊(注冊時密碼加密)

web.xml檔案配置DelegatingFilterProxy:通過代理模式将servlet容器中的filter同Spring容器中的bean關聯起來

targetFilterLifecycle屬性為true表明啟用引入filter的init()和destroy(),也就是spring容器中對應的filter生命周期交給servlet容器管理targetBeanName屬性設定Spring容器中filter的bean的id

<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xmlns="Java EE: XML Schemas for Java EE Deployment Descriptors" 
xsi:schemaLocation="Java EE: XML Schemas for Java EE Deployment Descriptors 
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>Shiro-07-ssm-shiro-authentication-1</display-name>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:resources/spring-*.xml</param-value>
  </context-param>
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  <servlet>
    <servlet-name>springmvc</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:resources/spring-mvc.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>springmvc</servlet-name>
    <url-pattern>*.do</url-pattern>
  </servlet-mapping>
  <filter>
    <filter-name>CharacterEncodingFilter</filter-name>
    <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
    <init-param>
      <param-name>encoding</param-name>
      <param-value>utf-8</param-value>
    </init-param>
    <init-param>
      <param-name>forceEncoding</param-name>
      <param-value>true</param-value>
    </init-param>
  </filter>
  <filter-mapping>
    <filter-name>CharacterEncodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
  
  <!-- 注冊DelegatingFilterProxy:通過代理模式将servlet容器中的filter同Spring容器中的bean關聯起來 -->
  <filter>
  	<filter-name>shiro</filter-name>
  	<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
  	<init-param>
  		<!-- 該屬性為true表明啟用引入filter的init()和destroy(),也就是spring容器中對應的filter生命周期交給servlet容器管理 -->
  		<param-name>targetFilterLifecycle</param-name>
  		<param-value>true</param-value>
  	</init-param>
  	<init-param>
  		<!-- 該屬性設定Spring容器中filter的bean的id -->
  		<param-name>targetBeanName</param-name>
  		<param-value>shiroFilter</param-value>
  	</init-param>
  </filter>
  <filter-mapping>
  	<filter-name>shiro</filter-name>
  	<url-pattern>/*</url-pattern>
  </filter-mapping>
  
</web-app>
           

需要導的包

authc過濾器 shiro_shiro工具類詳解3Spring整合Shiro

spring-shiro.xml配置檔案

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="Index of /schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="Index of /schema/context" 
    xmlns:mvc="Index of /schema/mvc"
    xmlns:tx="Index of /schema/tx"
    xmlns:aop="Index of /schema/aop"
    xsi:schemaLocation="
        Index of /schema/beans 
        http://www.springframework.org/schema/beans/spring-beans.xsd
        Index of /schema/tx 
        http://www.springframework.org/schema/tx/spring-tx.xsd
        Index of /schema/aop 
        http://www.springframework.org/schema/aop/spring-aop.xsd
        Index of /schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc.xsd
        Index of /schema/context 
        http://www.springframework.org/schema/context/spring-context.xsd">
    
    <!-- 注冊憑證比對器-->
    <bean id="credentialsMatcher" class="org.apache.shiro.authc.credential.HashedCredentialsMatcher">
    	<property name="hashAlgorithmName" value="md5"></property>
    	<property name="hashIterations" value="2"></property>
    </bean>
    <!-- 注冊自定義Realm -->
    <bean id="customRealm" class="com.bjsxt.realms.CustomRealm">
    	<property name="credentialsMatcher" ref="credentialsMatcher"></property>
    </bean>
    <!-- 注冊SecurityManager -->
    <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
    	<property name="realms" ref="customRealm"></property>
    </bean>
    <!-- 注冊ShiroFilterFactoryBean 注意:id名稱必須與web.xml中過濾器名稱對應 -->
    <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
    	<property name="securityManager" ref="securityManager"></property>
    	<property name="loginUrl" value="/user/login.do"></property>
    	<property name="successUrl" value="/jsp/users.jsp"></property>
    	<property name="unauthorizedUrl" value="/jsp/refuse.jsp"></property>
    	<!-- 設定過濾器鍊屬性 -->
    	<property name="filterChainDefinitions">
    		<value>
    			/user/login.do=authc
    			/**=anon
    		</value>
    	</property>
    </bean>
</beans>
           

realm授權檔案

import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
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 com.bjsxt.rbac.pojo.Users;
import com.bjsxt.rbac.service.IUserService;

public class CustomRealm extends AuthorizingRealm {

	
	@Autowired
	private IUserService userService;
	// 認證方法:擷取認證資訊
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) {
		
		try {
			//調用service
			//根據表單傳過來的使用者名查詢使用者資訊
			Users user = userService.selectByUsername(token.getPrincipal().toString());
			System.out.println(user);
			if (user != null) {
				ByteSource newSalt = ByteSource.Util.bytes(user.getPassword_salt());
				SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(token.getPrincipal(),
						user.getPassword(), newSalt, token.getPrincipal().toString());
				return simpleAuthenticationInfo;
			} else {
				return null;
			} 
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	// 授權方法:擷取授權資訊
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		return null;
	}

}
           

Spring整合Shiro實作菜單授權

SessionManager 的使用

SessionManager

會話管理器管理着應用中所有Subject的會話的建立、 維護、删除、失效、驗證等工作。

Shiro提供了三個預設實作:

DefaultSessionManager:DefaultSecurityManager

使用的預設實作,用于 JavaSE環境;

ServletContainerSessionManager:用于Web環境,其直接使用Servlet容器 的會話;

DefaultWebSessionManager:用于Web環境的實作,可以替代 ServletContainerSessionManager,自己維護着會話,直接廢棄了Servlet 容器的會話管理。

remember me功能實作

Shiro内置過濾器

authc過濾器 shiro_shiro工具類詳解3Spring整合Shiro

這些過濾器分為兩組,一組是認證過濾器,一組是授權過濾器。 其中anon,authcBasic,auchc,user是第一組, perms,roles,ssl,rest,port是第二組

Shiro内置過濾器

rest:

例子

/admins/user/**=rest[user],

根據請求的方法,相當于

/admins/user/**=perms[user:method] ,

其中method為post,get,delete等。

port:

例子

/admins/user/**=port[8081],

當請求的url的端口不是8081是跳轉到

schemal://serverName:8081?queryString

,其中schmal是協定http或https等,

serverName是你通路的host,8081是url配置裡port的端口,

queryString 是你通路的url裡的?後面的參數。

perms:

例子/admins/user/**=perms[user:add:*],

perms參數可以寫多個,多個時必 須加上引号,并且參數之間用逗号分割,例如 /admins/user/**=perms["user:add:*,user:modify:*"]

,當有多個參數時必須每個 參數都通過才通過,

想當于 isPermitedAll()方法。

roles:

例子

/admins/user/**=roles[admin],

參數可以寫多個,多個時必須加上引号, 并且參數之間用逗号分割,當有多個參數時,

例如

/admins/user/**=roles["admin,guest"],

每個參數通過才算通過,相當于 hasAllRoles()方法。

anon:

例子/admins/**=anon 沒有參數,表示可以匿名使用。

authc:

例如

/admins/user/**=authc

表示需要認證才能使用,沒有參數

authcBasic:

例如

/admins/user/**=authcBasic

沒有參數表示httpBasic認證

ssl:

例子

/admins/user/**=ssl

沒有參數,表示安全的url請求,協定為https