Spring Security Official Quick Case Guide Translation


Spring Security is a powerful and highly customizable authentication and access-control framework. It is the de-facto standard for securing Spring-based applications.

Translation: Spring Security is a powerful, highly customizable authentication and access control framework. It is an industry standard for protecting spring-based applications.

Spring Security is a framework that focuses on providing both authentication and authorization to Java applications. Like all Spring projects, the real power of Spring Security is found in how easily it can be extended to meet custom requirements

Translation: Spring Security is a framework that focuses on providing authentication and authorization to Java applications. Like all Spring projects, the real power of Spring Security is that it can be easily extended to meet customized needs

Features

  • Comprehensive and extensible support for both Authentication and Authorization // Comprehensive and extensible support for authentication and authorization
  • Protection against attacks like session fixation, clickjacking, cross site request forgery, etc //Prevent attacks, such as session fixation, clickjacking, cross site request forgery, etc.
  • Servlet API integration //Servlet API integration
  • Optional integration with Spring Web MVC //Optional integration with Spring Web MVC
  • Much more...More

Securing a Web Application

This guide walks you through the process of creating a simple web application with resources that are protected by Spring Security.

Translation: This guide will take you to create a simple web application that uses Spring Security to protect resources.

What You Will Build

You will build a Spring MVC application that secures the page with a login form that is backed by a fixed list of users.

Translation: You will create a Spring MVC application that uses a login form page to protect the page and log in to a list of users that supports fixed settings

What You Need

  • About 15 minutes //About 15 minutes
  • A favorite text editor or IDE //There is a familiar development tool
  • JDK 1.8 or later // JDK is greater than or equal to 1.8
  • Gradle 4+ or Maven 3.2+ // Gradle version is greater than or equal to 4 or Maven version is greater than or equal to 3.2
  • You can also import the code straight into your IDE: //You can also import the code straight into your development tool

How to complete this guide How to complete this guide

Like most Spring Getting Started guides, you can start from scratch and complete each step or you can bypass basic setup steps that are already familiar to you. Either way, you end up with working code.

Translation: Like other Spring Getting Started guides, you can complete each step from scratch, or you can skip those steps that you are familiar with. No matter what, you end up running the code

To start from scratch, move on to Starting with Spring Initializr . To start from scratch,
please skip to Starting with Spring Initializr.

To skip the basics, do the following: To skip the basics, do the following
:

  • Download and unzip the source repository for this guide, or clone it using Git:
    git clone https://github.com/spring-guides/gs-securing-web.git
    

Translation: Download and unzip the code repository associated with this case, or use the git command to pull the code

When you finish, you can check your results against the code in gs-securing-web/complete.

Translation: When you are finished, you can follow the example of gs-securing-web/complete

Starting with Spring Initializr use Spring Initializr initialization

For all Spring applications, you should start with the Spring Initializr. The Initializr offers a fast way to pull in all the dependencies you need for an application and does a lot of the setup for you. This example needs the Spring Web and Thymeleaf dependencies.

Translation: For the Spring application you are using, you should use Spring Initializr to initialize. This initialization tool provides a quick pull of the dependencies required by your application, and does a lot of construction for you. This case requires Spring Web and Thymeleaf dependencies.

The following listing shows the pom.xml file that is created when you choose Maven:

Translation: The following shows the configuration file information of pom when you choose maven build method:

<?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>2.3.2.RELEASE</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>
	<groupId>com.example</groupId>
	<artifactId>securing-web</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>securing-web</name>
	<description>Demo project for Spring Boot</description>

	<properties>
		<java.version>1.8</java.version>
	</properties>

	<dependencies>
		<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.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
			<exclusions>
				<exclusion>
					<groupId>org.junit.vintage</groupId>
					<artifactId>junit-vintage-engine</artifactId>
				</exclusion>
			</exclusions>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>

</project>

The following listing shows the build.gradle file that is created when you choose Gradle:

Translation: The following shows the configuration file information of build.gradle when you select the Gradle build method:

plugins {
	id 'org.springframework.boot' version '2.3.2.RELEASE'
	id 'io.spring.dependency-management' version '1.0.8.RELEASE'
	id 'java'
}

group = 'com.example'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '1.8'

repositories {
	mavenCentral()
}

dependencies {
	implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'
	implementation 'org.springframework.boot:spring-boot-starter-web'
	testImplementation('org.springframework.boot:spring-boot-starter-test') {
		exclude group: 'org.junit.vintage', module: 'junit-vintage-engine'
	}
}

test {
	useJUnitPlatform()
}

Create an Unsecured Web Application to create a non-secure applications

Before you can apply security to a web application, you need a web application to secure. This section walks you through creating a simple web application. Then you will secure it with Spring Security in the next section.

