Spring Boot保护Web应用程序

如果在类路径上添加了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 文件中添加以下依赖项。

<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安全配置文件,该文件用于保护应用程序以使用基本身份验证访问HTTP端点。

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

Java

现在,在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示例</title>
   </head>
   <body>
      <div th:if = "${param.error}">
         无效的用户名和密码.
      </div>
      <div th:if = "${param.logout}">
         你已经注销.
      </div>

      <form th:action = "@{/login}" method = "post">
         <div>
            <label> 用户名 : <input type = "text" name = "username"/> </label>
         </div>
         <div>
            <label> 密码: <input type = "password" name = "password"/> </label>
         </div>
         <div>
            <input type = "submit" value = "登录"/>
         </div>
      </form>
   </body>
</html>

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">您好,[[${#httpServletRequest.remoteUser}]]!</h1>
      <form th:action = "@{/logout}" method = "post">
         <input type = "submit" value = "注销"/>
      </form>
   </body>

</html>

HTML

主 Spring Boot应用程序的代码如下 -

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

Java

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

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

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

XML

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.yiibai‘
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

Shell

在“BUILD SUCCESS”之后,可以在target目录下找到JAR文件。
Gradle用户可以使用如下所示的命令 -

gradle clean build

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

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

java –jar <JARFILE>

Shell

在Web浏览器中访问URL => http://localhost:8080/ ,将看到如下图所示。

输入用户名和密码(user/password),然后点击登录 -

原文地址:https://www.cnblogs.com/borter/p/12423895.html

时间: 2024-08-12 04:16:23

Spring Boot保护Web应用程序的相关文章

Spring Boot非web应用程序实例

在Spring Boot中,要创建一个非Web应用程序,实现CommandLineRunner并覆盖run()方法,例如: import org.springframework.boot.CommandLineRunner; @SpringBootApplication public class SpringBootConsoleApplication implements CommandLineRunner { public static void main(String[] args) th

Spring Boot开发Web应用之Thymeleaf篇

前言 Web开发是我们平时开发中至关重要的,这里就来介绍一下Spring Boot对Web开发的支持. 正文 Spring Boot提供了spring-boot-starter-web为Web开发予以支持,spring-boot-starter-web为我们提供了嵌入的Tomcat以及Spring MVC的依赖. 项目结构推荐 一个好的项目结构会让你开发少一些问题,特别是Spring Boot中启动类要放在root package下面,我的web工程项目结构如下: root package结构:

spring mvc构建WEB应用程序入门例子

在使用spring mvc 构建web应用程序之前,需要了解spring mvc 的请求过程是怎样的,然后记录下如何搭建一个超简单的spring mvc例子. 1) spring mvc的请求经历 请求由DispatcherServlet分配给控制器(根据处理器映射),在控制器完成处理后,请求会被发送到一个视图(根据viewController解析逻辑视图) 来呈现输出结果. 整理成下图所示: 2)搭建一个简单的spring mvc例子 ①创建一个maven工程,其中pom中要有spring相关

使用 Spring Security 保护 Web 应用的安全

使用 Spring Security 保护 Web 应用的安全 安全一直是 Web 应用开发中非常重要的一个方面.从安全的角度来说,需要考虑用户认证和授权两个方面.为 Web 应用增加安全方面的能力并非一件简单的事情,需要考虑不同的认证和授权机制.Spring Security 为使用 Spring 框架的 Web 应用提供了良好的支持.本文将详细介绍如何使用 Spring Security 框架为 Web 应用提供安全支持. 4 评论: 成 富, 软件工程师, IBM 中国软件开发中心 201

Spring Boot 整合web层之JSON的使用

Spring Boot对web层进行了一系列的自动化配置,只需要引入web依赖,零配置,就可以直接使用spring  mvc 里面的东西,这篇看一下它对json的自动化配置: 创建一个web项目,勾选web的依赖,就可以看到依赖里面引入了json 在前后端分离的项目中,前后端的交互是通过json格式进行的.那么在Spring Boot中如何使用呢? 我们先看一个消息转化工具(HttpMessageConverter),所用的json生成都离不开它,它的作用: 1.将服务端返回的对象序列化成JSO

spring boot 启动web,内嵌tomcat

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/xsd/maven-4.0.0.xsd"

Spring Boot开发Web应用

静态资源访问 在我们开发Web应用的时候,需要引用大量的js.css.图片等静态资源. 默认配置 Spring Boot默认提供静态资源目录位置需置于classpath下,目录名需符合如下规则: /static /public /resources /META-INF/resources 举例:我们可以在src/main/resources/目录下创建static,在该位置放置一个图片文件.启动程序后,尝试访问http://localhost:8080/D.jpg.如能显示图片,配置成功. 渲染

Spring Boot 整合 Web 开发

这一节我们主要学习如何整合 Web 相关技术: Servlet Filter Listener 访问静态资源 文件上传 文件下载 Web三大基本组件分别是:Servlet,Listener,Filter.正常来说一旦我们用了框架,这三个基本就用不上了,Servlet 被 Controller 代替,Filter 被拦截器代替.但是可能在一些特殊的场景下不得不使用这三个基本组件时,Spring Boot 中要如何去引用呢?下面我们来一起学习一下. Spring Boot 集成了 Servlet 容

spring boot中通用应用程序属性

可以在application.properties文件内部application.yml,文件内部或命令行开关中指定各种属性.本附录提供了常见的Spring Boot属性列表以及对使用它们的基础类的引用. 核心属性: 键 默认值 描述 debug false 启用调试日志. info.*   要添加到信息端点的任意属性. logging.config   日志记录配置文件的位置.例如,用于logback的`classpath:logback.xml`. logging.exception-con