Shiro的登錄驗證及授權多Realm情況【基於SpringMVC框架下】


package com.shiro.action;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
public class LoginAction {
    @RequestMapping("/login")
     public String login(@RequestParam("username") String username,
              @RequestParam("password")String password){
         //創建subject實例
         Subject subject = SecurityUtils.getSubject();
         //判斷當前用戶是否登錄
         if(subject.isAuthenticated()==false){
             //將用戶名及密碼封裝交個UsernamePasswordToken
             UsernamePasswordToken token = new UsernamePasswordToken(username,password);
             try {
                subject.login(token);
            } catch (AuthenticationException e) {
                System.out.println("驗證不通過,無法登錄!");
                return "error";
            }
         }
        return "success";
         
     }
}
package com.shiro.bean;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashSet;
import java.util.Set;

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.crypto.hash.SimpleHash;
import org.apache.shiro.realm.jdbc.JdbcRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.apache.shiro.util.JdbcUtils;

/**
 * @author layne Action方法中執行subject.login(token)時會通過IOC容器調取Realm域進行數據和前端數據比對
 */
//public class ShiroRealm extends  AuthorizingRealm {

public class SecondRealm extends JdbcRealm {
/** * Returns all principals associated with the corresponding Subject. Each * principal is an identifying piece of information useful to the * application such as a username, or user id, a given name, etc - anything * useful to the application to identify the current <code>Subject</code>. * The returned PrincipalCollection should <em>not</em> contain any * credentials used to verify principals, such as passwords, private keys, * etc. Those should be instead returned by {@link #getCredentials() * getCredentials()}. * * @return all principals associated with the corresponding Subject. * * doGetAuthenticationInfo,獲取認證消息,如果數據庫沒有數據,返回null. * AuthenticationInfo可以使用 SimpleAuthenticationInfo實現類,封裝給正確用戶名和密碼 * token參數:需要驗證的token */ @Override protected AuthenticationInfo doGetAuthenticationInfo( AuthenticationToken token) throws AuthenticationException { /** * 1.將token轉換為UsernamePasswordToken 2.獲取用戶名 3.查詢數據庫,進行驗證 4.結果返回 * 5.驗證不通過,拋出異常 */
        // 1.將token轉換為UsernamePasswordToken
        UsernamePasswordToken upToken = (UsernamePasswordToken) token; // 2.獲取用戶名
        String userName = upToken.getUsername(); // 獲取用戶名后。通過查詢用戶名查詢數據庫是否有值,有值則進行密碼驗證。
 SimpleAuthenticationInfo info = null; Connection conn=null; PreparedStatement ps =null; ResultSet rs =null; // 3。查詢數據庫 // 使用JDBC鏈接數據庫進行查詢
        try { /*Class.forName("com.mysql.jdbc.Driver"); String url = "jdbc:mysql://localhost:3306/test"; Connection conn = DriverManager.getConnection(url, "root", "");*/ conn= dataSource.getConnection(); ps = conn.prepareStatement("select * from account where name=?"); ps.setString(1, userName); rs = ps.executeQuery(); if (rs.next()) { Object principal = userName; Object credentials = rs.getString(3); String realmName = this.getName(); // 設置鹽值
                ByteSource salt = ByteSource.Util.bytes(userName); // SimpleHash sh=new SimpleHash(algorithmName, source, salt, // iterations); // 加密類型 加密資源 鹽值加密 加密次數 // 給從數據庫中拿到的密碼做MD5的加密
                SimpleHash sh = new SimpleHash("SHA1", credentials, salt, 1024); // info = new SimpleAuthenticationInfo(principal, credentials, // realmName); // info = new SimpleAuthenticationInfo(principal, sh, // realmName); // 通過關於鹽值的構造器,將前端傳入的密碼在加密時再加入鹽值
                info = new SimpleAuthenticationInfo(principal, sh, salt, realmName); } else { throw new AuthenticationException(); } } catch (SQLException e) { e.printStackTrace(); } finally{ JdbcUtils.closeResultSet(rs); JdbcUtils.closeConnection(conn); } return info; } /** * 設置role驗證 */ @Override protected AuthorizationInfo doGetAuthorizationInfo( PrincipalCollection principals) { // 返回值:AuthorizationInfo:封裝獲取用戶對應所有角色,SimpleAuthorizationInfo(Set<String>) // 參數列表:PrincipalCollection登錄的身份,登錄的用戶名
        SimpleAuthorizationInfo info = null; Connection conn=null; PreparedStatement ps =null; ResultSet rs =null; try { /*Class.forName("com.mysql.jdbc.Driver"); String url = "jdbc:mysql://localhost:3306/test"; Connection conn = DriverManager.getConnection(url, "root", "");*/ conn = dataSource.getConnection(); ps = conn.prepareStatement("select * from account where name=?"); String userName = principals.toString(); ps.setString(1, userName); rs = ps.executeQuery(); if (rs.next()) { Set<String> roles = new HashSet<String>(); roles.add(rs.getString(4)); info = new SimpleAuthorizationInfo(roles); } else { throw new AuthenticationException(); } } catch (SQLException e) { e.printStackTrace(); } finally{ JdbcUtils.closeResultSet(rs); JdbcUtils.closeConnection(conn); } return info; } }