Translation: Before you can use a security framework for an application, you need to have a web application. This chapter will take you to create a simple web application. Then you will use Spring Security to protect this application in the next chapter

The web application includes two simple views: a home page and a “Hello, World” page. The home page is defined in the following Thymeleaf template (from src/main/resources/templates/home.html):

Translation: This application contains two simple pages: home page and welcome page (Hello, World). The home page is defined in the Thymeleaf template file (src/main/resources/templates/home.html in the project path).

<!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>Spring Security Example</title>
    </head>
    <body>
        <h1>Welcome!</h1>

        <p>Click <a th:href="@{/hello}">here</a> to see a greeting.</p>
    </body>
</html>

This simple view includes a link to the /hello page, which is defined in the following Thymeleaf template (from src/main/resources/templates/hello.html):

This page contains a link to the welcome page (/hello page), which is defined under the Thymeleafy template file.

<!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>Hello world!</h1>
    </body>
</html>

The web application is based on Spring MVC. As a result, you need to configure Spring MVC and set up view controllers to expose these templates. The following listing (from src/main/java/com/example/securingweb/MvcConfig.java) shows a class that configures Spring MVC in the application:

Translation: This application is based on Spring MVC. Therefore, you need to configure Spring MVC and set the view controller to expose these template access paths. The following configuration shows the configuration of Spring MVC by this (MvcConfig) class

package com.example.securingweb;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class MvcConfig implements WebMvcConfigurer {

	public void addViewControllers(ViewControllerRegistry registry) {
		registry.addViewController("/home").setViewName("home");
		registry.addViewController("/").setViewName("home");
		registry.addViewController("/hello").setViewName("hello");
		registry.addViewController("/login").setViewName("login");
	}

}

The addViewControllers() method (which overrides the method of the same name in WebMvcConfigurer) adds four view controllers. Two of the view controllers reference the view whose name is home (defined in home.html), and another references the view named hello (defined in hello.html). The fourth view controller references another view named login. You will create that view in the next section.

Translation: This addViewControllers() method (it overrides the addViewControllers() method of WebMvcConfigurer) adds four view controllers. Two of the view controllers point to the home page, and the other points to the page named hello (the welcome page). The fourth view controller points to the login page. You will create the login page in the next chapter.

At this point, you could jump ahead to “[Run the Application](#Run the Application)” and run the application without having to log in to anything.

Translation: At this moment, you can jump to the Run the Application directory and run this application that does not require login

Now that you have an unsecured web application, you can add security to it.

Translation: Now that you have a non-secure web application, you can add security to it.

Set up Spring Security 装配Spring Security

Suppose that you want to prevent unauthorized users from viewing the greeting page at /hello. As it is now, if visitors click the link on the home page, they see the greeting with no barriers to stop them. You need to add a barrier that forces the visitor to sign in before they can see that page.

Translation: Suppose you want to prevent unauthenticated users from visiting the welcome page. As it is now, if users click on the link on the homepage, they will see the welcome page, and there is no obstacle to stop them. You must add barriers to force visitors to log in before seeing the welcome page.

You do that by configuring Spring Security in the application. If Spring Security is on the classpath, Spring Boot automatically secures all HTTP endpoints with “basic” authentication. However, you can further customize the security settings. The first thing you need to do is add Spring Security to the classpath.

Translation: You can configure Spring Security to do so in your application. If Spring Security is in the classpath, the Spring Boot framework will automatically intercept all HTTP endpoints using basic authentication methods. However, you can further customize the security configuration. The first step you need to do is to add Spring Security to the classpath.

With Gradle, you need to add two lines (one for the application and one for testing) in the dependencies closure in build.gradle, as the following listing shows:

Translation: To use Gradle, you need to add two lines (one for application and one for testing) in the dependencies brackets of build.gradle. The following shows how to configure:

implementation 'org.springframework.boot:spring-boot-starter-security'
implementation 'org.springframework.security:spring-security-test'

The following listing shows the finished build.gradle file: The
complete build.gradle configuration file is as follows:

plugins {
	id 'org.springframework.boot' version '2.3.2.RELEASE'
	id 'io.spring.dependency-management' version '1.0.8.RELEASE'
	id 'java'
}

group = 'com.example'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '1.8'

repositories {
	mavenCentral()
}

dependencies {
	implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'
	implementation 'org.springframework.boot:spring-boot-starter-web'
	implementation 'org.springframework.boot:spring-boot-starter-security'
	implementation 'org.springframework.security:spring-security-test'
	testImplementation('org.springframework.boot:spring-boot-starter-test') {
		exclude group: 'org.junit.vintage', module: 'junit-vintage-engine'
	}
}

test {
	useJUnitPlatform()
}

With Maven, you need to add two extra entries (one for the application and one for testing) to the element in pom.xml, as the following listing shows:

Translation: To use Maven, you need to add two additional dependencies (one for application and one for testing) to the node of the pom.xml file, as shown below:

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
  <groupId>org.springframework.security</groupId>
  <artifactId>spring-security-test</artifactId>
  <scope>test</scope>
</dependency>

The following listing shows the finished pom.xml file: The
complete pom.xml file is as follows:

<?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>2.3.2.RELEASE</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>
	<groupId>com.example</groupId>
	<artifactId>securing-web</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>securing-web</name>
	<description>Demo project for Spring Boot</description>

	<properties>
		<java.version>1.8</java.version>
	</properties>

	<dependencies>
		<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.springframework.boot</groupId>
			<artifactId>spring-boot-starter-security</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.security</groupId>
			<artifactId>spring-security-test</artifactId>
			<scope>test</scope>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
			<exclusions>
				<exclusion>
					<groupId>org.junit.vintage</groupId>
					<artifactId>junit-vintage-engine</artifactId>
				</exclusion>
			</exclusions>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>

</project>

The following security configuration (from src/main/java/com/example/securingweb/WebSecurityConfig.java) ensures that only authenticated users can see the secret greeting:

Translation: The following security configuration (src/main/java/com/example/securingweb/WebSecurityConfig.java in the project path) ensures that only authenticated users can see the welcome page:

package com.example.securingweb;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
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.provisioning.InMemoryUserDetailsManager;

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
	@Override
	protected void configure(HttpSecurity http) throws Exception {
		http
			.authorizeRequests()
				.antMatchers("/", "/home").permitAll()
				.anyRequest().authenticated()
				.and()
			.formLogin()
				.loginPage("/login")
				.permitAll()
				.and()
			.logout()
				.permitAll();
	}

	@Bean
	@Override
	public UserDetailsService userDetailsService() {
		UserDetails user =
			 User.withDefaultPasswordEncoder()
				.username("user")
				.password("password")
				.roles("USER")
				.build();

		return new InMemoryUserDetailsManager(user);
	}
}

