无涯教程-Spring Boot - Web安全应用

59 阅读3分钟

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

为了向您的Spring Boot应用程序添加Spring Boot Security,无涯教程需要在构建配置文件中添加Spring Boot Starter Security依赖项。

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

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

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 Example</title> </head> <body> <h1>Welcome!</h1> <p>Click <a th:href="@{/hello}">here</a> to see a greeting.</p> </body>

</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>

现在,无涯教程需要为主视图和问候视图设置Spring MVC – View控制器。

为此,创建一个扩展WebMvcConfigurerAdapter的MVC配置文件。

package com.learnfk.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"); } }

现在,将Spring Boot Starter安全依赖项添加到您的构建配置文件中。

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

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

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

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

现在,创建一个Web安全配置文件,该文件用于保护您的应用程序通过使用基本身份验证来访问HTTP端点。

package com.learnfk.websecuritydemo;

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

@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(); } @Autowired public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { auth .inMemoryAuthentication() .withUser("user").password("password").roles("USER"); } }

现在,在 src/main/resources 目录下创建一个login.html文件,以允许用户通过登录屏幕访问HTTP端点。

<!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 Example </title> </head> <body> <div th:if="{param.error}"</span><span class="tag">&gt;</span><span class="pln"> Invalid username and password. </span><span class="tag">&lt;/div&gt;</span><span class="pln"> </span><span class="tag">&lt;div</span><span class="pln"> </span><span class="atn">th:if</span><span class="pun">=</span><span class="atv">"{param.logout}"> You have been logged out. </div>

  </span><span class="tag">&lt;form</span><span class="pln"> </span><span class="atn">th:action</span><span class="pun">=</span><span class="atv">"@{/login}"</span><span class="pln"> </span><span class="atn">method</span><span class="pun">=</span><span class="atv">"post"</span><span class="tag">&gt;</span><span class="pln">
     </span><span class="tag">&lt;div&gt;</span><span class="pln">
        </span><span class="tag">&lt;label&gt;</span><span class="pln"> User Name : </span><span class="tag">&lt;input</span><span class="pln"> </span><span class="atn">type</span><span class="pun">=</span><span class="atv">"text"</span><span class="pln"> </span><span class="atn">name</span><span class="pun">=</span><span class="atv">"username"</span><span class="tag">/&gt;</span><span class="pln"> </span><span class="tag">&lt;/label&gt;</span><span class="pln">
     </span><span class="tag">&lt;/div&gt;</span><span class="pln">
     </span><span class="tag">&lt;div&gt;</span><span class="pln">
        </span><span class="tag">&lt;label&gt;</span><span class="pln"> Password: </span><span class="tag">&lt;input</span><span class="pln"> </span><span class="atn">type</span><span class="pun">=</span><span class="atv">"password"</span><span class="pln"> </span><span class="atn">name</span><span class="pun">=</span><span class="atv">"password"</span><span class="tag">/&gt;</span><span class="pln"> </span><span class="tag">&lt;/label&gt;</span><span class="pln">
     </span><span class="tag">&lt;/div&gt;</span><span class="pln">
     </span><span class="tag">&lt;div&gt;</span><span class="pln">
        </span><span class="tag">&lt;input</span><span class="pln"> </span><span class="atn">type</span><span class="pun">=</span><span class="atv">"submit"</span><span class="pln"> </span><span class="atn">value</span><span class="pun">=</span><span class="atv">"Sign In"</span><span class="tag">/&gt;</span><span class="pln">
     </span><span class="tag">&lt;/div&gt;</span><span class="pln">
  </span><span class="tag">&lt;/form&gt;</span><span class="pln">
  

</body> </html>