package com.shiro.bean;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashSet;
import java.util.Set;

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.crypto.hash.SimpleHash;
import org.apache.shiro.realm.jdbc.JdbcRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.apache.shiro.util.JdbcUtils;

/**
 * @author layne Action方法中執行subject.login(token)時會通過IOC容器調取Realm域進行數據和前端數據比對
 */

//public class ShiroRealm extends  AuthorizingRealm {
public class ShiroRealm extends JdbcRealm {
    /**
     * Returns all principals associated with the corresponding Subject. Each
     * principal is an identifying piece of information useful to the
     * application such as a username, or user id, a given name, etc - anything
     * useful to the application to identify the current <code>Subject</code>.
     * The returned PrincipalCollection should <em>not</em> contain any
     * credentials used to verify principals, such as passwords, private keys,
     * etc. Those should be instead returned by {@link #getCredentials()
     * getCredentials()}.
     * 
     * @return all principals associated with the corresponding Subject.
     * 
     *         doGetAuthenticationInfo,獲取認證消息,如果數據庫沒有數據,返回null.
     *         AuthenticationInfo可以使用 SimpleAuthenticationInfo實現類,封裝給正確用戶名和密碼
     *         token參數:需要驗證的token
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(
            AuthenticationToken token) throws AuthenticationException {
        /**
         * 1.將token轉換為UsernamePasswordToken 2.獲取用戶名 3.查詢數據庫,進行驗證 4.結果返回
         * 5.驗證不通過,拋出異常
         */
        // 1.將token轉換為UsernamePasswordToken
        UsernamePasswordToken upToken = (UsernamePasswordToken) token;
        // 2.獲取用戶名
        String userName = upToken.getUsername();
        // 獲取用戶名后。通過查詢用戶名查詢數據庫是否有值,有值則進行密碼驗證。
        SimpleAuthenticationInfo info = null;
        // 3。查詢數據庫
        // 使用JDBC鏈接數據庫進行查詢
        
