1. 程式人生 > >IDEA整合Maven工具使用shiro進行許可權管理

IDEA整合Maven工具使用shiro進行許可權管理

第一步:匯入jar包

<!--shiro許可權控制器-->
<dependency>
    <groupId>org.apache.shiro</groupId>
    <artifactId>shiro-core</artifactId>
    <version>1.2.2</version>
</dependency>
<dependency>
    <groupId>org.apache.shiro</groupId>
    <artifactId>
shiro-web</artifactId> <version>1.2.2</version> </dependency> <dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-ehcache</artifactId> <version>1.2.2</version> </dependency> <dependency> <groupId>
org.apache.shiro</groupId> <artifactId>shiro-spring</artifactId> <version>1.2.2</version> </dependency> <dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-quartz</artifactId> <version>1.2.2</version>
</dependency>

第二步:

配置shiro.xml(myRealm、CustomCredentialsMatcher需要自己實現)

myRealm 需要繼承 AuthorizingRealm抽象類

CustomCredentialsMatcher 需要繼承SimpleCredentialsMathcer類 實現doCredentialsMatcher方法

<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://www.springframework.org/schema/beans"
xsi:schemaLocation="http://www.springframework.org/schema/beans
   http://www.springframework.org/schema/beans/spring-beans-4.0.xsd">
<!-- 繼承自AuthorizingRealm的自定義Realm,即指定Shiro驗證使用者登入 -->
<bean id="myRealm" class="cn.attendance.common.security.MyRealm">
        <property name="credentialsMatcher" ref="passwordMatcher"/>
    </bean>
    <bean id="passwordMatcher" class="cn.attendance.common.security.CustomCredentialsMatcher"/>
<!-- Shiro預設會使用Servlet容器的Session,可通過sessionMode屬性來指定使用Shiro原生Session -->
    <!-- 即<property name="sessionMode" value="native"/>,詳細說明見官方文件 -->
    <!-- 這裡主要是設定自定義的單Realm應用,若有多個Realm,可使用'realms'屬性代替 -->
<bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
        <property name="realm" ref="myRealm"/>
    </bean>
<!-- Shiro主過濾器本身功能十分強大,其強大之處就在於它支援任何基於URL路徑表示式的、自定義的過濾器的執行 -->
    <!-- Web應用中,Shiro可控制的Web請求必須經過Shiro主過濾器的攔截,Shiro對基於Spring的Web應用提供了完美的支援 -->
<bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
<!-- Shiro的核心安全介面,這個屬性是必須的 -->
<property name="securityManager" ref="securityManager"/>
<!-- 要求登入時的連結(可根據專案的URL進行替換),非必須的屬性,預設會自動尋找Web工程根目錄下的"/login.jsp"頁面 -->
<property name="loginUrl" value="/login"/>
<!-- 登入成功後要跳轉的連線(本例中此屬性用不到,因為登入成功後的處理邏輯在LoginController裡硬編碼為main.jsp了) -->
        <!-- <property name="successUrl" value="/system/main"/> -->
        <!-- 使用者訪問未對其授權的資源時,所顯示的連線 -->
        <!-- 若想更明顯的測試此屬性可以修改它的值,如unauthor.jsp,然後用[玄玉]登入後訪問/admin/listUser.jsp就看見瀏覽器會顯示unauthor.jsp -->
        <!--<property name="unauthorizedUrl" value="/error/403.html"/>-->
        <!-- Shiro連線約束配置,即過濾鏈的定義 -->
        <!-- 此處可配合我的這篇文章來理解各個過濾連的作用http://blog.csdn.net/jadyer/article/details/12172839 -->
        <!-- 下面value值的第一個'/'代表的路徑是相對於HttpServletRequest.getContextPath()的值來的 -->
        <!-- anon:它對應的過濾器裡面是空的,什麼都沒做,這裡.do和.jsp後面的*表示引數,比方說login.jsp?main這種 -->
        <!-- authc:該過濾器下的頁面必須驗證後才能訪問,它是Shiro內建的一個攔截器org.apache.shiro.web.filter.authc.FormAuthenticationFilter -->
<property name="filterChainDefinitions">
            <value>
/static/**=anon
                /login=anon
                <!--/user/userinfo=authc-->
/user/userinfo=anon
            </value>
        </property>
    </bean>
<!-- 保證實現了Shiro內部lifecycle函式的bean執行 -->
<bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor"/>
</beans>

第三步:

整合spring框架

<!--引入許可權管理-->
<import resource="spring-shiro.xml"/>

第四步:

整合spring-mvc框架

<!--開啟切面程式設計自動代理-->
<aop:aspectj-autoproxy proxy-target-class="true"/>
<bean class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor">
    <property name="securityManager" ref="securityManager"/>
</bean>

第五步:

在web.xml中配置

 <filter>
    <filter-name>shiroFilter</filter-name>
    <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
    <async-supported>true</async-supported>
    <init-param>
<!-- 該值預設為false,表示生命週期由SpringApplicationContext管理,設定為true則表示由ServletContainer管理 -->
<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>

 第六步 :

配置全域性無許可權跳轉頁面

<!--全域性錯誤頁面跳轉-->
<bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
    <property name="exceptionMappings">
        <props>
<!--無許可權跳轉後的頁面-->
<prop key="org.apache.shiro.authz.UnauthorizedException">403</prop>
        </props>
    </property>
</bean>

例項:

    1:認證:

(自定義的Realm需要繼承AuthorizingRealm類並從寫他的兩個方法)(CustomerCredentialsMatcher繼承SimpleCredentialsMathcer類並重寫doCredentialsMatcher方法)

    (1)呼叫subject.login(Token) ->

    (2)Realm類中的AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token)方法 ->  

    (3)強轉Token獲取使用者資訊  ->

    (4)return Authentication物件  ->

   (5)自定義的認證方法CustomerCredentialsMatcher.doCredentialsMatcher方法

2:程式碼

myRealm:

protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
    UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) token;
String username = usernamePasswordToken.getUsername();
User user = userService.findUserByUserName(username);
    if(user == null){
        return null;
}else{
        AuthenticationInfo info = new SimpleAuthenticationInfo(user.getUsername(),user.getPassword(),getName());
SecurityUtils.getSubject().getSession().setAttribute("userinfo",user);
        return info;
}
}

CustomerCredentials:

public boolean doCredentialsMatch(AuthenticationToken token, AuthenticationInfo info) {
    try {
        UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) token;
String password = String.valueOf(usernamePasswordToken.getPassword());
Object tokenCredentials = MD5Utils.encryptPassword(password);
Object accountCredentials = getCredentials(info);
        return equals(tokenCredentials,accountCredentials);
}catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
} catch (UnsupportedEncodingException e) {
        e.printStackTrace();
}
    return false;
}

授權程式碼:

protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {

    String username = (String)principalCollection.getPrimaryPrincipal();
User user = userService.findUserByUserName(username);
SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
    for(Role role :user.getRoleList()){
        authorizationInfo.addRole(role.getRole());
        for(Permission permission :role.getPermissionList()){
            authorizationInfo.addStringPermission(permission.getPermission());
}
    }
    return authorizationInfo;
}