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>

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>

使用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>

現在,需要為Home和hello視圖設置Spring MVC - View控制器。為此,創建一個擴展WebMvcConfigurerAdapter的MVC配置檔。

package com.zaixian.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.zaixian.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示例</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>

最後,更新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>

主 Spring Boot應用程式的代碼如下 -

package com.zaixian.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.zaixian</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>

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.zaixian'
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”之後,可以在target目錄下找到JAR檔。
Gradle用戶可以使用如下所示的命令 -

gradle clean build

在“BUILD SUCCESSFUL”之後,可以在build/libs 目錄下找到JAR檔。

現在,使用下麵顯示的命令運行JAR檔 -

java –jar <JARFILE>

在Web流覽器中訪問URL => http://localhost:8080/ ,將看到如下圖所示。

輸入用戶名和密碼(user/password),然後點擊登錄 -

看到問候語如下:


上一篇: Spring Boot資料庫源(連接資料庫) 下一篇:無