The WebSecurityConfig class is annotated with @EnableWebSecurity to enable Spring Security’s web security support and provide the Spring MVC integration. It also extends WebSecurityConfigurerAdapter and overrides a couple of its methods to set some specifics of the web security configuration.

Translation: WebSecurityConfig is annotated with @EnableWebSecurity, which enables Spring Security's web security support and provides the integration of Sping MVC. It also inherits WebSecurityConfigurerAdapter and rewrites its two methods in order to configure custom security configurations.

The configure(HttpSecurity) method defines which URL paths should be secured and which should not. Specifically, the / and /home paths are configured to not require any authentication. All other paths must be authenticated.

Translation: The configure(HttpSecurity) method defines which URL paths should be checked for security, and which are not. In particular, the "/" and "/home" paths are configured to not require any authentication. All other paths require certification.

When a user successfully logs in, they are redirected to the previously requested page that required authentication. There is a custom /login page (which is specified by loginPage()), and everyone is allowed to view it.

Translation: When users successfully log in, they are redirected to a page that they were not authorized to access before. There is a custom login page (it is marked by loginPage()), and everyone can access it.

The userDetailsService() method sets up an in-memory user store with a single user. That user is given a user name of user, a password of password, and a role of USER.

Translation: userDetailsService() This method sets the use of memory to protect user information and defines a user. The account of this user is user, the password is password, and the role is USER.

Now you need to create the login page. There is already a view controller for the login view, so you need only to create the login view itself, as the following listing (from src/main/resources/templates/login.html) shows:

Translation: Now you need to create a login page. We already have a view controller for the login page, so you only need to create the login page. This page is shown below (src/main/resources/templates/login.html under the project path):

<!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>Spring Security Example </title>
    </head>
    <body>
        <div th:if="${param.error}">
            Invalid username and password.
        </div>
        <div th:if="${param.logout}">
            You have been logged out.
        </div>
        <form th:action="@{/login}" method="post">
            <div><label> User Name : <input type="text" name="username"/> </label></div>
            <div><label> Password: <input type="password" name="password"/> </label></div>
            <div><input type="submit" value="Sign In"/></div>
        </form>
    </body>
</html>

This Thymeleaf template presents a form that captures a username and password and posts them to /login. As configured, Spring Security provides a filter that intercepts that request and authenticates the user. If the user fails to authenticate, the page is redirected to /login?error, and your page displays the appropriate error message. Upon successfully signing out, your application is sent to /login?logout, and your page displays the appropriate success message.

Translation: This Thymeleaf template shows a form to get the username and password and send it to /login. As configured above, Spring Security provides filters to intercept requests and authenticate users. If the user authentication fails, the page will be redirected to /login?error, and your page will display related error messages. Once the user logs out, your application is forwarded to /login?logout, and your page will display related success messages.

