Spring Security 简明教程

Spring Security - XML Configuration

在基于 Spring boot 的项目中,首选基于 Java 的配置,但我们也有等效的 XML 配置。在本文中,我们将按如下所示使用基于 XML 的 Spring Security 配置:

<beans:beans //...
   <http auto-config="true">
      <intercept-url pattern="/admin" access="hasRole('ROLE_ADMIN')" />
      <intercept-url pattern="/**" access="hasRole('ROLE_ADMIN')"/>
   </http>
   <authentication-manager>
      <authentication-provider>
         <user-service>
            <user name="admin" password="{noop}1234" authorities="ROLE_ADMIN" />
         </user-service>
      </authentication-provider>
   </authentication-manager>
   <beans:bean id ="passwordEncoder"
      class = "org.springframework.security.crypto.password.NoOpPasswordEncoder"
      factory-method = "getInstance">
   </beans:bean>
</beans:beans>
  1. http −所有与 Web 相关的命名空间功能的父级。在这里,我们可以配置拦截哪些 URL,需要哪些权限、使用哪种类型的登录,以及所有此类配置。

  2. auto-config −将此属性设置为 true 会自动设置表单登录、基本登录及退出功能。Spring Security 会使用标准值和已启用的功能对其进行生成。

  3. intercept-url −它使用 access 属性设置我们想要保护的 URL 模式。

  4. access −它指定哪些用户被允许访问模式属性指定的 URL。它是基于用户的角色和权限进行设定。我们可以在此属性中使用 SPEL。

  5. authentication-manager −<authentication-manager> 用于配置应用程序中的用户、他们的密码和角色。这些用户将可以访问应用程序的受保护部分,前提是他们具有适当的角色。DaoAuthenticationProvider bean 将由 <authentication-provider> 创建,而 <user-service> 元素将创建一个 InMemoryDaoImpl。所有 authentication-provider 元素都将允许用户通过将用户信息提供给 authentication-manager 进行身份验证。

  6. password-encoder −这将注册一个密码编码器 bean。为了简化操作,这里我们使用了 NoOpPasswordEncoder。

为了在 Spring Boot 应用程序中注册此 security-config.xml,我们可以按如下所示导入它:

@SpringBootApplication
@ImportResource("classpath:/spring/spring-security.xml")
public class FormloginApplication {
   public static void main(String[] args) {
      SpringApplication.run(FormloginApplication.class, args);
   }
}

让我们使用 Spring Security 开始实际编程。在开始使用 Spring 框架编写示例之前,您必须确保已正确设置 Spring 环境,如 Spring Security - Environment Setup 章节所述。我们还假设您具备 Spring Tool Suite IDE 方面的部分工作知识。

现在,让我们开始编写一个由 Maven 管理的基于 Spring MVC 的应用程序,该应用程序将要求用户登录、认证用户,然后提供使用 Spring Security 表单登录功能注销的选项。

Create Project using Spring Initializr

Spring Initializr 是开始 Spring Boot 项目的一个好方法。它提供了一个易于使用的用户界面来创建项目、添加依赖项、选择 Java 运行时等。它会生成一个框架项目结构,下载后可以在 Spring Tool Suite 中导入,然后我们可以使用现成的项目结构继续进行。

我们选择了一个 maven 项目,将项目命名为 formlogin,并将 java 版本指定为 21。添加了以下依赖项:

  1. Spring Web

  2. Spring Security

  3. Thymeleaf

  4. Spring Boot DevTools

spring initializr

Thymeleaf 是 Java 的模板引擎。它使我们能够快速开发用于在浏览器中渲染的静态或动态网页。它已得到极大的扩展,它允许我们定义和定制精细处理的模板。除此之外,我们可以通过点击 link 来了解更多有关 Thymeleaf 的信息。

让我们开始生成并下载项目。然后我们将它解压到我们选择的文件夹中并使用任何 IDE 来打开它。我将使用 Spring Tools Suite 4 。它可以从 https://spring.io/tools 网站免费下载,且已针对 spring 应用进行优化。

pom.xml with all relevant dependencies

