Spring Boot securing Web applications

If you add Spring Boot Security dependency on the class path, Spring Boot application will automatically provide all HTTP basic authentication for the endpoint. Endpoint “/”and “/home”does not require any authentication. All other endpoints require authentication.

To Spring Boot Security Add to Spring Boot application, you need to add Spring Boot Starter Security dependencies in build configuration file.

Maven users can pom.xml to add the following file dependencies.

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

Gradle users can build.gradle add the following file dependencies.

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

Securing Web Applications

First, create a Web application unsafe use Thymeleaf template.
Then, in src / main / resources / templates to create a directory home.htmlfile.

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

Using a simple view Thymeleaf templates defined in the HTML file /hello. Now, src/main/resources/templatescreate a file in the directory: 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

Now, we need to set up Spring MVC and hello to Home View - View controller. To do this, create an extension WebMvcConfigurerAdapterof the MVC configuration file.

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

Now add the Spring Boot Starter security dependencies to build the profile. Maven users can pom.xml to add the following file dependencies.

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

Gradle users can build.gradle add the following file dependencies.

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

Now, create a Web security configuration file, which is used to protect the application to use Basic authentication to access the HTTP endpoint.

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

Now, in src / main / resources to create a directory login.html files to allow users to access via HTTP endpoint login screen.

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

Finally, update hello.html file - allows the user to log off from the application and displays the current user name, as follows -

<!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 Code main application is as follows -

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

Here are the complete code build configuration files.

Maven build file - pom.xml contents are as follows:

<?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 file - 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')
}

Now, create an executable JAR file, and use the following command to run Gradle or Maven Spring Boot application.

Maven users use the command given below -

mvn clean install
Shell

After "BUILD SUCCESS", you can targetfind the JAR file directory.
Gradle user can use the command shown in the following -

gradle clean build

After the "BUILD SUCCESSFUL", can build / libs locate the JAR file directory.

Now, use the following command to run the show JAR file -

java –jar <JARFILE>
Shell

Access the URL in a Web browser => http://localhost:8080/, you will see the following figure.

Enter the user name and password ( user/ password), and then click Login -

Guess you like

Origin www.cnblogs.com/borter/p/12423895.html