最后,更新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 th:inline="text">Hello [[${#httpServletRequest.remoteUser}]]!</h1> <form th:action="@{/logout}" method="post"> <input type="submit" value="Sign Out"/> </form> </body>

</html>

下面给出了主要的Spring Boot应用程序的代码-

package com.learnfk.websecuritydemo;

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

@SpringBootApplication public class WebsecurityDemoApplication { public static void main(String[] args) { SpringApplication.run(WebsecurityDemoApplication.class, args); } }

下面给出了构建配置文件的完整代码。

Maven-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 
   http://maven.apache.org/xsd/maven-4.0.0.xsd">

<modelVersion>4.0.0</modelVersion> <groupId>com.learnfk</groupId> <artifactId>websecurity-demo</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>websecurity-demo</name> <description>Demo project for Spring Boot</description>

<parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.5.9.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent>

<properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <java.version>1.8</java.version> </properties>

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

  </span><span class="tag">&lt;dependency&gt;</span><span class="pln">
     </span><span class="tag">&lt;groupId&gt;</span><span class="pln">org.springframework.boot</span><span class="tag">&lt;/groupId&gt;</span><span class="pln">
     </span><span class="tag">&lt;artifactId&gt;</span><span class="pln">spring-boot-starter-thymeleaf</span><span class="tag">&lt;/artifactId&gt;</span><span class="pln">
  </span><span class="tag">&lt;/dependency&gt;</span><span class="pln">
  
  </span><span class="tag">&lt;dependency&gt;</span><span class="pln">
     </span><span class="tag">&lt;groupId&gt;</span><span class="pln">org.springframework.boot</span><span class="tag">&lt;/groupId&gt;</span><span class="pln">
     </span><span class="tag">&lt;artifactId&gt;</span><span class="pln">spring-boot-starter-web</span><span class="tag">&lt;/artifactId&gt;</span><span class="pln">
  </span><span class="tag">&lt;/dependency&gt;</span><span class="pln">

  </span><span class="tag">&lt;dependency&gt;</span><span class="pln">
     </span><span class="tag">&lt;groupId&gt;</span><span class="pln">org.springframework.boot</span><span class="tag">&lt;/groupId&gt;</span><span class="pln">
     </span><span class="tag">&lt;artifactId&gt;</span><span class="pln">spring-boot-starter-test</span><span class="tag">&lt;/artifactId&gt;</span><span class="pln">
     </span><span class="tag">&lt;scope&gt;</span><span class="pln">test</span><span class="tag">&lt;/scope&gt;</span><span class="pln">
  </span><span class="tag">&lt;/dependency&gt;</span><span class="pln">
  
  </span><span class="tag">&lt;dependency&gt;</span><span class="pln">
     </span><span class="tag">&lt;groupId&gt;</span><span class="pln">org.springframework.security</span><span class="tag">&lt;/groupId&gt;</span><span class="pln">
     </span><span class="tag">&lt;artifactId&gt;</span><span class="pln">spring-security-test</span><span class="tag">&lt;/artifactId&gt;</span><span class="pln">
     </span><span class="tag">&lt;scope&gt;</span><span class="pln">test</span><span class="tag">&lt;/scope&gt;</span><span class="pln">
  </span><span class="tag">&lt;/dependency&gt;</span><span class="pln">

</dependencies>

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

</project>

Gradle – build.gradle

buildscript {
   ext {
      springBootVersion=1.5.9.RELEASE
   }
   repositories {
      mavenCentral()
   }
   dependencies {
      classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
   }
}

apply plugin: java apply plugin: eclipse apply plugin: org.springframework.boot

group=com.learnfk version=0.0.1-SNAPSHOT sourceCompatibility=1.8

repositories { mavenCentral() } dependencies { compile(org.springframework.boot:spring-boot-starter-security) compile(org.springframework.boot:spring-boot-starter-thymeleaf) compile(org.springframework.boot:spring-boot-starter-web)

testCompile(org.springframework.boot:spring-boot-starter-test) testCompile(org.springframework.security:spring-security-test) }

现在,创建一个可执行的JAR文件,并使用以下Maven或Gradle命令运行Spring Boot应用程序。

Maven用户可以使用以下命令-

mvn clean install

在" BUILD SUCCESS"之后,您可以在目标目录下找到JAR文件。

Gradle用户可以使用如下所示的命令-

gradle clean build

在" BUILD SUCCESSFUL"之后,您可以在build/libs目录下找到JAR文件。

现在,使用下面显示的命令运行JAR文件:

java jar <JARFILE> 

在网络浏览器中点击URL http:// localhost:8080/。您可以看到如下所示的输出。

Output on Web Browser Click Link Output Login Page Output Signout Page Output Logged Out Invalid Username Password

参考链接

www.learnfk.com/spring-boot…