Spring Security简介
Spring Security是一个能够为基于Spring的企业应用系统提供声明式的安全访问控制解决方案的安全框架。它提供了一组可以在Spring应用上下文中配置的Bean,充分利用了Spring IOC,DI(控制反转Inversion of Control ,DI:Dependency Injection 依赖注入)和AOP(面向切面编程)功能,为应用系统提供声明式的安全访问控制功能,减少了为企业系统安全控制编写大量重复代码的工作。
Spring Security入门小Demo
创建一个index.html
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title> </head> <body> 欢迎来到SpringSecurity安全世界! </body> </html>
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/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>cn.test.demo</groupId> <artifactId>spring-security-demo</artifactId> <version>1.0.0-SNAPSHOT</version> <packaging>war</packaging> <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>
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>
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"> <!-- 页面拦截规则 use-expressions:是否启动SPEL表达式,默认是true --> <http use-expressions="false"> <!-- 当前用户必须有ROLE_USER的角色,才可以访问根目录及所属子目录的资源 --> <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>
启动:右键项目 -> Run As -> Maven build
后台日志
[INFO] Scanning for projects... [WARNING] [WARNING] Some problems were encountered while building the effective model for cn.test.demo:spring-security-demo:war:1.0.0-SNAPSHOT [WARNING] 'build.plugins.plugin.version' for org.apache.tomcat.maven:tomcat7-maven-plugin is missing. @ line 74, column 16 [WARNING] [WARNING] It is highly recommended to fix these problems because they threaten the stability of your build. [WARNING] [WARNING] For this reason, future Maven versions might no longer support building such malformed projects. [WARNING] [INFO] [INFO] -----------------< cn.test.demo:spring-security-demo >------------------ [INFO] Building spring-security-demo 1.0.0-SNAPSHOT [INFO] --------------------------------[ war ]--------------------------------- [INFO] [INFO] >>> tomcat7-maven-plugin:2.2:run (default-cli) > process-classes @ spring-security-demo >>> [INFO] [INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ spring-security-demo --- [WARNING] Using platform encoding (UTF-8 actually) to copy filtered resources, i.e. build is platform dependent! [INFO] Copying 1 resource [INFO] [INFO] --- maven-compiler-plugin:3.2:compile (default-compile) @ spring-security-demo --- [INFO] Nothing to compile - all classes are up to date [INFO] [INFO] <<< tomcat7-maven-plugin:2.2:run (default-cli) < process-classes @ spring-security-demo <<< [INFO] [INFO] [INFO] --- tomcat7-maven-plugin:2.2:run (default-cli) @ spring-security-demo --- [INFO] Running war on http://localhost:9090/ [INFO] Using existing Tomcat server configuration at E:eclipse-2018-12-workspacespring-security-demo arget omcat [INFO] create webapp with contextPath: 九月 24, 2019 1:40:43 下午 org.apache.coyote.AbstractProtocol init 信息: Initializing ProtocolHandler ["http-bio-9090"] 九月 24, 2019 1:40:43 下午 org.apache.catalina.core.StandardService startInternal 信息: Starting service Tomcat 九月 24, 2019 1:40:43 下午 org.apache.catalina.core.StandardEngine startInternal 信息: Starting Servlet Engine: Apache Tomcat/7.0.47 九月 24, 2019 1:40:46 下午 org.apache.catalina.core.ApplicationContext log 信息: No Spring WebApplicationInitializer types detected on classpath 九月 24, 2019 1:40:46 下午 org.apache.catalina.core.ApplicationContext log 信息: Initializing Spring root WebApplicationContext 九月 24, 2019 1:40:46 下午 org.springframework.web.context.ContextLoader initWebApplicationContext 信息: Root WebApplicationContext: initialization started 九月 24, 2019 1:40:46 下午 org.springframework.web.context.support.XmlWebApplicationContext prepareRefresh 信息: Refreshing Root WebApplicationContext: startup date [Tue Sep 24 13:40:46 CST 2019]; root of context hierarchy 九月 24, 2019 1:40:46 下午 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions 信息: Loading XML bean definitions from class path resource [spring-security.xml] 九月 24, 2019 1:40:47 下午 org.springframework.security.core.SpringSecurityCoreVersion performVersionChecks 信息: You are running with Spring Security Core 4.1.0.RELEASE 九月 24, 2019 1:40:47 下午 org.springframework.security.core.SpringSecurityCoreVersion performVersionChecks 警告: **** You are advised to use Spring 4.2.5.RELEASE or later with this version. You are running: 4.2.4.RELEASE 九月 24, 2019 1:40:47 下午 org.springframework.security.config.SecurityNamespaceHandler <init> 信息: Spring Security 'config' module version is 4.1.0.RELEASE 九月 24, 2019 1:40:47 下午 org.springframework.security.config.http.AuthenticationConfigBuilder createLoginPageFilterIfNeeded 信息: No login page configured. The default internal one will be used. Use the 'login-page' attribute to set the URL of the login page. 九月 24, 2019 1:40:47 下午 org.springframework.security.config.http.HttpSecurityBeanDefinitionParser checkFilterChainOrder 信息: Checking sorted filter chain: [Root bean: class [org.springframework.security.web.context.SecurityContextPersistenceFilter]; scope=; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null, order = 200, Root bean: class [org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter]; scope=; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null, order = 400, Root bean: class [org.springframework.security.web.header.HeaderWriterFilter]; scope=; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null, order = 500, Root bean: class [org.springframework.security.web.csrf.CsrfFilter]; scope=; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null, order = 600, <org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter#0>, order = 1100, Root bean: class [org.springframework.security.web.authentication.ui.DefaultLoginPageGeneratingFilter]; scope=; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null, order = 1300, Root bean: class [org.springframework.security.web.savedrequest.RequestCacheAwareFilter]; scope=; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null, order = 1600, Root bean: class [org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter]; scope=; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null, order = 1700, Root bean: class [org.springframework.security.web.authentication.AnonymousAuthenticationFilter]; scope=; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null, order = 2000, Root bean: class [org.springframework.security.web.session.SessionManagementFilter]; scope=; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null, order = 2100, Root bean: class [org.springframework.security.web.access.ExceptionTranslationFilter]; scope=; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null, order = 2200, <org.springframework.security.web.access.intercept.FilterSecurityInterceptor#0>, order = 2300] 九月 24, 2019 1:40:47 下午 org.springframework.security.web.DefaultSecurityFilterChain <init> 信息: Creating filter chain: org.springframework.security.web.util.matcher.AnyRequestMatcher@1, [org.springframework.security.web.context.SecurityContextPersistenceFilter@127d0515, org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter@48819a8b, org.springframework.security.web.header.HeaderWriterFilter@10f5eea8, org.springframework.security.web.csrf.CsrfFilter@51494bec, org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter@2be6b97d, org.springframework.security.web.authentication.ui.DefaultLoginPageGeneratingFilter@6f773b48, org.springframework.security.web.savedrequest.RequestCacheAwareFilter@504818a0, org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter@4b453f6e, org.springframework.security.web.authentication.AnonymousAuthenticationFilter@55f65a2a, org.springframework.security.web.session.SessionManagementFilter@38d86a7, org.springframework.security.web.access.ExceptionTranslationFilter@1390036e, org.springframework.security.web.access.intercept.FilterSecurityInterceptor@71ccf03d] 九月 24, 2019 1:40:47 下午 org.springframework.security.config.http.DefaultFilterChainValidator checkLoginPageIsntProtected 信息: Checking whether login URL '/login' is accessible with your configuration 九月 24, 2019 1:40:47 下午 org.springframework.web.context.ContextLoader initWebApplicationContext 信息: Root WebApplicationContext: initialization completed in 859 ms 九月 24, 2019 1:40:47 下午 org.apache.coyote.AbstractProtocol start 信息: Starting ProtocolHandler ["http-bio-9090"]
打开浏览器访问:http://localhost:9090/
如果用户名和密码不是登陆的角色不是ROLE_USER的话,提示如下
如果输入正确,提示如下
配置说明
intercept-url:表示拦截页面
/*:表示的是该目录下的资源,只包括本级目录不包括下级目录
/**:表示的是该目录以及该目录下所有级别子目录的资源
form-login:为开启表单登陆
use-expressions:为是否使用Spring表达式语言(SPEL),默认为true,如果开启,则拦截的配置应该写成以下形式
<intercept-url pattern="/**" access="hasRole('ROLE_USER')" />