一、spring security的模块
搭建spring security首先我们要导入必须的jar,即maven的依赖。spring security按模块划分,一个模块对应一个jar。
spring security分为以下九个模块:
1.Core spring-security-core.jar:核心模块。包含核心的认证(authentication)和授权(authorization)的类和接口,远程支持和基础配置API。
2.Remoting spring-security-remoting.jar:提供与spring remoting整合的支持。
3.Web spring-security-web.jar:包含过滤器和相关的网络安全的代码。用于我们进行web安全验证和基于URL的访问控制。
4.Config spring-security-config.jar:包含security namepace的解析代码。
5.LDAP spring-security-ldap.jar:提供LDAP验证和配置的支持。
6.ACL spring-security-acl.jar:提供对特定domain对象的ACL(访问控制列表)实现。用来限定对特定对象的访问
7.CAS sprig-security-cas.jar:提供与spring security CAS客户端集成
8.OpenID spring-security-openid.jar:提供OpenId Web验证支持。基于一个外部OpenId服务器对用户进行验证。
9.Test spring-security-test.jar:提供spring security的测试支持。
一般情况下,Core和Config模块都是需要的,因为我们本教程只是用于Java web应用表单的验证登录,所以这里我们还需要引入Web。
说明:本篇教程的代码已上传github,地址:https://github.com/wutianqi/spring_security_create
二、搭建
1.项目工程结构
2.代码展示
2.1 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>com.wuqi</groupId> <artifactId>spring_security_create</artifactId> <packaging>war</packaging> <version>0.0.1-SNAPSHOT</version> <name>spring_security_create Maven Webapp</name> <url>http://maven.apache.org</url> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <!-- web --> <jsp.version>2.2</jsp.version> <servlet.version>3.1.0</servlet.version> <jstl.version>1.2</jstl.version> <!-- spring 和 spring security --> <spring-security.version>4.2.3.RELEASE</spring-security.version> <spring-framework.version>4.3.11.RELEASE</spring-framework.version> <!-- Logging --> <logback.version>1.0.13</logback.version> <slf4j.version>1.7.5</slf4j.version> </properties> <dependencies> <!-- spring --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${spring-framework.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> <version>${spring-framework.version}</version> </dependency> <!-- spring security --> <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-core</artifactId> <version>${spring-security.version}</version> </dependency> <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-web</artifactId> <version>${spring-security.version}</version> </dependency> <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-config</artifactId> <version>${spring-security.version}</version> </dependency> <!-- 其他一些依赖 --> <dependency> <groupId>javax</groupId> <artifactId>javaee-web-api</artifactId> <version>7.0</version> <scope>provided</scope> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>${servlet.version}</version> <scope>provided</scope> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>${jstl.version}</version> </dependency> <dependency> <groupId>javax.servlet.jsp</groupId> <artifactId>jsp-api</artifactId> <version>${jsp.version}</version> <scope>provided</scope> </dependency> <dependency> <groupId>com.fasterxml.jackson.dataformat</groupId> <artifactId>jackson-dataformat-xml</artifactId> <version>2.5.3</version> </dependency> <!-- 日志 --> <!-- 使用SLF4J和LogBack作为日志 --> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>${slf4j.version}</version> </dependency> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.16</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>jcl-over-slf4j</artifactId> <version>${slf4j.version}</version> </dependency> <!--logback日志--> <dependency> <groupId>ch.qos.logback</groupId> <artifactId>logback-core</artifactId> <version>${logback.version}</version> </dependency> <!--实现slf4j接口并整合--> <dependency> <groupId>ch.qos.logback</groupId> <artifactId>logback-classic</artifactId> <version>${logback.version}</version> </dependency> <dependency> <groupId>ch.qos.logback</groupId> <artifactId>logback-access</artifactId> <version>${logback.version}</version> </dependency> </dependencies> <build> <finalName>spring_security_create</finalName> <plugins> <!-- 配置maven的内嵌的tomcat,通过内置的tomcat启动 --> <plugin> <groupId>org.apache.tomcat.maven</groupId> <artifactId>tomcat7-maven-plugin</artifactId> <version>2.2</version> <configuration> <uriEncoding>utf8</uriEncoding> <!-- 配置启动的端口为9090 --> <port>9090</port> <path>/</path> </configuration> </plugin> </plugins> </build> </project>
该pom文件除了包括了spring security的依赖外,还包括了spring、springmvc、日志的一些依赖,除了spring security的依赖,其他的你没必要太过于纠结。直接拿过来用就可以了。日志我使用了logback,这个你也直接拿过来用就行了,直接将logback.xml放在你的类路径下就可以起作用了。而且这些知识也不是本篇教程所讨论的。
2.2 MyWebConfig
package com.wuqi.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; import org.springframework.web.servlet.view.InternalResourceViewResolver; import org.springframework.web.servlet.view.JstlView; /** * MVC配置类 * @author wuqi * @date 2018/06/13 */ @EnableWebMvc @Configuration @ComponentScan("com.wuqi") public class MyWebConfig extends WebMvcConfigurerAdapter { //配置mvc视图解析器 @Bean public InternalResourceViewResolver viewResolver() { InternalResourceViewResolver viewResolver = new InternalResourceViewResolver(); viewResolver.setPrefix("/WEB-INF/classes/views/"); viewResolver.setSuffix(".jsp"); viewResolver.setViewClass(JstlView.class); return viewResolver; } }
MyWebConfig是SpringMvc的配置类,这里只配置了视图解析器
2.3 WebInitializer
package com.wuqi.config; import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer; /** * 替代web.xml的配置 * @author wuqi * @date 2018/06/13 */ public class WebInitializer extends AbstractAnnotationConfigDispatcherServletInitializer { @Override protected Class<?>[] getRootConfigClasses() { return null; } @Override protected Class<?>[] getServletConfigClasses() { return new Class[] {MyWebConfig.class}; } @Override protected String[] getServletMappings() { //将DispatcherServlet映射到 / return new String[] {"/"}; } }
WebInitializer相当于在web.xml中注册DispatcherServlet,以及配置Spring Mvc的配置文件
2.4 MySecurityConfig
package com.wuqi.config; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; /** * spring security配置类 * @author wuqi * @date 2018/06/13 */ @EnableWebSecurity @Configuration public class MySecurityConfig extends WebSecurityConfigurerAdapter { @Autowired public void configUser(AuthenticationManagerBuilder builder) throws Exception { builder .inMemoryAuthentication() //创建用户名为user,密码为password的用户 .withUser("user").password("password").roles("USER"); } }
MySecurityConfig是spring security的配置类,定制spring security的一些行为就在这里。其中@EnableWebSecurity用于创建过滤器
2.5 SecurityInitializer
package com.wuqi.config; import org.springframework.security.web.context.AbstractSecurityWebApplicationInitializer; /** * security初始化类,用户注册过滤器 * @author wuqi * @date 2018/06/13 */ public class SecurityInitializer extends AbstractSecurityWebApplicationInitializer { }
SecurityInitializer主要就是用于注册spring secuirty的过滤器
2.6 logback.xml
<?xml version="1.0" encoding="UTF-8"?> <configuration scan="true" scanPeriod="1 seconds"> <contextListener class="ch.qos.logback.classic.jul.LevelChangePropagator"> <resetJUL>true</resetJUL> </contextListener> <jmxConfigurator /> <appender name="console" class="ch.qos.logback.core.ConsoleAppender"> <encoder> <pattern>logbak: %d{HH:mm:ss.SSS} %logger{36} - %msg%n</pattern> </encoder> </appender> <logger name="org.springframework.security.web" level="DEBUG" /> <logger name="org.springframework.security" level="DEBUG" /> <logger name="org.springframework.security.config" level="DEBUG" /> <root level="INFO"> <appender-ref ref="console" /> </root> </configuration>
该日志文件就是将web、core、config模块的日志级别调为debug模式。
3.运行展示
3.1 通过maven内置的Tomcat启动项目(不知道的网上看下,有很多资料),访问端口为9090。地址栏访问 http://localhost:9090
由此可以看到当访问我们的项目时,spring security将我们的项目保护了起来,并提供了一个默认的登录页面,让我们去登录。我们在MySecurityConfig中配置了一个用户。用户名为"user",密码为"password",输入这个用户名和密码,即可正常访问我们的项目。
3.2 输入用户名和密码
三、总结
到现在为止,我们已经搭建了一个基于spring(spring mvc)的spring security项目。可能你会很疑惑,为什么会产生这种效果。那个输入用户名和密码的页面,我们在项目中也没有创建,是怎么出来的呢?
其实这一切都是经过我们上述的配置,我们创建并注册了spring security的过滤器。是这些过滤器为我们做到的。除此之外,spring security还为我们做了额外的其他的保护。总的来说,经过我们上述的配置后,spring security为我们的应用提供了以下默认功能:
1.访问应用中的每个URL都需要进行验证
2.生成一个登陆表单
3.允许用户使用username和password来登陆
4.允许用户注销
5.CSRF攻击拦截
6.Session Fixation(session固定攻击)
7.安全Header集成
7.1 HTTP Strict Transport Security for secure requests
7.2 X-Content-Type-Options integration
7.3 缓存控制 (can be overridden later by your application to allow caching of your static resources)
7.4 X-XSS-Protection integration
7.5 X-Frame-Options integration to help prevent Clickjacking
8.Integrate with the following Servlet API methods
8.1 HttpServletRequest#getRemoteUser()
8.2 HttpServletRequest.html#getUserPrincipal()
8.3 HttpServletRequest.html#isUserInRole(java.lang.String)
8.4 HttpServletRequest.html#login(java.lang.String, java.lang.String)
8.5 HttpServletRequest.html#logout()
下一节,通过spring security过滤器的创建和注册源码的分析,你将会了解这一切!
参考资料:http://www.tianshouzhi.com/api/tutorials/spring_security_4/250
https://docs.spring.io/spring-security/site/docs/4.1.3.RELEASE/reference/htmlsingle/