基于Spring Boot保护Web应用程序

2020-03-06 12:03:04于丽

如果在类路径上添加了Spring Boot Security依赖项,则Spring Boot应用程序会自动为所有HTTP端点提供基本身份验证。端点“/”和“/home”不需要任何身份验证。所有其他端点都需要身份验证。

要将Spring Boot Security添加到Spring Boot应用程序,需要在构建配置文件中添加Spring Boot Starter Security依赖项。

Maven用户可以在pom.xml 文件中添加以下依赖项。

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

XML

Gradle用户可以在build.gradle 文件中添加以下依赖项。

compile("org.springframework.boot:spring-boot-starter-security")

保护Web应用程序

首先,使用Thymeleaf模板创建不安全的Web应用程序。

然后,在 src/main/resources/templates 目录下创建一个home.html 文件。

<!DOCTYPE html>
<html xmlns = "http://www.w3.org/1999/xhtml" 
  xmlns:th = "http://www.thymeleaf.org" 
  xmlns:sec = "http://www.thymeleaf.org/thymeleaf-extras-springsecurity3">
  <head>
   <title>Spring Security示例</title>
  </head>
  <body>
   <h1>欢迎您!</h1>
   <p>点击 <a th:href = "@{/hello}">这里</a> 看到问候语.</p>
  </body>
</html>

HTML

使用Thymeleaf模板在HTML文件中定义的简单视图/hello。现在,在src/main/resources/templates目录下创建一个文件:hello.html。

<!DOCTYPE html>
<html xmlns = "http://www.w3.org/1999/xhtml" 
  xmlns:th = "http://www.thymeleaf.org" 
  xmlns:sec = "http://www.thymeleaf.org/thymeleaf-extras-springsecurity3">
  <head>
   <title>Hello World!</title>
  </head>
  <body>
   <h1>Hello world!</h1>
  </body>
</html>

HTML

现在,需要为Home和hello视图设置Spring MVC - View控制器。为此,创建一个扩展WebMvcConfigurerAdapter的MVC配置文件。

package com.yiibai.websecuritydemo;

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

@Configuration
public class MvcConfig extends WebMvcConfigurerAdapter {
  @Override
  public void addViewControllers(ViewControllerRegistry registry) {
   registry.addViewController("/home").setViewName("home");
   registry.addViewController("/").setViewName("home");
   registry.addViewController("/hello").setViewName("hello");
   registry.addViewController("/login").setViewName("login");
  }
}

Java

现在,将Spring Boot Starter安全依赖项添加到构建配置文件中。Maven用户可以在pom.xml 文件中添加以下依赖项。