让我们看一看我们的 pom.xml 文件。它应该与以下内容类似 −

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
   <modelVersion>4.0.0</modelVersion>
   <parent>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-parent</artifactId>
      <version>3.3.1</version>
      <relativePath/> <!-- lookup parent from repository -->
   </parent>
   <groupId>com.tutorialspoint.security</groupId>
   <artifactId>formlogin</artifactId>
   <version>0.0.1-SNAPSHOT</version>
   <name>formlogin</name>
   <description>Demo project for Spring Boot</description>
   <url/>
   <licenses>
      <license/>
   </licenses>
   <developers>
      <developer/>
   </developers>
   <scm>
      <connection/>
      <developerConnection/>
      <tag/>
      <url/>
   </scm>
   <properties>
      <java.version>21</java.version>
   </properties>
   <dependencies>
      <dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter-security</artifactId>
      </dependency>
      <dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter-thymeleaf</artifactId>
      </dependency>
      <dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter-web</artifactId>
      </dependency>
      <dependency>
         <groupId>org.thymeleaf.extras</groupId>
         <artifactId>thymeleaf-extras-springsecurity6</artifactId>
      </dependency>
      <dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-devtools</artifactId>
         <scope>runtime</scope>
         <optional>true</optional>
      </dependency>
      <dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter-test</artifactId>
         <scope>test</scope>
      </dependency>
      <dependency>
         <groupId>org.springframework.security</groupId>
         <artifactId>spring-security-test</artifactId>
         <scope>test</scope>
      </dependency>
   </dependencies>
   <build>
      <plugins>
         <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
         </plugin>
      </plugins>
   </build>
</project>

Spring Security Configuration XML

以下是 /src/main/resources/spring/ 文件夹中创建的 Spring 安全性配置文件的完整代码,文件名为 spring-security.xml。

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 auto-config="true">
   <intercept-url pattern="/admin" access="hasRole('ROLE_ADMIN')" />
   <intercept-url pattern="/**" access="hasRole('ROLE_ADMIN')"/> </http>
   <authentication-manager>
      <authentication-provider>
         <user-service>
            <user name="admin" password="{noop}1234" authorities="ROLE_ADMIN" />
         </user-service>
      </authentication-provider> </authentication-manager>
      <beans:bean id ="passwordEncoder"
         class = "org.springframework.security.crypto.password.NoOpPasswordEncoder"
         factory-method = "getInstance">
      </beans:bean>
</beans:beans>

Spring Boot Application

以下是 FormloginApplication 类的内容,其中我们从 classpath 导入 spring-security.xml。

FormloginApplication.java

package com.tutorialspoint.security.formlogin;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ImportResource;

@SpringBootApplication
@ImportResource("classpath:/spring/spring-security.xml")
public class FormloginApplication {
   public static void main(String[] args) {
      SpringApplication.run(FormloginApplication.class, args);
   }
}

Controller Class

在此类中,我们为“/”端点创建了一个映射,其中“/admin”用于索引页面,以及此应用程序的管理员页面。

AuthController.java

package com.tutorialspoint.security.formlogin.controllers;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

@Controller
public class AuthController {
   @GetMapping("/")
   public String home() {
      return "index";
   }
   @GetMapping("/admin")
   public String admin() {
      return "admin";
   }
}

Views

使用以下内容在 /src/main/resources/templates 文件夹中创建 index.html 以作为主页。

index.html

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
   xmlns:th="https://www.thymeleaf.org"
   xmlns:sec="https://www.thymeleaf.org/thymeleaf-extras-springsecurity3">
   <head>
      <title>
         Hello World!
      </title>
   </head>
   <body>
      <h1 th:inline="text">Hello World!</h1>
      <a href="/logout" alt="logout">Sign Out</a>
   </body>
<html>

让我们在 /src/main/resources/templates 文件夹中使用以下内容创建 admin.html,作为管理员页面。

admin.html

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="https://www.thymeleaf.org"
xmlns:sec="https://www.thymeleaf.org/thymeleaf-extras-springsecurity6">
   <head>
      <title>
         Hello Admin!
      </title>
   </head>
   <body>
      <p>Admin Console</p>
      <a href="/logout" alt="logout">Sign Out</a>
   </body>
<html>

Running the Application

一旦我们准备好了所有组件,接下来运行应用程序。右击项目,选择 Run As 然后选择 Spring Boot App

它将启动该应用,并且一旦应用启动,我们就可以运行 localhost:8080 来查看更改。

Output

现在打开 localhost:8080,您将看到我们的登录页面。

Login Page with Admin Details entered

xml admin formlogin

Home Page for Admin

当我们输入有效的管理员证书后,它将加载主页,主页即为 index.html。

xml admin formlogin success

Open Admin Page

现在打开 localhost:8080/admin,您将看到管理员页面。

xml admin page

Logout

单击注销链接,它会要求进行注销。

xml logout confirm

点击注销按钮,它将显示登录页面。

xml logout