基于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>

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我们。

(0)

相关推荐

  • spring boot如何使用AOP统一处理web请求

    为了保证服务的高可用,及时发现问题,迅速解决问题,为应用添加log是必不可少的. 但是随着项目的增大,方法增多,每个方法加单独加日志处理会有很多冗余 那在SpringBoot项目中如何统一的处理Web请求日志? 基本思想: 采用AOP的方式,拦截请求,写入日志 AOP 是面向切面的编程,就是在运行期通过动态代理的方式对代码进行增强处理 基于AOP不会破坏原来程序逻辑,因此它可以很好的对业务逻辑的各个部分进行隔离,从而使得业务逻辑各部分之间的耦合度降低,提高程序的可重用性,同时提高了开发的效率.

  • SpringBoot2.0整合WebSocket代码实例

    这篇文章主要介绍了SpringBoot2.0整合WebSocket代码实例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 之前公司的某个系统为了实现推送技术,所用的技术都是Ajax轮询,这种方式浏览器需要不断的向服务器发出请求,显然这样会浪费很多的带宽等资源,所以研究了下WebSocket,本文将详细介绍下. 一.什么是WebSocket? WebSocket是HTML5开始提供的一种在单个TCP连接上进行全双工通讯的协议,能更好的节省服务器资

  • SpringBoot基本web开发demo过程解析

    这篇文章主要介绍了SpringBoot基本web开发demo过程解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 1.在创建的springboot项目中的pom.xml中导入Lombok的依赖 <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.18

  • SpringBoot中通过实现WebMvcConfigurer参数校验的方法示例

    在Spring5.0和SpringBoot2.0中废弃了WebMvcConfigurerAdapter类. 现有两种解决方案 1 直接实现WebMvcConfigurer (官方推荐) 2 直接继承WebMvcConfigurationSupport 本篇文章讨论下使用第一种方式完成参数校验. 首先附上代码. @Slf4j @Controller @RequestMapping("/goods") public class GoodsController { @Autowired Mi

  • springboot web项目打jar或者war包并运行的实现

    (一)springboot web项目打jar包 1.打包 两种打包方式 maven命令打包 切换目录到工程根下,pom.xml所在位置,运行maven的打包命令 mvn clean package -Dmaven.test.skip=true IDEA 工具执行maven任务打包 会在xxx项目模块下/target目录下生成xxx-0.0.1-SNAPSHOT.jar 2.运行jar包 启动运行(切换目录到target下,执行命令) F:\Java\idea-workspace\shixun0

  • spring boot使用WebClient调用HTTP服务代码示例

    这篇文章主要介绍了spring boot使用WebClient调用HTTP服务代码示例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 WebClient的请求模式属于异步非阻塞,能够以少量固定的线程处理高并发的HTTP请求 WebClient是Spring WebFlux模块提供的一个非阻塞的基于响应式编程的进行Http请求的客户端工具,从Spring5.0开始提供 在Spring Boot应用中 1.添加Spring WebFlux依赖 <d

  • Spring Boot配置接口WebMvcConfigurer的实现

    WebMvcConfigurer配置类其实是Spring内部的一种配置方式,采用JavaBean的形式来代替传统的xml配置文件形式进行针对框架个性化定制.基于java-based方式的spring mvc配置,需要创建一个配置类并实现WebMvcConfigurer 接口,WebMvcConfigurerAdapter 抽象类是对WebMvcConfigurer接口的简单抽象(增加了一些默认实现),但在在SpringBoot2.0及Spring5.0中WebMvcConfigurerAdapt

  • springboot集成WebSockets广播消息(推荐)

    一 WebScoketS 简介 RFC 6455 即 webSockets 协议提供了一种标准化的方式去建立全双工,双方面交流的通道在客户端和服务端甚至单一的TCP连接中进行通信: webSockets 协议其跟HTTP的tcp协议不同,但是其设计目的是通过HTTP协议进行工作,可以使用40或者443端口和重新使用现有的防火墙规则: GET /spring-websocket-portfolio/portfolio HTTP/1.1 Host: localhost:8080 Upgrade: w

  • 基于Spring Boot保护Web应用程序

    如果在类路径上添加了Spring Boot Security依赖项,则Spring Boot应用程序会自动为所有HTTP端点提供基本身份验证.端点"/"和"/home"不需要任何身份验证.所有其他端点都需要身份验证. 要将Spring Boot Security添加到Spring Boot应用程序,需要在构建配置文件中添加Spring Boot Starter Security依赖项. Maven用户可以在pom.xml 文件中添加以下依赖项. <depend

  • 使用Spring Boot创建Web应用程序的示例代码

    在这篇文章中,我们将探讨使用Spring Boot创建Web应用程序的细节. 我们将探索Spring Boot如何帮助你加速应用程序开发. 我们将使用Spring Boot构建一个简单的Web应用程序,并为其添加一些有用的服务. 1. 介绍 启动一个新项目的主要挑战之一是该项目的初始设置. 我们需要对不同的目录结构进行调用,并且需要确保我们遵循所有行业标准.对于使用Spring Boot创建Web应用程序,我们需要以下工具: 我们自己喜欢的IDE (我将使用IntelliJ) Maven JDK

  • Spring Boot在Web应用中基于JdbcRealm安全验证过程

    目录 正文 01-RBAC 基于角色的访问控制 02-Shiro 中基于 JdbcRealm 实现用户认证.授权 03-集成到 Spring Boot Web 应用中 04-总结 正文 在安全领域,Subject 用来指代与系统交互的实体,可以是用户.第三方应用等,它是安全认证框架(例如 Shiro)验证的主题. Principal 是 Subject 具有的属性,例如用户名.身份证号.电话号码.邮箱等任何安全验证过程中关心的要素. Primary principal 指能够唯一区分 Subje

  • 详解基于Spring Boot/Spring Session/Redis的分布式Session共享解决方案

    分布式Web网站一般都会碰到集群session共享问题,之前也做过一些Spring3的项目,当时解决这个问题做过两种方案,一是利用nginx,session交给nginx控制,但是这个需要额外工作较多:还有一种是利用一些tomcat上的插件,修改tomcat配置文件,让tomcat自己去把Session放到Redis/Memcached/DB中去.这两种各有优缺,也都能解决问题. 但是现在项目全线Spring Boot,并不自己维护Tomcat,而是由Spring去启动Tomcat.这样就会有一

  • 基于spring boot 的配置参考大全(推荐)

    如下所示: # =================================================================== # COMMON SPRING BOOT PROPERTIES # # This sample file is provided as a guideline. Do NOT copy it in its # entirety to your own application. ^^^ # =============================

  • Spring Boot整合Web项目常用功能详解

    前言 在Web应用开发过程中,一般都涵盖一些常用功能的实现,如数据库访问.异常处理.消息队列.缓存服务.OSS服务,以及接口日志配置,接口文档生成等.如果每个项目都来一套,则既费力又难以维护.可以通过Spring Boot的Starter来将这些常用功能进行整合与集中维护,以达到开箱即用的目的. 项目基于Spring Boot 2.1.5.RELEASE 版. 项目地址 整个项目分为如下几部分: spring-boot-autoconfigure: 具体的各功能实现,每个功能通过package的

  • 基于spring boot 日志(logback)报错的解决方式

    记录一次报错解决方法: No converter found capable of converting from type [java.lang.String] to type [java.util.Map<java.lang.String, java.lang.String>] org.springframework.boot.context.properties.bind.BindException: Failed to bind properties under 'logging.le

  • Spring Boot实现微信小程序登录

    使用Spring Boot完成微信小程序登录 由于微信最近的版本更新,wx.getUserInfo()的这个接口即将失效,将用wx.getUserProfile()替换,所以近期我也对自己的登录进行更新,并且为了巩固学习到的知识,我自己做了一个小demo,在此分享给大家,希望能对大家有所帮助.废话不多说,直接上代码. 前端 .wxml <button class="r" bindtap="bindGetUserInfo">同意</button>

  • 详解基于Spring Boot与Spring Data JPA的多数据源配置

    由于项目需要,最近研究了一下基于spring Boot与Spring Data JPA的多数据源配置问题.以下是传统的单数据源配置代码.这里使用的是Spring的Annotation在代码内部直接配置的方式,没有使用任何XML文件. @Configuration @EnableJpaRepositories(basePackages = "org.lyndon.repository") @EnableTransactionManagement @PropertySource("

  • 基于spring boot 1.5.4 集成 jpa+hibernate+jdbcTemplate(详解)

    1.pom添加依赖 <!-- spring data jpa,会注入tomcat jdbc pool/hibernate等 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <dependency> <

随机推荐