學習Spring-security (2)

Maven項目建立好以後,並加載好對應的Jar包依賴以後。css

接着搭建Spring-Security環境java

注意:使用Spring-Security 必須得加載Spring框架的依賴包 (Spring,Common等等Jar)mysql

  1. 配置web.xml 加載Spring容器的監聽器 ContextLoaderListener
  2. 加載Spring-Security的攔截器 filter.DelegatingFilterProxy
  3. 加載上述兩個的配置文件 

   web.xml配置文件以下:web

<?xml version="1.0"?>
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
                         "http://java.sun.com/dtd/web-app_2_3.dtd">
<web-app>
 <display-name>Archetype Created Web Application</display-name>
 <context-param>
  <param-name>contextConfigLocation</param-name>
  <param-value>classpath:applicationContext.xml,
        classpath:applicationContext-security.xml</param-value>
 </context-param>
 <!-- SpringSecurity 核心過濾器配置 -->
 <filter>
  <filter-name>springSecurityFilterChain</filter-name>
  <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
 </filter>
 <filter-mapping>
  <filter-name>springSecurityFilterChain</filter-name>
  <url-pattern>/*</url-pattern>
 </filter-mapping>
 <listener>
  <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
 </listener>
 <login-config>
  <auth-method>BASIC</auth-method>
 </login-config>
</web-app>

      配置Spring-security.xml文件 以下:spring

<?xml version="1.0" encoding="UTF-8"?>  
<beans xmlns="http://www.springframework.org/schema/beans"  
    xmlns:sec="http://www.springframework.org/schema/security"  
    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-3.0.xsd  
        http://www.springframework.org/schema/security  
        http://www.springframework.org/schema/security/spring-security-3.2.xsd">  
  
    <!-- 配置不過濾的資源(靜態資源及登陸相關) -->  
    <sec:http pattern="/**/*.css" security="none"></sec:http>  
    <sec:http pattern="/**/*.jpg" security="none"></sec:http>  
    <sec:http pattern="/**/*.jpeg" security="none"></sec:http>  
    <sec:http pattern="/**/*.gif" security="none"></sec:http>  
    <sec:http pattern="/**/*.png" security="none"></sec:http>  
    <sec:http pattern="/js/*.js" security="none"></sec:http>  
      
    <sec:http pattern="/login.jsp" security="none"></sec:http>  
    <sec:http pattern="/getCode" security="none" /><!-- 不過濾驗證碼 -->  
    <sec:http pattern="/test/**" security="none"></sec:http><!-- 不過濾測試內容 -->  
      
    <sec:http auto-config="true">  
        <!-- 配置資源連接過濾,表示意思爲:訪問/app.jsp 須要ROLE_SERVICE 權限 -->
        <sec:intercept-url pattern="/app.jsp" access="ROLE_SERVICE"/>  
         <!-- 配置資源連接過濾,表示意思爲:訪問全部資源   須要ROLE_ADMIN 權限 -->
        <sec:intercept-url pattern="/**" access="ROLE_ADMIN"/>  
        <!-- 注意,Spring-security採用從上到下過濾,你訪問的連接 Spring從上面開始往下找。上面的優先級比下面的優先級高。-->
        
        <!-- 
        	自定義登錄頁面,login-page 自定義登錄頁面
        	authentication-failure-url 用戶權限校驗失敗以後纔會跳轉到這個頁面,若是數據庫中沒有這個用戶則不會跳轉到這個頁面。
        	default-target-url 登錄成功後跳轉的頁面。
        	注:登錄頁面用戶名固定 name:j_username,密碼 name:j_password,action:/j_spring_security_check
         -->
        <sec:form-login login-page="/login.jsp" authentication-failure-url="/loginfail.jsp" default-target-url="/index.jsp"/>
        
        <!-- 
        	登出, invalidate-session 是否刪除session
			logout-url:登出處理連接
			logout-success-url:登出成功頁面
			注:登出操做 只須要連接到 logout便可登出當前用戶        	
        -->
        <sec:logout invalidate-session="true" logout-url="/logout" logout-success-url="/login.jsp"/>      
    </sec:http>  

    <!-- 權限管理器,用來查詢用戶的全部權限使用。登錄用戶以後,由這個攔截器來查詢用戶,分配對應的權限 ,而後分配給sec:http 來作對應的攔截-->
    <sec:authentication-manager>  
    	<!-- 手動定義一個用戶以及對應的權限 -->
        <sec:authentication-provider>  
            <sec:user-service >  
                <sec:user name="admin" password="admin" authorities="ROLE_ADMIN"/>  
            </sec:user-service>  
        </sec:authentication-provider>
        <!-- 本身定義 一個類處理用戶登錄的時候,用戶名,密碼,權限獲取-->
        <sec:authentication-provider user-service-ref="Userservices"></sec:authentication-provider>
        <!-- 直接經過SQL來獲取數據庫中的用戶名,密碼,權限-->
        <sec:authentication-provider>
        	<sec:jdbc-user-service data-source-ref="Datasource" authorities-by-username-query="select b.username as username,a.ROLE_CODE as authority from ZX_ROLE a left join ZX_USER b on a.USER_ID=b.ID where b.username=?" 
				users-by-username-query="select username,password,enable as status from ZX_USER where username=?"/>
        </sec:authentication-provider>
    </sec:authentication-manager>  
</beans>

配置applicationContext.xml文件以下:sql

<?xml version="1.0" encoding="UTF-8"?>  
<beans xmlns="http://www.springframework.org/schema/beans"  
    xmlns:sec="http://www.springframework.org/schema/security"  
    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-3.0.xsd  
        http://www.springframework.org/schema/security  
        http://www.springframework.org/schema/security/spring-security-3.1.xsd">  
        
        <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
        	<property name="dataSource" ref="Datasource"></property>
        	<property name="mappingLocations">
        		<list>
        			<value>classpath*:/hibernate/*.hbm.xml</value>
        		</list>
        	</property>
        </bean>
        <!-- 
        	這個類爲用戶登錄 處理類,須要實現UserDetailsService接口  
        	重寫 loadUserByUsername 方法,而且注意  此方法的返回值爲UserDetails類型
        	而UserDetails 是一個接口,因此應該返回他的實現類 org.springframework.security.core.userdetails.User
        	注意org.springframework.security.core.userdetails.User的參數 有七個
        	username,用戶登錄名
        	password,密碼
        	enabled,是否可用
        	accountNonExpired,set to true if the account has not expired
			credentialsNonExpired, set to true if the credentials have not expired
			accountNonLocked, set to true if the account is not locked
			authorities,是用戶的權限集合 泛型爲<?  extends GrantedAuthority> collection
			因此這個值須要咱們定義一個泛型爲GrantedAuthority(這是一個接口 ,他的實現類爲GrantedAuthorityImpl)集合
			咱們查詢出對應的用戶角色後 遍歷 而且實例化GrantedAuthorityImpl 設置對應的角色代碼 放入集合
			最後返回org.springframework.security.core.userdetails.User便可
        -->
        <bean id="Datasource" class="org.apache.commons.dbcp.BasicDataSource">
        	<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
        	<property name="url" value="*"></property>
        	<property name="username" value="**"></property>
        	<property name="password" value="***"></property>
        </bean>
    	<bean id="Userservices" class="services.userserviceDaoImp">
    		<property name="udi" ref="userdaoimp"></property>
    	</bean>
    	<bean id="userdaoimp" class="Dao.userDaoimp">
    		<property name="sessionFactory" ref="sessionFactory"></property>
    	</bean>
</beans>

用戶登錄操做類 以下:數據庫

package services;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import hibernate.Role;
import hibernate.User;

import org.springframework.security.config.http.UserDetailsServiceFactoryBean;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.GrantedAuthorityImpl;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import Dao.userDaoimp;


public class userserviceDaoImp implements UserDetailsService{
	private userDaoimp udi;
	public UserDetails loadUserByUsername(String username)
			throws UsernameNotFoundException {
		System.out.println(username);
		System.out.println(udi.getSessionFactory());
		User u=udi.getUserByname(username);
		System.out.println(u.toString());
		List<Role> list=udi.getRoleByUser(u);
		List<GrantedAuthority> rolelist=new ArrayList<GrantedAuthority>();
		for (int i = 0; i < list.size(); i++) {
			Role rol=list.get(i);
			System.out.println(rol.getRoleCode());
			GrantedAuthorityImpl gi=new GrantedAuthorityImpl(rol.getRoleCode());
			rolelist.add(gi);
		}
		org.springframework.security.core.userdetails.User user=new org.springframework.security.core.userdetails.User(u.getUsername(), u.getPassword(),true, true, true, true, rolelist);
		return user;
	}
	public userDaoimp getUdi() {
		return udi;
	}
	public void setUdi(userDaoimp udi) {
		this.udi = udi;
	}
	
}

這樣 整個配置完成apache

 

注意:我的管理器(userserviceDaoImp )必須繼承 UserDetailsService 。可是其中權限的處理方法可能不一樣。上述的方法適用於Spring Security 3.*版本 對於Spring Security 4.*的話 處理方法不一樣 以下:session

public class AuthuserService extends SqlSessionTemplate implements UserDetailsService{
	public AuthuserService(SqlSessionFactory sqlSessionFactory) {
		super(sqlSessionFactory);
	}

	public UserDetails loadUserByUsername(String username)
			throws UsernameNotFoundException {
		UserServices us=new UserServices(getSqlSessionFactory());
		List<role> list=us.getRoleByusername(username);
		System.out.println(list);
		List<GrantedAuthority> rolelist=new ArrayList<GrantedAuthority>();
		for (int i = 0; i < list.size(); i++) {
			role rol=list.get(i);
			System.out.println(rol.getRoleCode());
            //在Spring Security 4.*中移除了GrantedAuthorityImpl類。添加了SimpleGrantedAuthority
            //咱們對權限的封裝將採用這個類
			GrantedAuthority gi=new SimpleGrantedAuthority(rol.getRoleCode());
			rolelist.add(gi);
		}
		return new  User(username, "password", rolelist);
	}
	
}
相關文章
相關標籤/搜索