Last, you need to provide the visitor a way to display the current user name and sign out. To do so, update the hello.html to say hello to the current user and contain a Sign Out form, as the following listing (from src/main/resources/templates/hello.html) shows:

Translation: Finally, you need to provide users with a way to display the currently logged in user name and log out. In order to do so, update the welcome page (hello.html) to welcome the current user and include an exit form, as shown in the following configuration (in the project's src/main/resources/templates/hello.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 [[${#httpServletRequest.remoteUser}]]!</h1>
        <form th:action="@{/logout}" method="post">
            <input type="submit" value="Sign Out"/>
        </form>
    </body>
</html>

We display the username by using Spring Security’s integration with HttpServletRequest#getRemoteUser(). The “Sign Out” form submits a POST to /logout. Upon successfully logging out, it redirects the user to /login?logout.

Translation: We display the user name using Spring Security's integrated HttpServletRequest#getRemoteUser(), this "Sign Out" form submits a Post request to the //logout path. Once the exit is successful, the application redirects to the /login?logout path.

Run the Application Run the application

The Spring Initializr creates an application class for you. In this case, you need not modify the class. The following listing (from src/main/java/com/example/securingweb/SecuringWebApplication.java) shows the application class:

Translation: Spring Initializr creates application startup classes for you. In this case, you do not need to change this class. The following shows the application startup class (in the project src/main/java/com/example/securingweb/SecuringWebApplication.java):

package com.example.securingweb;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class SecuringWebApplication {

	public static void main(String[] args) throws Throwable {
		SpringApplication.run(SecuringWebApplication.class, args);
	}

}

Build an executable JAR build an executable JAR

You can run the application from the command line with Gradle or Maven. You can also build a single executable JAR file that contains all the necessary dependencies, classes, and resources and run that. Building an executable jar makes it easy to ship, version, and deploy the service as an application throughout the development lifecycle, across different environments, and so forth.

Translation: You can run the application using the command line based on Gradle or Maven. You can also compile into an executable JAR package, which contains all the dependencies, classes, resources and start it. Building an executable jar makes it easy to publish, version, and deploy the service as an application throughout the development life cycle, across different environments, etc.

If you use Gradle, you can run the application by using ./gradlew bootRun. Alternatively, you can build the JAR file by using ./gradlew build and then run the JAR file, as follows:

Translation: If you use Gradle, you can use "./gradlew bootRun" to run this application. Or, you can use "./gradlew build" to build the jar package, and use the following command to run the jar package.

java -jar build/libs/gs-securing-web-0.1.0.jar

If you use Maven, you can run the application by using ./mvnw spring-boot:run. Alternatively, you can build the JAR file with ./mvnw clean package and then run the JAR file, as follows:

Translation: If you use Maven, you can use "./mvnw spring-boot:run" to run the application. Alternatively, you can also use "./mvnw clean package" to build the jar package and run the jar package with the following command:

java -jar target/gs-securing-web-0.1.0.jar

The steps described here create a runnable JAR. You can also build a classic WAR file.
This step describes how to create a JAR package, you can also build a WAR package

Once the application starts up, point your browser to http://localhost:8080. You should see the home page, as the following image shows:

Translation: Once the application is launched, let your browser visit "http://localhost:8080", and you can see the home page as shown below:
Insert picture description here

When you click on the link, it attempts to take you to the greeting page at /hello. However, because that page is secured and you have not yet logged in, it takes you to the login page, as the following image shows:

Translation: When you click on this link, it tries to take you to the welcome page. However, since this page is secured, you are not logged in either. The application redirects to the login page, as shown in the following figure:
Insert picture description here

If you jumped down here with the unsecured version, you do not see the login page. You should back up and write the rest of the security-based code. If you jumped down here with the unsecured version, you
will not see Go to this login page. You should back up and write the rest of the security-based code.

At the login page, sign in as the test user by entering user and password for the username and password fields, respectively. Once you submit the login form, you are authenticated and then taken to the greeting page, as the following image shows:

Translation: On the login page, enter the account and password of the test account in the user name and password boxes to log in. Once you submit the form, you will be authenticated to the welcome page, as shown below:
Insert picture description here

If you click on the Sign Out button, your authentication is revoked, and you are returned to the login page with a message indicating that you are logged out.
Summary

Translation: If you click the logout button, your authentication information will be cleared and you will be redirected to the login page, which prompts you to log out.

Congratulations! You have developed a simple web application that is secured with Spring Security.
See Also

Translation: Congratulations! You have developed a simple Spring Security secure web application.

The following guides may also be helpful
:

Guess you like

Origin blog.csdn.net/Lixuanshengchao/article/details/112442682