Spring Security是一個可以爲基於Spring的企業應用系統提供聲明式的安全訪問控制解決方案的安全框架。它提供了一組能夠在Spring應用上下文中配置的Bean,充分利用了Spring IoC,DI(控制反轉Inversion of Control ,DI:Dependency Injection 依賴注入)和AOP(面向切面編程)功能,爲應用系統提供聲明式的安全訪問控制功能,減小了爲企業系統安全控制編寫大量重複代碼的工做。
(1)建立工程spring_security_demo ,pom.xml內容
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>cn.itcast.demo</groupId> <artifactId>spring-security-demo</artifactId> <packaging>war</packaging> <version>0.0.1-SNAPSHOT</version> <properties> <spring.version>4.2.4.RELEASE</spring.version> </properties> <dependencies> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context-support</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-web</artifactId> <version>4.1.0.RELEASE</version> </dependency> <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-config</artifactId> <version>4.1.0.RELEASE</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>servlet-api</artifactId> <version>2.5</version> <scope>provided</scope> </dependency> </dependencies> <build> <plugins> <!-- java編譯插件 --> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.2</version> <configuration> <source>1.7</source> <target>1.7</target> <encoding>UTF-8</encoding> </configuration> </plugin> <plugin> <groupId>org.apache.tomcat.maven</groupId> <artifactId>tomcat7-maven-plugin</artifactId> <configuration> <!-- 指定端口 --> <port>9090</port> <!-- 請求路徑 --> <path>/</path> </configuration> </plugin> </plugins> </build> </project>
(2)建立web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5"> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring-security.xml</param-value> </context-param> <listener> <listener-class> org.springframework.web.context.ContextLoaderListener </listener-class> </listener> <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> </web-app>
(3)建立index.html 內容略(IDEA的index.jsp也可用) (4)建立spring 配置文件spring-security.xml
<?xml version="1.0" encoding="UTF-8"?> <beans:beans xmlns="http://www.springframework.org/schema/security" xmlns:beans="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 http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security.xsd"> <!-- 頁面攔截規則 --> <http use-expressions="false"> <intercept-url pattern="/**" access="ROLE_USER" /> <form-login/> </http> <!-- 認證管理器 --> <authentication-manager> <authentication-provider> <user-service> <user name="admin" password="123456" authorities="ROLE_USER"/> </user-service> </authentication-provider> </authentication-manager> </beans:beans>
**配置說明**: intercept-url 表示攔截頁面 // 表示的是該目錄下的資源,只包括本級目錄不包括下級目錄 // 表示的是該目錄以及該目錄下全部級別子目錄的資源 form-login 爲開啓表單登錄
use-expressions 爲是否使用使用 Spring 表達式語言( SpEL ),默認爲true ,若是開啓,則攔截的配置寫成如下形式css
<intercept-url pattern="/**" access="hasRole('ROLE_USER')" />
此時啓動localhost:9090就能看到登錄頁面html
pom.xmljava
<dependencies> <!--公共組件--> <dependency> <groupId>com.yh</groupId> <artifactId>yh_common</artifactId> <version>1.0-SNAPSHOT</version> </dependency> <!-- Spring --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-beans</artifactId> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aspects</artifactId> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jms</artifactId> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context-support</artifactId> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> </dependency> <!--認證相關--> <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-web</artifactId> </dependency> <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-config</artifactId> </dependency> <!-- dubbo相關 --> <dependency> <groupId>com.alibaba</groupId> <artifactId>dubbo</artifactId> </dependency> <dependency> <groupId>org.apache.zookeeper</groupId> <artifactId>zookeeper</artifactId> </dependency> <dependency> <groupId>com.github.sgroschupf</groupId> <artifactId>zkclient</artifactId> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> </dependency> <dependency> <groupId>org.javassist</groupId> <artifactId>javassist</artifactId> <version>3.23.1-GA</version> </dependency> <dependency> <groupId>commons-codec</groupId> <artifactId>commons-codec</artifactId> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>servlet-api</artifactId> <scope>provided</scope> </dependency> <dependency> <groupId>com.yh</groupId> <artifactId>yh_sellergoods_interface</artifactId> <version>1.0-SNAPSHOT</version> </dependency> <!-- 文件上傳組件 --> <dependency> <groupId>org.csource.fastdfs</groupId> <artifactId>fastdfs</artifactId> </dependency> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.apache.tomcat.maven</groupId> <artifactId>tomcat7-maven-plugin</artifactId> <version>2.2</version> <configuration> <!-- 指定端口 --> <port>9102</port> <!-- 請求路徑 --> <path>/</path> </configuration> </plugin> </plugins> </build>
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5"> <!-- 解決post亂碼 --> <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> <servlet> <servlet-name>springmvc</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <!-- 指定加載的配置文件 ,經過參數contextConfigLocation加載--> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring/spring*.xml</param-value> </init-param> <load-on-startup>2</load-on-startup> </servlet> <servlet-mapping> <servlet-name>springmvc</servlet-name> <url-pattern>*.do</url-pattern> </servlet-mapping> <context-param> <param-name>contextConfigLocation</param-name> <!--加載common中的配置文件 要使用 classpath*--> <param-value>classpath:spring/spring*.xml,classpath*:spring/applicationContext*.xml</param-value> </context-param> <listener> <listener-class> org.springframework.web.context.ContextLoaderListener </listener-class> </listener> <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> </web-app>
<?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:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" xmlns:dubbo="http://code.alibabatech.com/schema/dubbo" xmlns:mvc="http://www.springframework.org/schema/mvc" 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://code.alibabatech.com/schema/dubbo http://code.alibabatech.com/schema/dubbo/dubbo.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <context:property-placeholder location="classpath:config/application.properties"/> <!-- 配置多媒體解析器 --> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <property name="defaultEncoding" value="UTF-8"></property> <!-- 設定文件上傳的最大值5MB,5*1024*1024 --> <property name="maxUploadSize" value="5242880"></property> </bean> <mvc:annotation-driven> <mvc:message-converters register-defaults="true"> <bean class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter"> <property name="supportedMediaTypes" value="application/json"/> <property name="features"> <array> <value>WriteMapNullValue</value> <value>WriteDateUseDateFormat</value> </array> </property> </bean> </mvc:message-converters> </mvc:annotation-driven> <!-- 引用dubbo 服務 --> <!--<dubbo:application name="yh_shop_web"/>--> <!--<dubbo:registry address="zookeeper://192.168.80.128:2181"/>--> <!--<dubbo:annotation package="com.yh.shop.controller"/>--> </beans>
<?xml version="1.0" encoding="UTF-8"?> <beans:beans xmlns="http://www.springframework.org/schema/security" xmlns:beans="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:dubbo="http://code.alibabatech.com/schema/dubbo" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://code.alibabatech.com/schema/dubbo http://code.alibabatech.com/schema/dubbo/dubbo.xsd"> <!--容許匿名訪問的資源--> <http pattern="/shoplogin.html" security="none"></http> <http pattern="/register.html" security="none"></http> <http pattern="/seller/add.do" security="none"></http> <http pattern="/css/**" security="none"></http> <http pattern="/img/**" security="none"></http> <http pattern="/js/**" security="none"></http> <http pattern="/plugins/**" security="none"></http> <!--攔截規則--> <!--不使用表達式--> <http> <!--攔截全部根目錄資源及其子目錄--> <intercept-url pattern="/**" access="hasRole('ROLE_SELLER')"></intercept-url> <!--自定義登錄頁面 登錄成功跳轉頁面 指定了是否在身份驗證經過後老是跳轉到default-target-url屬性指定的URL。--> <!--指定用戶名密碼的name username-parameter="username" password-parameter="password"--> <form-login login-page="/shoplogin.html" default-target-url="/admin/index.html" always-use-default-target="true"/> <logout/> <csrf disabled="true"></csrf> <!--請求過濾--> <headers> <!--容許同源訪問--> <frame-options policy="SAMEORIGIN"/> </headers> </http> <authentication-manager> <!--實現接口 查詢用戶--> <authentication-provider user-service-ref="userDetailService"> <password-encoder ref="bCryptPasswordEncoder"></password-encoder> </authentication-provider> </authentication-manager> <!-- 引用dubbo 服務 --> <dubbo:application name="yh_shop_web"/> <dubbo:registry address="zookeeper://192.168.80.128:2181"/> <dubbo:annotation package="com.yh"/> <beans:bean id="userDetailService" class="com.yh.page.service.UserDetailServiceImpl"></beans:bean> <beans:bean id="bCryptPasswordEncoder" class="org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder"></beans:bean> </beans:beans>
package com.yh.page.service; import com.alibaba.dubbo.config.annotation.Reference; import com.yh.pojo.TbSeller; import com.yh.sellergoods.service.SellerService; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.userdetails.User; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.stereotype.Component; import java.util.ArrayList; / 實現userdetail接口 用於驗證前臺輸入用戶信息匹配 <p> 須要讓接口掃描到這個類 / @Component public class UserDetailServiceImpl implements UserDetailsService { //遠程調用dubbo提供的服務 可是此時尚未 @Reference public SellerService sellerService; @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { TbSeller seller = sellerService.findOne(username); System.out.println(seller); //沒找到用戶 或者用戶沒有經過審覈 if (seller == null || !"1".equals(seller.getStatus())) { return null; } ArrayList<GrantedAuthority> list = new ArrayList<>(); list.add(new SimpleGrantedAuthority("ROLE_SELLER")); return new User(username, seller.getPassword(), list); } }
# connect timeout in seconds # default value is 30s connect_timeout=30 # network timeout in seconds # default value is 30s network_timeout=60 # the base path to store log files base_path=/home/fastdfs # tracker_server can ocur more than once, and tracker_server format is # "host:port", host can be hostname or ip address tracker_server=172.16.224.128:22122 #standard log level as syslog, case insensitive, value list: ### emerg for emergency ### alert ### crit for critical ### error ### warn for warning ### notice ### info ### debug log_level=info # if use connection pool # default value is false # since V4.05 use_connection_pool = false # connections whose the idle time exceeds this time will be closed # unit: second # default value is 3600 # since V4.05 connection_pool_max_idle_time = 3600 # if load FastDFS parameters from tracker server # since V4.05 # default value is false load_fdfs_parameters_from_tracker=false # if use storage ID instead of IP address # same as tracker.conf # valid only when load_fdfs_parameters_from_tracker is false # default value is false # since V4.05 use_storage_id = false # specify storage ids filename, can use relative or absolute path # same as tracker.conf # valid only when load_fdfs_parameters_from_tracker is false # since V4.05 storage_ids_filename = storage_ids.conf #HTTP settings http.tracker_server_port=80 #use "#include" directive to include HTTP other settiongs ##include http.conf
package com.yh.shop.controller; import entity.Result; import org.springframework.beans.factory.annotation.Value; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.multipart.MultipartFile; import utils.FastDFSClient; // 文件上傳controller @RestController public class UploadController { @Value("${FILE_SERVER_URL}") public String FILE_SERVER_URL; @RequestMapping("upload") public Result upload(MultipartFile file) { //文件名稱 //String originalFilename = file.getOriginalFilename(); //獲取擴展名稱 //String extName = originalFilename.substring(originalFilename.lastIndexOf(".") + 1); String extName = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".")+1); try { //建立fastdfs客戶端 FastDFSClient fastDFSClient = new FastDFSClient("classpath:config/fdfs_client.conf"); //返回圖片路徑 String path = fastDFSClient.uploadFile(file.getBytes(), extName); System.out.println(path); return new Result(true, FILE_SERVER_URL + path); } catch (Exception e) { e.printStackTrace(); return new Result(false, "上傳失敗"); } } }