        Connection conn =null;
        ResultSet rs  =null;
        try {
            /*Class.forName("com.mysql.jdbc.Driver");
            String url = "jdbc:mysql://localhost:3306/test";
            Connection conn = DriverManager.getConnection(url, "root", "");*/
            conn = dataSource.getConnection();
            PreparedStatement ps = conn.prepareStatement("select * from account where name=?");
            ps.setString(1, userName);
            rs = ps.executeQuery();
            if (rs.next()) {
                Object principal = userName;
                Object credentials = rs.getString(3);
                String realmName = this.getName();
                // 設置鹽值
                ByteSource salt = ByteSource.Util.bytes(userName);
                // SimpleHash sh=new SimpleHash(algorithmName, source, salt,
                // iterations);
                // 加密類型 加密資源 鹽值加密 加密次數
                // 給從數據庫中拿到的密碼做MD5的加密
                SimpleHash sh = new SimpleHash("MD5", credentials, salt, 1024);
                // info = new SimpleAuthenticationInfo(principal, credentials,
                // realmName);
                // info = new SimpleAuthenticationInfo(principal, sh,
                // realmName);
                // 通過關於鹽值的構造器,將前端傳入的密碼在加密時再加入鹽值
                info = new SimpleAuthenticationInfo(principal, sh, salt,
                        realmName);
            } else {
                throw new AuthenticationException();
            }
        }catch (SQLException e) {
            e.printStackTrace();
        }finally{
            JdbcUtils.closeResultSet(rs);
            JdbcUtils.closeConnection(conn);
        }
        return info;
    }
    /**
     * 設置role驗證
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(
            PrincipalCollection principals) {
        // 返回值:AuthorizationInfo:封裝獲取用戶對應所有角色,SimpleAuthorizationInfo(Set<String>)
        // 參數列表:PrincipalCollection登錄的身份,登錄的用戶名
        SimpleAuthorizationInfo info = null;
        
        Connection conn =null;
        ResultSet rs  =null;
        try {
            /*Class.forName("com.mysql.jdbc.Driver");
            String url = "jdbc:mysql://localhost:3306/test";
            Connection conn = DriverManager.getConnection(url, "root", "");*/
            conn = dataSource.getConnection();
            PreparedStatement ps = conn.prepareStatement("select * from account where name=?");
            String userName = principals.toString();
            ps.setString(1, userName);
            rs = ps.executeQuery();
            if (rs.next()) {
                Set<String> roles = new HashSet<String>();
                roles.add(rs.getString(4));
                info = new SimpleAuthorizationInfo(roles);
            } else {
                throw new AuthenticationException();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }finally{
            JdbcUtils.closeResultSet(rs);
            JdbcUtils.closeConnection(conn);
        }
        return info;
    }
}
<?xml version="1.0" encoding="UTF-8"?>
<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.xsd">
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
       <property name="driverClass" value="${driverClass}"></property>
       <property name="jdbcUrl" value="${url}"></property>
       <property name="user" value="${user}"></property>
       <property name="password"  value="${password}"></property>
    </bean> 
    
    <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
      <property name="location"  value="classpath:hibernate.properties" />
    </bean>
    
    <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
        <property name="cacheManager" ref="cacheManager"/>
        <property name="authorizer" ref="authorizer"></property>
        <property name="authenticator" ref="authentictor"></property>
    </bean> 
    <bean id="authorizer" class="org.apache.shiro.authz.ModularRealmAuthorizer">
       <property name="realms">
          <list>
              <ref bean="jdbcRealm"/>
              <ref bean="defaultRealm"/>
          </list>
       </property>
    </bean>
    
    <bean id="authentictor"  class="org.apache.shiro.authc.pam.ModularRealmAuthenticator">
      <property name="realms">
          <list>
              <ref bean="jdbcRealm"/>
              <ref bean="defaultRealm"/>
          </list>
       </property>
    </bean>
     <!-- <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
        <property name="cacheManager" ref="cacheManager"/>
        <property name="auticationtor" ref="auticationtor"></property>
     </bean>
     <bean name="auticationtor" class="org.apache.shiro.authc.pam.ModularRealmAuthenticator">
        <property name="realms">
           <list>
                <ref bean=""/>
                <ref bean=""/>
           </list>
        </property>
        <property name="authenticationStrategy" ref="allSuccessfulStrategy"/>
     </bean>
     <bean id="allSuccessfulStrategy" class="org.apache.shiro.authc.pam.AllSuccessfulStrategy"/> -->
    
    <bean id="jdbcRealm" class="com.shiro.bean.ShiroRealm">
        <property name="dataSource" ref="dataSource"></property>
         <!-- 配置密碼加密使用MD5加密 -->
         <property name="credentialsMatcher">
           <bean class="org.apache.shiro.authc.credential.HashedCredentialsMatcher">
              <property name="hashAlgorithmName" value="MD5"></property>
              <property name="hashIterations" value="1024"></property>
           </bean>
         </property>
        
    </bean>
    
    <bean id="defaultRealm" class="com.shiro.bean.SecondRealm">
         <property name="dataSource" ref="dataSource"></property>
         <!-- 配置密碼加密使用SHA1加密 -->
         <property name="credentialsMatcher">
           <bean class="org.apache.shiro.authc.credential.HashedCredentialsMatcher">
              <property name="hashAlgorithmName" value="SHA1"></property>
              <property name="hashIterations" value="1024"></property>
           </bean>
         </property>
    </bean>
    <bean id="cacheManager" class="org.apache.shiro.cache.ehcache.EhCacheManager">
        <property name="cacheManagerConfigFile" value="classpath:ehcache.xml"/> 
    </bean>
   
    <!-- 必須要有這樣一個實例,用來管理在Spring容器當中的Shiro常見的對象 -->
    <bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor"/>
    <!-- 啟用Shiro注解 -->
    <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>
    <!-- 網絡方面 -->
    <bean id="secureRemoteInvocationExecutor" class="org.apache.shiro.spring.remoting.SecureRemoteInvocationExecutor">
        <property name="securityManager" ref="securityManager"/>
    </bean>
    <!-- 
                                         配置ShiroFilter
        1.shiroFilter這個bean的id必須與web.xml文件中的filter-name保持一致
     -->
    <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
        <property name="securityManager" ref="securityManager"/>
        <property name="loginUrl" value="/login.jsp"/>
        <property name="successUrl" value="/success.jsp"/>
        <property name="unauthorizedUrl" value="/adb.jsp"/>
        <!-- shiro過濾器具體配置 -->
        <property name="filterChainDefinitions">
            <value>
                /login.jsp = anon
                /login = anon
                /logout =logout
                /admin.jsp=roles[admin]
                /user.jsp=roles[user]
                /** = authc
            </value>
        </property>
    </bean>
</beans>
driverClass=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/test
user=root
password=
<?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:mvc="http://www.springframework.org/schema/mvc" 
        xmlns:context="http://www.springframework.org/schema/context" 
        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.xsd
            http://www.springframework.org/schema/context 
            http://www.springframework.org/schema/context/spring-context.xsd"> 
            <!-- 視圖資源管理器 -->
            <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
               <property name="prefix" value="/"></property>
               <property name="suffix" value=".jsp"></property>
            </bean>
            
            
            <context:component-scan base-package="*"></context:component-scan>
            <mvc:annotation-driven></mvc:annotation-driven>
            <mvc:default-servlet-handler/>
</beans>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM